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, Score};
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;
33 use core::ops::{Deref, DerefMut};
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, Score = Sc>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, Score = 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: Score<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, Score = 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.lock().deref_mut(), &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 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
111 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
114 /// [`Score`]: crate::routing::scoring::Score
115 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score<ScoreParams = SP>, SP: Sized> {
117 // Maps a channel's short channel id and its direction to the liquidity used up.
118 inflight_htlcs: &'a InFlightHtlcs,
121 impl<'a, S: Score<ScoreParams = SP>, SP: Sized> ScorerAccountingForInFlightHtlcs<'a, S, SP> {
122 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
123 pub fn new(scorer: &'a mut S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
124 ScorerAccountingForInFlightHtlcs {
132 impl<'a, S: Score<ScoreParams = SP>, SP: Sized> Writeable for ScorerAccountingForInFlightHtlcs<'a, S, SP> {
133 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
136 impl<'a, S: Score<ScoreParams = SP>, SP: Sized> Score for ScorerAccountingForInFlightHtlcs<'a, S, SP> {
137 type ScoreParams = S::ScoreParams;
138 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
139 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
140 source, target, short_channel_id
142 let usage = ChannelUsage {
143 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
147 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
149 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
153 fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64) {
154 self.scorer.payment_path_failed(path, short_channel_id)
157 fn payment_path_successful(&mut self, path: &Path) {
158 self.scorer.payment_path_successful(path)
161 fn probe_failed(&mut self, path: &Path, short_channel_id: u64) {
162 self.scorer.probe_failed(path, short_channel_id)
165 fn probe_successful(&mut self, path: &Path) {
166 self.scorer.probe_successful(path)
170 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
171 /// in-use channel liquidity.
173 pub struct InFlightHtlcs(
174 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
175 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
176 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
178 HashMap<(u64, bool), u64>
182 /// Constructs an empty `InFlightHtlcs`.
183 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
185 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
186 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
187 if path.hops.is_empty() { return };
189 let mut cumulative_msat = 0;
190 if let Some(tail) = &path.blinded_tail {
191 cumulative_msat += tail.final_value_msat;
194 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
195 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
196 // the router excludes the payer node. In the following lines, the payer's information is
197 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
198 // in our sliding window of two.
199 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
200 .map(|hop| hop.pubkey)
201 .chain(core::iter::once(payer_node_id));
203 // Taking the reversed vector from above, we zip it with just the reversed hops list to
204 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
205 // the total amount sent.
206 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
207 cumulative_msat += next_hop.fee_msat;
209 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
210 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
211 .or_insert(cumulative_msat);
215 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
217 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
219 .entry((channel_scid, source < target))
220 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
221 .or_insert(used_msat);
224 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
226 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
227 self.0.get(&(channel_scid, source < target)).map(|v| *v)
231 impl Writeable for InFlightHtlcs {
232 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
235 impl Readable for InFlightHtlcs {
236 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
237 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
238 Ok(Self(infight_map))
242 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
243 /// that leads to it.
244 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
245 pub struct RouteHop {
246 /// The node_id of the node at this hop.
247 pub pubkey: PublicKey,
248 /// The node_announcement features of the node at this hop. For the last hop, these may be
249 /// amended to match the features present in the invoice this node generated.
250 pub node_features: NodeFeatures,
251 /// The channel that should be used from the previous hop to reach this node.
252 pub short_channel_id: u64,
253 /// The channel_announcement features of the channel that should be used from the previous hop
254 /// to reach this node.
255 pub channel_features: ChannelFeatures,
256 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
257 /// If this is the last hop in [`Path::hops`]:
258 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
259 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
261 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
263 /// The CLTV delta added for this hop.
264 /// If this is the last hop in [`Path::hops`]:
265 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
266 /// * otherwise, this is the CLTV delta expected at the destination
268 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
269 pub cltv_expiry_delta: u32,
272 impl_writeable_tlv_based!(RouteHop, {
273 (0, pubkey, required),
274 (2, node_features, required),
275 (4, short_channel_id, required),
276 (6, channel_features, required),
277 (8, fee_msat, required),
278 (10, cltv_expiry_delta, required),
281 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
282 /// their [`Bolt12Invoice`].
284 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
285 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
286 pub struct BlindedTail {
287 /// The hops of the [`BlindedPath`] provided by the recipient.
289 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
290 pub hops: Vec<BlindedHop>,
291 /// The blinding point of the [`BlindedPath`] provided by the recipient.
293 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
294 pub blinding_point: PublicKey,
295 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
296 /// inferring the destination. May be 0.
297 pub excess_final_cltv_expiry_delta: u32,
298 /// The total amount paid on this [`Path`], excluding the fees.
299 pub final_value_msat: u64,
302 impl_writeable_tlv_based!(BlindedTail, {
303 (0, hops, required_vec),
304 (2, blinding_point, required),
305 (4, excess_final_cltv_expiry_delta, required),
306 (6, final_value_msat, required),
309 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
310 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
311 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
313 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
314 pub hops: Vec<RouteHop>,
315 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
316 pub blinded_tail: Option<BlindedTail>,
320 /// Gets the fees for a given path, excluding any excess paid to the recipient.
321 pub fn fee_msat(&self) -> u64 {
322 match &self.blinded_tail {
323 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
325 // Do not count last hop of each path since that's the full value of the payment
326 self.hops.split_last().map_or(0,
327 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
332 /// Gets the total amount paid on this [`Path`], excluding the fees.
333 pub fn final_value_msat(&self) -> u64 {
334 match &self.blinded_tail {
335 Some(blinded_tail) => blinded_tail.final_value_msat,
336 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
340 /// Gets the final hop's CLTV expiry delta.
341 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
342 match &self.blinded_tail {
344 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
349 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
350 /// it can take multiple paths. Each path is composed of one or more hops through the network.
351 #[derive(Clone, Hash, PartialEq, Eq)]
353 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
354 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
356 pub paths: Vec<Path>,
357 /// The `payment_params` parameter passed via [`RouteParameters`] to [`find_route`].
359 /// This is used by `ChannelManager` to track information which may be required for retries.
360 pub payment_params: Option<PaymentParameters>,
364 /// Returns the total amount of fees paid on this [`Route`].
366 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
367 /// the amount passed to [`find_route`]'s `route_params.final_value_msat`.
368 pub fn get_total_fees(&self) -> u64 {
369 self.paths.iter().map(|path| path.fee_msat()).sum()
372 /// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
373 /// requested if we had to reach htlc_minimum_msat.
374 pub fn get_total_amount(&self) -> u64 {
375 self.paths.iter().map(|path| path.final_value_msat()).sum()
379 const SERIALIZATION_VERSION: u8 = 1;
380 const MIN_SERIALIZATION_VERSION: u8 = 1;
382 impl Writeable for Route {
383 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
384 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
385 (self.paths.len() as u64).write(writer)?;
386 let mut blinded_tails = Vec::new();
387 for path in self.paths.iter() {
388 (path.hops.len() as u8).write(writer)?;
389 for (idx, hop) in path.hops.iter().enumerate() {
391 if let Some(blinded_tail) = &path.blinded_tail {
392 if blinded_tails.is_empty() {
393 blinded_tails = Vec::with_capacity(path.hops.len());
395 blinded_tails.push(None);
398 blinded_tails.push(Some(blinded_tail));
399 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
402 write_tlv_fields!(writer, {
403 (1, self.payment_params, option),
404 (2, blinded_tails, optional_vec),
410 impl Readable for Route {
411 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
412 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
413 let path_count: u64 = Readable::read(reader)?;
414 if path_count == 0 { return Err(DecodeError::InvalidValue); }
415 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
416 let mut min_final_cltv_expiry_delta = u32::max_value();
417 for _ in 0..path_count {
418 let hop_count: u8 = Readable::read(reader)?;
419 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
420 for _ in 0..hop_count {
421 hops.push(Readable::read(reader)?);
423 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
424 min_final_cltv_expiry_delta =
425 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
426 paths.push(Path { hops, blinded_tail: None });
428 _init_and_read_tlv_fields!(reader, {
429 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
430 (2, blinded_tails, optional_vec),
432 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
433 if blinded_tails.len() != 0 {
434 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
435 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
436 path.blinded_tail = blinded_tail_opt;
439 Ok(Route { paths, payment_params })
443 /// Parameters needed to find a [`Route`].
445 /// Passed to [`find_route`] and [`build_route_from_hops`].
446 #[derive(Clone, Debug, PartialEq, Eq)]
447 pub struct RouteParameters {
448 /// The parameters of the failed payment path.
449 pub payment_params: PaymentParameters,
451 /// The amount in msats sent on the failed payment path.
452 pub final_value_msat: u64,
455 impl Writeable for RouteParameters {
456 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
457 write_tlv_fields!(writer, {
458 (0, self.payment_params, required),
459 (2, self.final_value_msat, required),
460 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
461 // `RouteParameters` directly. For compatibility, we write it here.
462 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
468 impl Readable for RouteParameters {
469 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
470 _init_and_read_tlv_fields!(reader, {
471 (0, payment_params, (required: ReadableArgs, 0)),
472 (2, final_value_msat, required),
473 (4, final_cltv_delta, option),
475 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
476 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
477 if final_cltv_expiry_delta == &0 {
478 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
483 final_value_msat: final_value_msat.0.unwrap(),
488 /// Maximum total CTLV difference we allow for a full payment path.
489 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
491 /// Maximum number of paths we allow an (MPP) payment to have.
492 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
493 // limits, but for now more than 10 paths likely carries too much one-path failure.
494 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
496 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
498 // The median hop CLTV expiry delta currently seen in the network.
499 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
501 // During routing, we only consider paths shorter than our maximum length estimate.
502 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
503 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
504 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
506 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
507 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
508 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
509 // (payment_secret and total_msat) = 93 bytes for the final hop.
510 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
511 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
512 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
514 /// Information used to route a payment.
515 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
516 pub struct PaymentParameters {
517 /// Information about the payee, such as their features and route hints for their channels.
520 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
521 pub expiry_time: Option<u64>,
523 /// The maximum total CLTV delta we accept for the route.
524 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
525 pub max_total_cltv_expiry_delta: u32,
527 /// The maximum number of paths that may be used by (MPP) payments.
528 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
529 pub max_path_count: u8,
531 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
532 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
533 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
534 /// increasing failure probability for those paths.
536 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
537 /// restriction have been found. While paths which meet this criteria will be searched for, it
538 /// is ultimately up to the scorer to select them over other paths.
540 /// A value of 0 will allow payments up to and including a channel's total announced usable
541 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
544 pub max_channel_saturation_power_of_half: u8,
546 /// A list of SCIDs which this payment was previously attempted over and which caused the
547 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
549 pub previously_failed_channels: Vec<u64>,
552 impl Writeable for PaymentParameters {
553 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
554 let mut clear_hints = &vec![];
555 let mut blinded_hints = &vec![];
557 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
558 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
560 write_tlv_fields!(writer, {
561 (0, self.payee.node_id(), option),
562 (1, self.max_total_cltv_expiry_delta, required),
563 (2, self.payee.features(), option),
564 (3, self.max_path_count, required),
565 (4, *clear_hints, required_vec),
566 (5, self.max_channel_saturation_power_of_half, required),
567 (6, self.expiry_time, option),
568 (7, self.previously_failed_channels, required_vec),
569 (8, *blinded_hints, optional_vec),
570 (9, self.payee.final_cltv_expiry_delta(), option),
576 impl ReadableArgs<u32> for PaymentParameters {
577 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
578 _init_and_read_tlv_fields!(reader, {
579 (0, payee_pubkey, option),
580 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
581 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
582 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
583 (4, clear_route_hints, required_vec),
584 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
585 (6, expiry_time, option),
586 (7, previously_failed_channels, optional_vec),
587 (8, blinded_route_hints, optional_vec),
588 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
590 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
591 let payee = if blinded_route_hints.len() != 0 {
592 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
594 route_hints: blinded_route_hints,
595 features: features.and_then(|f: Features| f.bolt12()),
599 route_hints: clear_route_hints,
600 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
601 features: features.and_then(|f| f.bolt11()),
602 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
606 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
607 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
609 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
611 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
617 impl PaymentParameters {
618 /// Creates a payee with the node id of the given `pubkey`.
620 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
622 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
624 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
626 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
627 max_path_count: DEFAULT_MAX_PATH_COUNT,
628 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
629 previously_failed_channels: Vec::new(),
633 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
635 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
638 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
639 /// whether your router will be allowed to find a multi-part route for this payment. If you
640 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
641 /// [`RecipientOnionFields::secret_only`].
643 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
644 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
645 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
646 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
647 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
650 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
651 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
652 /// [`PaymentParameters::expiry_time`].
653 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
654 Self::blinded(invoice.payment_paths().to_vec())
655 .with_bolt12_features(invoice.features().clone()).unwrap()
656 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
659 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
660 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
662 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
664 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
665 max_path_count: DEFAULT_MAX_PATH_COUNT,
666 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
667 previously_failed_channels: Vec::new(),
671 /// Includes the payee's features. Errors if the parameters were not initialized with
672 /// [`PaymentParameters::from_bolt12_invoice`].
674 /// This is not exported to bindings users since bindings don't support move semantics
675 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
677 Payee::Clear { .. } => Err(()),
678 Payee::Blinded { route_hints, .. } =>
679 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
683 /// Includes the payee's features. Errors if the parameters were initialized with
684 /// [`PaymentParameters::from_bolt12_invoice`].
686 /// This is not exported to bindings users since bindings don't support move semantics
687 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
689 Payee::Blinded { .. } => Err(()),
690 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
692 payee: Payee::Clear {
693 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
699 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
700 /// [`PaymentParameters::from_bolt12_invoice`].
702 /// This is not exported to bindings users since bindings don't support move semantics
703 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
705 Payee::Blinded { .. } => Err(()),
706 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
708 payee: Payee::Clear {
709 route_hints, node_id, features, final_cltv_expiry_delta,
715 /// Includes a payment expiration in seconds relative to the UNIX epoch.
717 /// This is not exported to bindings users since bindings don't support move semantics
718 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
719 Self { expiry_time: Some(expiry_time), ..self }
722 /// Includes a limit for the total CLTV expiry delta which is considered during routing
724 /// This is not exported to bindings users since bindings don't support move semantics
725 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
726 Self { max_total_cltv_expiry_delta, ..self }
729 /// Includes a limit for the maximum number of payment paths that may be used.
731 /// This is not exported to bindings users since bindings don't support move semantics
732 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
733 Self { max_path_count, ..self }
736 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
737 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
739 /// This is not exported to bindings users since bindings don't support move semantics
740 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
741 Self { max_channel_saturation_power_of_half, ..self }
745 /// The recipient of a payment, differing based on whether they've hidden their identity with route
747 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
749 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
750 /// will be included in the final [`Route`].
752 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
754 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
755 /// Features supported by the payee.
757 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
759 features: Option<Bolt12InvoiceFeatures>,
761 /// The recipient included these route hints in their BOLT11 invoice.
763 /// The node id of the payee.
765 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
766 route_hints: Vec<RouteHint>,
767 /// Features supported by the payee.
769 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
770 /// does not contain any features.
772 /// [`for_keysend`]: PaymentParameters::for_keysend
773 features: Option<Bolt11InvoiceFeatures>,
774 /// The minimum CLTV delta at the end of the route. This value must not be zero.
775 final_cltv_expiry_delta: u32,
780 fn node_id(&self) -> Option<PublicKey> {
782 Self::Clear { node_id, .. } => Some(*node_id),
786 fn node_features(&self) -> Option<NodeFeatures> {
788 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
789 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
792 fn supports_basic_mpp(&self) -> bool {
794 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
795 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
798 fn features(&self) -> Option<FeaturesRef> {
800 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
801 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
804 fn final_cltv_expiry_delta(&self) -> Option<u32> {
806 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
810 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
812 Self::Blinded { route_hints, .. } => &route_hints[..],
813 Self::Clear { .. } => &[]
817 fn unblinded_route_hints(&self) -> &[RouteHint] {
819 Self::Blinded { .. } => &[],
820 Self::Clear { route_hints, .. } => &route_hints[..]
825 enum FeaturesRef<'a> {
826 Bolt11(&'a Bolt11InvoiceFeatures),
827 Bolt12(&'a Bolt12InvoiceFeatures),
830 Bolt11(Bolt11InvoiceFeatures),
831 Bolt12(Bolt12InvoiceFeatures),
835 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
837 Self::Bolt12(f) => Some(f),
841 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
843 Self::Bolt11(f) => Some(f),
849 impl<'a> Writeable for FeaturesRef<'a> {
850 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
852 Self::Bolt11(f) => Ok(f.write(w)?),
853 Self::Bolt12(f) => Ok(f.write(w)?),
858 impl ReadableArgs<bool> for Features {
859 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
860 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
861 Ok(Self::Bolt12(Readable::read(reader)?))
865 /// A list of hops along a payment path terminating with a channel to the recipient.
866 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
867 pub struct RouteHint(pub Vec<RouteHintHop>);
869 impl Writeable for RouteHint {
870 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
871 (self.0.len() as u64).write(writer)?;
872 for hop in self.0.iter() {
879 impl Readable for RouteHint {
880 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
881 let hop_count: u64 = Readable::read(reader)?;
882 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
883 for _ in 0..hop_count {
884 hops.push(Readable::read(reader)?);
890 /// A channel descriptor for a hop along a payment path.
891 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
892 pub struct RouteHintHop {
893 /// The node_id of the non-target end of the route
894 pub src_node_id: PublicKey,
895 /// The short_channel_id of this channel
896 pub short_channel_id: u64,
897 /// The fees which must be paid to use this channel
898 pub fees: RoutingFees,
899 /// The difference in CLTV values between this node and the next node.
900 pub cltv_expiry_delta: u16,
901 /// The minimum value, in msat, which must be relayed to the next hop.
902 pub htlc_minimum_msat: Option<u64>,
903 /// The maximum value in msat available for routing with a single HTLC.
904 pub htlc_maximum_msat: Option<u64>,
907 impl_writeable_tlv_based!(RouteHintHop, {
908 (0, src_node_id, required),
909 (1, htlc_minimum_msat, option),
910 (2, short_channel_id, required),
911 (3, htlc_maximum_msat, option),
913 (6, cltv_expiry_delta, required),
916 #[derive(Eq, PartialEq)]
917 struct RouteGraphNode {
919 lowest_fee_to_node: u64,
920 total_cltv_delta: u32,
921 // The maximum value a yet-to-be-constructed payment path might flow through this node.
922 // This value is upper-bounded by us by:
923 // - how much is needed for a path being constructed
924 // - how much value can channels following this node (up to the destination) can contribute,
925 // considering their capacity and fees
926 value_contribution_msat: u64,
927 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
928 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
929 path_htlc_minimum_msat: u64,
930 /// All penalties incurred from this hop on the way to the destination, as calculated using
932 path_penalty_msat: u64,
933 /// The number of hops walked up to this node.
934 path_length_to_node: u8,
937 impl cmp::Ord for RouteGraphNode {
938 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
939 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
940 .saturating_add(other.path_penalty_msat);
941 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
942 .saturating_add(self.path_penalty_msat);
943 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
947 impl cmp::PartialOrd for RouteGraphNode {
948 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
949 Some(self.cmp(other))
953 /// A wrapper around the various hop representations.
955 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
956 #[derive(Clone, Debug)]
957 enum CandidateRouteHop<'a> {
958 /// A hop from the payer, where the outbound liquidity is known.
960 details: &'a ChannelDetails,
962 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
964 info: DirectedChannelInfo<'a>,
965 short_channel_id: u64,
967 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
970 hint: &'a RouteHintHop,
972 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
974 hint: &'a (BlindedPayInfo, BlindedPath),
977 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
978 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
979 /// introduction node and the destination. Useful for tracking that we need to include a blinded
980 /// path at the end of our [`Route`].
982 hint: &'a (BlindedPayInfo, BlindedPath),
987 impl<'a> CandidateRouteHop<'a> {
988 fn short_channel_id(&self) -> Option<u64> {
990 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
991 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
992 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
993 CandidateRouteHop::Blinded { .. } => None,
994 CandidateRouteHop::OneHopBlinded { .. } => None,
998 // NOTE: This may alloc memory so avoid calling it in a hot code path.
999 fn features(&self) -> ChannelFeatures {
1001 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
1002 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1003 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1004 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1005 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1009 fn cltv_expiry_delta(&self) -> u32 {
1011 CandidateRouteHop::FirstHop { .. } => 0,
1012 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1013 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1014 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1015 CandidateRouteHop::OneHopBlinded { .. } => 0,
1019 fn htlc_minimum_msat(&self) -> u64 {
1021 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1022 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1023 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1024 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1025 CandidateRouteHop::OneHopBlinded { .. } => 0,
1029 fn fees(&self) -> RoutingFees {
1031 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1032 base_msat: 0, proportional_millionths: 0,
1034 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1035 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1036 CandidateRouteHop::Blinded { hint, .. } => {
1038 base_msat: hint.0.fee_base_msat,
1039 proportional_millionths: hint.0.fee_proportional_millionths
1042 CandidateRouteHop::OneHopBlinded { .. } =>
1043 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1047 fn effective_capacity(&self) -> EffectiveCapacity {
1049 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1050 liquidity_msat: details.next_outbound_htlc_limit_msat,
1052 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1053 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1054 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1055 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1056 EffectiveCapacity::Infinite,
1057 CandidateRouteHop::Blinded { hint, .. } =>
1058 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1059 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1063 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1065 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1066 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1067 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1070 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1072 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1080 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1081 enum CandidateHopId {
1082 /// Contains (scid, src_node_id < target_node_id)
1084 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1089 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1090 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1092 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1093 EffectiveCapacity::Infinite => u64::max_value(),
1094 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1095 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1096 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1097 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1098 // expected to have been generated from up-to-date capacity information.
1099 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1100 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1101 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1105 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1106 -> bool where I1::Item: PartialEq<I2::Item> {
1108 let a = iter_a.next();
1109 let b = iter_b.next();
1110 if a.is_none() && b.is_none() { return true; }
1111 if a.is_none() || b.is_none() { return false; }
1112 if a.unwrap().ne(&b.unwrap()) { return false; }
1116 /// It's useful to keep track of the hops associated with the fees required to use them,
1117 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1118 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1119 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1121 struct PathBuildingHop<'a> {
1122 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1123 // is a larger refactor and will require careful performance analysis.
1125 candidate: CandidateRouteHop<'a>,
1128 /// All the fees paid *after* this channel on the way to the destination
1129 next_hops_fee_msat: u64,
1130 /// Fee paid for the use of the current channel (see candidate.fees()).
1131 /// The value will be actually deducted from the counterparty balance on the previous link.
1132 hop_use_fee_msat: u64,
1133 /// Used to compare channels when choosing the for routing.
1134 /// Includes paying for the use of a hop and the following hops, as well as
1135 /// an estimated cost of reaching this hop.
1136 /// Might get stale when fees are recomputed. Primarily for internal use.
1137 total_fee_msat: u64,
1138 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1139 /// walk and may be invalid thereafter.
1140 path_htlc_minimum_msat: u64,
1141 /// All penalties incurred from this channel on the way to the destination, as calculated using
1142 /// channel scoring.
1143 path_penalty_msat: u64,
1144 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1145 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1146 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1147 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1148 /// avoid processing them again.
1149 was_processed: bool,
1150 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1151 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1152 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1153 // value_contribution_msat, which requires tracking it here. See comments below where it is
1154 // used for more info.
1155 value_contribution_msat: u64,
1158 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1159 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1160 let mut debug_struct = f.debug_struct("PathBuildingHop");
1162 .field("node_id", &self.node_id)
1163 .field("short_channel_id", &self.candidate.short_channel_id())
1164 .field("total_fee_msat", &self.total_fee_msat)
1165 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1166 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1167 .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)))
1168 .field("path_penalty_msat", &self.path_penalty_msat)
1169 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1170 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1171 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1172 let debug_struct = debug_struct
1173 .field("value_contribution_msat", &self.value_contribution_msat);
1174 debug_struct.finish()
1178 // Instantiated with a list of hops with correct data in them collected during path finding,
1179 // an instance of this struct should be further modified only via given methods.
1181 struct PaymentPath<'a> {
1182 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1185 impl<'a> PaymentPath<'a> {
1186 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1187 fn get_value_msat(&self) -> u64 {
1188 self.hops.last().unwrap().0.fee_msat
1191 fn get_path_penalty_msat(&self) -> u64 {
1192 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1195 fn get_total_fee_paid_msat(&self) -> u64 {
1196 if self.hops.len() < 1 {
1200 // Can't use next_hops_fee_msat because it gets outdated.
1201 for (i, (hop, _)) in self.hops.iter().enumerate() {
1202 if i != self.hops.len() - 1 {
1203 result += hop.fee_msat;
1209 fn get_cost_msat(&self) -> u64 {
1210 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1213 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1214 // to change fees may result in an inconsistency.
1216 // Sometimes we call this function right after constructing a path which is inconsistent in
1217 // that it the value being transferred has decreased while we were doing path finding, leading
1218 // to the fees being paid not lining up with the actual limits.
1220 // Note that this function is not aware of the available_liquidity limit, and thus does not
1221 // support increasing the value being transferred beyond what was selected during the initial
1223 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1224 let mut total_fee_paid_msat = 0 as u64;
1225 for i in (0..self.hops.len()).rev() {
1226 let last_hop = i == self.hops.len() - 1;
1228 // For non-last-hop, this value will represent the fees paid on the current hop. It
1229 // will consist of the fees for the use of the next hop, and extra fees to match
1230 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1231 let mut cur_hop_fees_msat = 0;
1233 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1236 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1237 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1238 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1239 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1240 // set it too high just to maliciously take more fees by exploiting this
1241 // match htlc_minimum_msat logic.
1242 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1243 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1244 // Note that there is a risk that *previous hops* (those closer to us, as we go
1245 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1247 // This might make us end up with a broken route, although this should be super-rare
1248 // in practice, both because of how healthy channels look like, and how we pick
1249 // channels in add_entry.
1250 // Also, this can't be exploited more heavily than *announce a free path and fail
1252 cur_hop_transferred_amount_msat += extra_fees_msat;
1253 total_fee_paid_msat += extra_fees_msat;
1254 cur_hop_fees_msat += extra_fees_msat;
1258 // Final hop is a special case: it usually has just value_msat (by design), but also
1259 // it still could overpay for the htlc_minimum_msat.
1260 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1262 // Propagate updated fees for the use of the channels to one hop back, where they
1263 // will be actually paid (fee_msat). The last hop is handled above separately.
1264 cur_hop.fee_msat = cur_hop_fees_msat;
1267 // Fee for the use of the current hop which will be deducted on the previous hop.
1268 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1269 // this channel is free for us.
1271 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1272 cur_hop.hop_use_fee_msat = new_fee;
1273 total_fee_paid_msat += new_fee;
1275 // It should not be possible because this function is called only to reduce the
1276 // value. In that case, compute_fee was already called with the same fees for
1277 // larger amount and there was no overflow.
1286 /// Calculate the fees required to route the given amount over a channel with the given fees.
1287 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1288 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1289 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1293 /// Calculate the fees required to route the given amount over a channel with the given fees,
1294 /// saturating to [`u64::max_value`].
1295 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1296 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1297 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1298 .saturating_add(channel_fees.base_msat as u64)
1301 /// The default `features` we assume for a node in a route, when no `features` are known about that
1304 /// Default features are:
1305 /// * variable_length_onion_optional
1306 fn default_node_features() -> NodeFeatures {
1307 let mut features = NodeFeatures::empty();
1308 features.set_variable_length_onion_optional();
1312 struct LoggedPayeePubkey(Option<PublicKey>);
1313 impl fmt::Display for LoggedPayeePubkey {
1314 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1317 "payee node id ".fmt(f)?;
1321 "blinded payee".fmt(f)
1327 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1328 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1329 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1331 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1332 "blinded route hint with introduction node id ".fmt(f)?;
1333 hint.1.introduction_node_id.fmt(f)?;
1334 " and blinding point ".fmt(f)?;
1335 hint.1.blinding_point.fmt(f)
1337 CandidateRouteHop::FirstHop { .. } => {
1338 "first hop with SCID ".fmt(f)?;
1339 self.0.short_channel_id().unwrap().fmt(f)
1341 CandidateRouteHop::PrivateHop { .. } => {
1342 "route hint with SCID ".fmt(f)?;
1343 self.0.short_channel_id().unwrap().fmt(f)
1347 self.0.short_channel_id().unwrap().fmt(f)
1354 fn sort_first_hop_channels(
1355 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1356 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1358 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1359 // most like to use.
1361 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1362 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1365 // Second, because simply always sorting in descending order would always use our largest
1366 // available outbound capacity, needlessly fragmenting our available channel capacities,
1367 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1368 // which have enough, but not too much, capacity for the payment.
1370 // Available outbound balances factor in liquidity already reserved for previously found paths.
1371 channels.sort_unstable_by(|chan_a, chan_b| {
1372 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1373 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1374 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1375 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1376 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1377 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1378 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1379 // Sort in descending order
1380 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1382 // Sort in ascending order
1383 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1388 /// Finds a route from us (payer) to the given target node (payee).
1390 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1391 /// in the given [`RouteParameters::payment_params`].
1392 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1394 /// Private routing paths between a public node and the target may be included in the `payee` field
1395 /// of [`RouteParameters::payment_params`].
1397 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1398 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1399 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1401 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1402 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1403 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1407 /// Panics if first_hops contains channels without `short_channel_id`s;
1408 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1410 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1411 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1412 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1413 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1414 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1415 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1416 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1417 ) -> Result<Route, LightningError>
1418 where L::Target: Logger, GL::Target: Logger {
1419 let graph_lock = network_graph.read_only();
1420 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1421 route_params.final_value_msat, logger, scorer, score_params,
1422 random_seed_bytes)?;
1423 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1427 pub(crate) fn get_route<L: Deref, S: Score>(
1428 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1429 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, logger: L, scorer: &S, score_params: &S::ScoreParams,
1430 _random_seed_bytes: &[u8; 32]
1431 ) -> Result<Route, LightningError>
1432 where L::Target: Logger {
1433 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1434 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1435 // so use a dummy id for this in the blinded case.
1436 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1437 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1438 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1439 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1440 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1442 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1443 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1446 if final_value_msat > MAX_VALUE_MSAT {
1447 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1450 if final_value_msat == 0 {
1451 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1454 match &payment_params.payee {
1455 Payee::Clear { route_hints, node_id, .. } => {
1456 for route in route_hints.iter() {
1457 for hop in &route.0 {
1458 if hop.src_node_id == *node_id {
1459 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1464 Payee::Blinded { route_hints, .. } => {
1465 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1466 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});
1468 for (_, blinded_path) in route_hints.iter() {
1469 if blinded_path.blinded_hops.len() == 0 {
1470 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1471 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1472 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1473 } else if blinded_path.blinded_hops.len() == 1 &&
1474 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1475 && p.introduction_node_id != blinded_path.introduction_node_id)
1477 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1482 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1483 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1484 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});
1487 // The general routing idea is the following:
1488 // 1. Fill first/last hops communicated by the caller.
1489 // 2. Attempt to construct a path from payer to payee for transferring
1490 // any ~sufficient (described later) value.
1491 // If succeed, remember which channels were used and how much liquidity they have available,
1492 // so that future paths don't rely on the same liquidity.
1493 // 3. Proceed to the next step if:
1494 // - we hit the recommended target value;
1495 // - OR if we could not construct a new path. Any next attempt will fail too.
1496 // Otherwise, repeat step 2.
1497 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1498 // (not recommended value).
1499 // 5. If yes, proceed. If not, fail routing.
1500 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1501 // transferred up to the transfer target value.
1502 // 7. Reduce the value of the last path until we are sending only the target value.
1503 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1504 // them so that we're not sending two HTLCs along the same path.
1506 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1507 // distance from the payee
1509 // We are not a faithful Dijkstra's implementation because we can change values which impact
1510 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1511 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1512 // the value we are currently attempting to send over a path, we simply reduce the value being
1513 // sent along the path for any hops after that channel. This may imply that later fees (which
1514 // we've already tabulated) are lower because a smaller value is passing through the channels
1515 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1516 // channels which were selected earlier (and which may still be used for other paths without a
1517 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1520 // One potentially problematic case for this algorithm would be if there are many
1521 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1522 // graph walking), we may never find a path which is not liquidity-limited and has lower
1523 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1524 // Because we only consider paths with at least 5% of the total value being sent, the damage
1525 // from such a case should be limited, however this could be further reduced in the future by
1526 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1527 // limits for the purposes of fee calculation.
1529 // Alternatively, we could store more detailed path information in the heap (targets, below)
1530 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1531 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1532 // and practically (as we would need to store dynamically-allocated path information in heap
1533 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1534 // results of such an algorithm would likely be biased towards lower-value paths.
1536 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1537 // outside of our current search value, running a path search more times to gather candidate
1538 // paths at different values. While this may be acceptable, further path searches may increase
1539 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1540 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1541 // the same time, remaining generic across different payment values.
1543 let network_channels = network_graph.channels();
1544 let network_nodes = network_graph.nodes();
1546 if payment_params.max_path_count == 0 {
1547 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1550 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1551 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1553 let allow_mpp = if payment_params.max_path_count == 1 {
1555 } else if payment_params.payee.supports_basic_mpp() {
1557 } else if let Some(payee) = payee_node_id_opt {
1558 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1559 |info| info.features.supports_basic_mpp()))
1562 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1563 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1564 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1567 // Prepare the data we'll use for payee-to-payer search by
1568 // inserting first hops suggested by the caller as targets.
1569 // Our search will then attempt to reach them while traversing from the payee node.
1570 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1571 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1572 if let Some(hops) = first_hops {
1574 if chan.get_outbound_payment_scid().is_none() {
1575 panic!("first_hops should be filled in with usable channels, not pending ones");
1577 if chan.counterparty.node_id == *our_node_pubkey {
1578 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1581 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1582 .or_insert(Vec::new())
1585 if first_hop_targets.is_empty() {
1586 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1590 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1591 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1592 // adding duplicate entries when we find a better path to a given node.
1593 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1595 // Map from node_id to information about the best current path to that node, including feerate
1597 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1599 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1600 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1601 // htlc_minimum with extra fees while still finding a cheaper path.
1602 let mut hit_minimum_limit;
1604 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1605 // We start with a path_value of the exact amount we want, and if that generates a route we may
1606 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1607 // amount we want in total across paths, selecting the best subset at the end.
1608 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1609 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1610 let mut path_value_msat = final_value_msat;
1612 // Routing Fragmentation Mitigation heuristic:
1614 // Routing fragmentation across many payment paths increases the overall routing
1615 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1616 // Taking too many smaller paths also increases the chance of payment failure.
1617 // Thus to avoid this effect, we require from our collected links to provide
1618 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1619 // This requirement is currently set to be 1/max_path_count of the payment
1620 // value to ensure we only ever return routes that do not violate this limit.
1621 let minimal_value_contribution_msat: u64 = if allow_mpp {
1622 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1627 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1628 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1629 // drop the requirement by setting this to 0.
1630 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1632 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1633 // determine if the channel can be used by additional MPP paths or to inform path finding
1634 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1635 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1637 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1638 HashMap::with_capacity(network_nodes.len());
1640 // Keeping track of how much value we already collected across other paths. Helps to decide
1641 // when we want to stop looking for new paths.
1642 let mut already_collected_value_msat = 0;
1644 for (_, channels) in first_hop_targets.iter_mut() {
1645 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1649 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1650 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1652 // Remember how many candidates we ignored to allow for some logging afterwards.
1653 let mut num_ignored_value_contribution = 0;
1654 let mut num_ignored_path_length_limit = 0;
1655 let mut num_ignored_cltv_delta_limit = 0;
1656 let mut num_ignored_previously_failed = 0;
1658 macro_rules! add_entry {
1659 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1660 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1661 // since that value has to be transferred over this channel.
1662 // Returns whether this channel caused an update to `targets`.
1663 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1664 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1665 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1666 // We "return" whether we updated the path at the end, and how much we can route via
1667 // this channel, via this:
1668 let mut did_add_update_path_to_src_node = None;
1669 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1670 // practice these cases should be caught earlier:
1671 // - for regular channels at channel announcement (TODO)
1672 // - for first and last hops early in get_route
1673 if $src_node_id != $dest_node_id {
1674 let scid_opt = $candidate.short_channel_id();
1675 let effective_capacity = $candidate.effective_capacity();
1676 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1678 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1679 // It may be misleading because we might later choose to reduce the value transferred
1680 // over these channels, and the channel which was insufficient might become sufficient.
1681 // Worst case: we drop a good channel here because it can't cover the high following
1682 // fees caused by one expensive channel, but then this channel could have been used
1683 // if the amount being transferred over this path is lower.
1684 // We do this for now, but this is a subject for removal.
1685 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1686 let used_liquidity_msat = used_liquidities
1687 .get(&$candidate.id($src_node_id < $dest_node_id))
1688 .map_or(0, |used_liquidity_msat| {
1689 available_value_contribution_msat = available_value_contribution_msat
1690 .saturating_sub(*used_liquidity_msat);
1691 *used_liquidity_msat
1694 // Verify the liquidity offered by this channel complies to the minimal contribution.
1695 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1696 // Do not consider candidate hops that would exceed the maximum path length.
1697 let path_length_to_node = $next_hops_path_length + 1;
1698 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1700 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1701 // In order to already account for some of the privacy enhancing random CLTV
1702 // expiry delta offset we add on top later, we subtract a rough estimate
1703 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1704 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1705 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1706 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1707 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1708 .saturating_add($candidate.cltv_expiry_delta());
1709 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1711 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1712 // Includes paying fees for the use of the following channels.
1713 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1714 Some(result) => result,
1715 // Can't overflow due to how the values were computed right above.
1716 None => unreachable!(),
1718 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1719 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1720 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1722 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1723 let may_overpay_to_meet_path_minimum_msat =
1724 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1725 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1726 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1727 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1729 let payment_failed_on_this_channel = scid_opt.map_or(false,
1730 |scid| payment_params.previously_failed_channels.contains(&scid));
1732 let should_log_candidate = match $candidate {
1733 CandidateRouteHop::FirstHop { .. } => true,
1734 CandidateRouteHop::PrivateHop { .. } => true,
1735 CandidateRouteHop::Blinded { .. } => true,
1739 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1740 // bother considering this channel. If retrying with recommended_value_msat may
1741 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1742 // around again with a higher amount.
1743 if !contributes_sufficient_value {
1744 if should_log_candidate {
1745 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1747 num_ignored_value_contribution += 1;
1748 } else if exceeds_max_path_length {
1749 if should_log_candidate {
1750 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1752 num_ignored_path_length_limit += 1;
1753 } else if exceeds_cltv_delta_limit {
1754 if should_log_candidate {
1755 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1757 num_ignored_cltv_delta_limit += 1;
1758 } else if payment_failed_on_this_channel {
1759 if should_log_candidate {
1760 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1762 num_ignored_previously_failed += 1;
1763 } else if may_overpay_to_meet_path_minimum_msat {
1764 hit_minimum_limit = true;
1765 } else if over_path_minimum_msat {
1766 // Note that low contribution here (limited by available_liquidity_msat)
1767 // might violate htlc_minimum_msat on the hops which are next along the
1768 // payment path (upstream to the payee). To avoid that, we recompute
1769 // path fees knowing the final path contribution after constructing it.
1770 let path_htlc_minimum_msat = cmp::max(
1771 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1772 .saturating_add($next_hops_path_htlc_minimum_msat),
1773 $candidate.htlc_minimum_msat());
1774 let hm_entry = dist.entry($src_node_id);
1775 let old_entry = hm_entry.or_insert_with(|| {
1776 // If there was previously no known way to access the source node
1777 // (recall it goes payee-to-payer) of short_channel_id, first add a
1778 // semi-dummy record just to compute the fees to reach the source node.
1779 // This will affect our decision on selecting short_channel_id
1780 // as a way to reach the $dest_node_id.
1782 node_id: $dest_node_id.clone(),
1783 candidate: $candidate.clone(),
1785 next_hops_fee_msat: u64::max_value(),
1786 hop_use_fee_msat: u64::max_value(),
1787 total_fee_msat: u64::max_value(),
1788 path_htlc_minimum_msat,
1789 path_penalty_msat: u64::max_value(),
1790 was_processed: false,
1791 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1792 value_contribution_msat,
1796 #[allow(unused_mut)] // We only use the mut in cfg(test)
1797 let mut should_process = !old_entry.was_processed;
1798 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1800 // In test/fuzzing builds, we do extra checks to make sure the skipping
1801 // of already-seen nodes only happens in cases we expect (see below).
1802 if !should_process { should_process = true; }
1806 let mut hop_use_fee_msat = 0;
1807 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1809 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1810 // will have the same effective-fee
1811 if $src_node_id != our_node_id {
1812 // Note that `u64::max_value` means we'll always fail the
1813 // `old_entry.total_fee_msat > total_fee_msat` check below
1814 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1815 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1818 let channel_usage = ChannelUsage {
1819 amount_msat: amount_to_transfer_over_msat,
1820 inflight_htlc_msat: used_liquidity_msat,
1823 let channel_penalty_msat = scid_opt.map_or(0,
1824 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1825 channel_usage, score_params));
1826 let path_penalty_msat = $next_hops_path_penalty_msat
1827 .saturating_add(channel_penalty_msat);
1828 let new_graph_node = RouteGraphNode {
1829 node_id: $src_node_id,
1830 lowest_fee_to_node: total_fee_msat,
1831 total_cltv_delta: hop_total_cltv_delta,
1832 value_contribution_msat,
1833 path_htlc_minimum_msat,
1835 path_length_to_node,
1838 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1839 // if this way is cheaper than the already known
1840 // (considering the cost to "reach" this channel from the route destination,
1841 // the cost of using this channel,
1842 // and the cost of routing to the source node of this channel).
1843 // Also, consider that htlc_minimum_msat_difference, because we might end up
1844 // paying it. Consider the following exploit:
1845 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1846 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1847 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1848 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1850 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1851 // but it may require additional tracking - we don't want to double-count
1852 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1853 // can't use something that may decrease on future hops.
1854 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1855 .saturating_add(old_entry.path_penalty_msat);
1856 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1857 .saturating_add(path_penalty_msat);
1859 if !old_entry.was_processed && new_cost < old_cost {
1860 targets.push(new_graph_node);
1861 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1862 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1863 old_entry.total_fee_msat = total_fee_msat;
1864 old_entry.node_id = $dest_node_id.clone();
1865 old_entry.candidate = $candidate.clone();
1866 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1867 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1868 old_entry.path_penalty_msat = path_penalty_msat;
1869 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1871 old_entry.value_contribution_msat = value_contribution_msat;
1873 did_add_update_path_to_src_node = Some(value_contribution_msat);
1874 } else if old_entry.was_processed && new_cost < old_cost {
1875 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1877 // If we're skipping processing a node which was previously
1878 // processed even though we found another path to it with a
1879 // cheaper fee, check that it was because the second path we
1880 // found (which we are processing now) has a lower value
1881 // contribution due to an HTLC minimum limit.
1883 // e.g. take a graph with two paths from node 1 to node 2, one
1884 // through channel A, and one through channel B. Channel A and
1885 // B are both in the to-process heap, with their scores set by
1886 // a higher htlc_minimum than fee.
1887 // Channel A is processed first, and the channels onwards from
1888 // node 1 are added to the to-process heap. Thereafter, we pop
1889 // Channel B off of the heap, note that it has a much more
1890 // restrictive htlc_maximum_msat, and recalculate the fees for
1891 // all of node 1's channels using the new, reduced, amount.
1893 // This would be bogus - we'd be selecting a higher-fee path
1894 // with a lower htlc_maximum_msat instead of the one we'd
1895 // already decided to use.
1896 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1898 value_contribution_msat + path_penalty_msat <
1899 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1907 did_add_update_path_to_src_node
1911 let default_node_features = default_node_features();
1913 // Find ways (channels with destination) to reach a given node and store them
1914 // in the corresponding data structures (routing graph etc).
1915 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1916 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1917 // This data can later be helpful to optimize routing (pay lower fees).
1918 macro_rules! add_entries_to_cheapest_to_target_node {
1919 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1920 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1921 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1922 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1923 let was_processed = elem.was_processed;
1924 elem.was_processed = true;
1927 // Entries are added to dist in add_entry!() when there is a channel from a node.
1928 // Because there are no channels from payee, it will not have a dist entry at this point.
1929 // If we're processing any other node, it is always be the result of a channel from it.
1930 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1935 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1936 for details in first_channels {
1937 let candidate = CandidateRouteHop::FirstHop { details };
1938 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1939 $next_hops_value_contribution,
1940 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1941 $next_hops_cltv_delta, $next_hops_path_length);
1945 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1948 &default_node_features
1951 if !features.requires_unknown_bits() {
1952 for chan_id in $node.channels.iter() {
1953 let chan = network_channels.get(chan_id).unwrap();
1954 if !chan.features.requires_unknown_bits() {
1955 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1956 if first_hops.is_none() || *source != our_node_id {
1957 if directed_channel.direction().enabled {
1958 let candidate = CandidateRouteHop::PublicHop {
1959 info: directed_channel,
1960 short_channel_id: *chan_id,
1962 add_entry!(candidate, *source, $node_id,
1963 $fee_to_target_msat,
1964 $next_hops_value_contribution,
1965 $next_hops_path_htlc_minimum_msat,
1966 $next_hops_path_penalty_msat,
1967 $next_hops_cltv_delta, $next_hops_path_length);
1978 let mut payment_paths = Vec::<PaymentPath>::new();
1980 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1981 'paths_collection: loop {
1982 // For every new path, start from scratch, except for used_liquidities, which
1983 // helps to avoid reusing previously selected paths in future iterations.
1986 hit_minimum_limit = false;
1988 // If first hop is a private channel and the only way to reach the payee, this is the only
1989 // place where it could be added.
1990 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
1991 for details in first_channels {
1992 let candidate = CandidateRouteHop::FirstHop { details };
1993 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
1994 0, 0u64, 0, 0).is_some();
1995 log_trace!(logger, "{} direct route to payee via {}",
1996 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2000 // Add the payee as a target, so that the payee-to-payer
2001 // search algorithm knows what to start with.
2002 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2003 // The payee is not in our network graph, so nothing to add here.
2004 // There is still a chance of reaching them via last_hops though,
2005 // so don't yet fail the payment here.
2006 // If not, targets.pop() will not even let us enter the loop in step 2.
2009 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2014 // If a caller provided us with last hops, add them to routing targets. Since this happens
2015 // earlier than general path finding, they will be somewhat prioritized, although currently
2016 // it matters only if the fees are exactly the same.
2017 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2018 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2019 let have_intro_node_in_graph =
2020 // Only add the hops in this route to our candidate set if either
2021 // we have a direct channel to the first hop or the first hop is
2022 // in the regular network graph.
2023 first_hop_targets.get(&intro_node_id).is_some() ||
2024 network_nodes.get(&intro_node_id).is_some();
2025 if !have_intro_node_in_graph { continue }
2026 let candidate = if hint.1.blinded_hops.len() == 1 {
2027 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2028 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2029 let mut path_contribution_msat = path_value_msat;
2030 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2031 0, path_contribution_msat, 0, 0_u64, 0, 0)
2033 path_contribution_msat = hop_used_msat;
2035 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2036 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2038 for details in first_channels {
2039 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2040 add_entry!(first_hop_candidate, our_node_id, intro_node_id, 0, path_contribution_msat, 0,
2045 for route in payment_params.payee.unblinded_route_hints().iter()
2046 .filter(|route| !route.0.is_empty())
2048 let first_hop_in_route = &(route.0)[0];
2049 let have_hop_src_in_graph =
2050 // Only add the hops in this route to our candidate set if either
2051 // we have a direct channel to the first hop or the first hop is
2052 // in the regular network graph.
2053 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2054 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2055 if have_hop_src_in_graph {
2056 // We start building the path from reverse, i.e., from payee
2057 // to the first RouteHintHop in the path.
2058 let hop_iter = route.0.iter().rev();
2059 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2060 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2061 let mut hop_used = true;
2062 let mut aggregate_next_hops_fee_msat: u64 = 0;
2063 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2064 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2065 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2066 let mut aggregate_next_hops_path_length: u8 = 0;
2067 let mut aggregate_path_contribution_msat = path_value_msat;
2069 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2070 let source = NodeId::from_pubkey(&hop.src_node_id);
2071 let target = NodeId::from_pubkey(&prev_hop_id);
2072 let candidate = network_channels
2073 .get(&hop.short_channel_id)
2074 .and_then(|channel| channel.as_directed_to(&target))
2075 .map(|(info, _)| CandidateRouteHop::PublicHop {
2077 short_channel_id: hop.short_channel_id,
2079 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2081 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2082 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2083 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2084 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2086 aggregate_path_contribution_msat = hop_used_msat;
2088 // If this hop was not used then there is no use checking the preceding
2089 // hops in the RouteHint. We can break by just searching for a direct
2090 // channel between last checked hop and first_hop_targets.
2094 let used_liquidity_msat = used_liquidities
2095 .get(&candidate.id(source < target)).copied()
2097 let channel_usage = ChannelUsage {
2098 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2099 inflight_htlc_msat: used_liquidity_msat,
2100 effective_capacity: candidate.effective_capacity(),
2102 let channel_penalty_msat = scorer.channel_penalty_msat(
2103 hop.short_channel_id, &source, &target, channel_usage, score_params
2105 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2106 .saturating_add(channel_penalty_msat);
2108 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2109 .saturating_add(hop.cltv_expiry_delta as u32);
2111 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2114 // Searching for a direct channel between last checked hop and first_hop_targets
2115 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2116 sort_first_hop_channels(first_channels, &used_liquidities,
2117 recommended_value_msat, our_node_pubkey);
2118 for details in first_channels {
2119 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2120 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2121 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2122 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2123 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2131 // In the next values of the iterator, the aggregate fees already reflects
2132 // the sum of value sent from payer (final_value_msat) and routing fees
2133 // for the last node in the RouteHint. We need to just add the fees to
2134 // route through the current node so that the preceding node (next iteration)
2136 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2137 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2138 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2140 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2141 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2142 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2143 .checked_add(hop_htlc_minimum_msat_inc);
2144 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2146 if idx == route.0.len() - 1 {
2147 // The last hop in this iterator is the first hop in
2148 // overall RouteHint.
2149 // If this hop connects to a node with which we have a direct channel,
2150 // ignore the network graph and, if the last hop was added, add our
2151 // direct channel to the candidate set.
2153 // Note that we *must* check if the last hop was added as `add_entry`
2154 // always assumes that the third argument is a node to which we have a
2156 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2157 sort_first_hop_channels(first_channels, &used_liquidities,
2158 recommended_value_msat, our_node_pubkey);
2159 for details in first_channels {
2160 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2161 add_entry!(first_hop_candidate, our_node_id,
2162 NodeId::from_pubkey(&hop.src_node_id),
2163 aggregate_next_hops_fee_msat,
2164 aggregate_path_contribution_msat,
2165 aggregate_next_hops_path_htlc_minimum_msat,
2166 aggregate_next_hops_path_penalty_msat,
2167 aggregate_next_hops_cltv_delta,
2168 aggregate_next_hops_path_length);
2176 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2178 // At this point, targets are filled with the data from first and
2179 // last hops communicated by the caller, and the payment receiver.
2180 let mut found_new_path = false;
2183 // If this loop terminates due the exhaustion of targets, two situations are possible:
2184 // - not enough outgoing liquidity:
2185 // 0 < already_collected_value_msat < final_value_msat
2186 // - enough outgoing liquidity:
2187 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2188 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2189 // paths_collection will be stopped because found_new_path==false.
2190 // This is not necessarily a routing failure.
2191 '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() {
2193 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2194 // traversing the graph and arrange the path out of what we found.
2195 if node_id == our_node_id {
2196 let mut new_entry = dist.remove(&our_node_id).unwrap();
2197 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2200 let mut features_set = false;
2201 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2202 for details in first_channels {
2203 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2204 if details.get_outbound_payment_scid().unwrap() == scid {
2205 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2206 features_set = true;
2213 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2214 if let Some(node_info) = node.announcement_info.as_ref() {
2215 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2217 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2220 // We can fill in features for everything except hops which were
2221 // provided via the invoice we're paying. We could guess based on the
2222 // recipient's features but for now we simply avoid guessing at all.
2226 // Means we succesfully traversed from the payer to the payee, now
2227 // save this path for the payment route. Also, update the liquidity
2228 // remaining on the used hops, so that we take them into account
2229 // while looking for more paths.
2230 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2234 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2235 Some(payment_hop) => payment_hop,
2236 // We can't arrive at None because, if we ever add an entry to targets,
2237 // we also fill in the entry in dist (see add_entry!).
2238 None => unreachable!(),
2240 // We "propagate" the fees one hop backward (topologically) here,
2241 // so that fees paid for a HTLC forwarding on the current channel are
2242 // associated with the previous channel (where they will be subtracted).
2243 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2244 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2246 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2247 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2249 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2250 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2252 let mut payment_path = PaymentPath {hops: ordered_hops};
2254 // We could have possibly constructed a slightly inconsistent path: since we reduce
2255 // value being transferred along the way, we could have violated htlc_minimum_msat
2256 // on some channels we already passed (assuming dest->source direction). Here, we
2257 // recompute the fees again, so that if that's the case, we match the currently
2258 // underpaid htlc_minimum_msat with fees.
2259 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2260 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2261 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2263 // Since a path allows to transfer as much value as
2264 // the smallest channel it has ("bottleneck"), we should recompute
2265 // the fees so sender HTLC don't overpay fees when traversing
2266 // larger channels than the bottleneck. This may happen because
2267 // when we were selecting those channels we were not aware how much value
2268 // this path will transfer, and the relative fee for them
2269 // might have been computed considering a larger value.
2270 // Remember that we used these channels so that we don't rely
2271 // on the same liquidity in future paths.
2272 let mut prevented_redundant_path_selection = false;
2273 let prev_hop_iter = core::iter::once(&our_node_id)
2274 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2275 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2276 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2277 let used_liquidity_msat = used_liquidities
2278 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2279 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2280 .or_insert(spent_on_hop_msat);
2281 let hop_capacity = hop.candidate.effective_capacity();
2282 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2283 if *used_liquidity_msat == hop_max_msat {
2284 // If this path used all of this channel's available liquidity, we know
2285 // this path will not be selected again in the next loop iteration.
2286 prevented_redundant_path_selection = true;
2288 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2290 if !prevented_redundant_path_selection {
2291 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2292 // we'll probably end up picking the same path again on the next iteration.
2293 // Decrease the available liquidity of a hop in the middle of the path.
2294 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2295 let exhausted = u64::max_value();
2296 log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2297 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2298 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2299 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2302 // Track the total amount all our collected paths allow to send so that we know
2303 // when to stop looking for more paths
2304 already_collected_value_msat += value_contribution_msat;
2306 payment_paths.push(payment_path);
2307 found_new_path = true;
2308 break 'path_construction;
2311 // If we found a path back to the payee, we shouldn't try to process it again. This is
2312 // the equivalent of the `elem.was_processed` check in
2313 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2314 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2316 // Otherwise, since the current target node is not us,
2317 // keep "unrolling" the payment graph from payee to payer by
2318 // finding a way to reach the current target from the payer side.
2319 match network_nodes.get(&node_id) {
2322 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2323 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2324 total_cltv_delta, path_length_to_node);
2330 if !found_new_path && channel_saturation_pow_half != 0 {
2331 channel_saturation_pow_half = 0;
2332 continue 'paths_collection;
2334 // If we don't support MPP, no use trying to gather more value ever.
2335 break 'paths_collection;
2339 // Stop either when the recommended value is reached or if no new path was found in this
2341 // In the latter case, making another path finding attempt won't help,
2342 // because we deterministically terminated the search due to low liquidity.
2343 if !found_new_path && channel_saturation_pow_half != 0 {
2344 channel_saturation_pow_half = 0;
2345 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2346 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2347 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2348 break 'paths_collection;
2349 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2350 // Further, if this was our first walk of the graph, and we weren't limited by an
2351 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2352 // limited by an htlc_minimum_msat value, find another path with a higher value,
2353 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2354 // still keeping a lower total fee than this path.
2355 if !hit_minimum_limit {
2356 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2357 break 'paths_collection;
2359 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2360 path_value_msat = recommended_value_msat;
2364 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2365 num_ignored_cltv_delta_limit + num_ignored_previously_failed;
2366 if num_ignored_total > 0 {
2367 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);
2371 if payment_paths.len() == 0 {
2372 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2375 if already_collected_value_msat < final_value_msat {
2376 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2380 let mut selected_route = payment_paths;
2382 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2383 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2385 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2386 // the value they contribute towards the payment amount.
2387 // We sort in descending order as we will remove from the front in `retain`, next.
2388 selected_route.sort_unstable_by(|a, b|
2389 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2390 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2393 // We should make sure that at least 1 path left.
2394 let mut paths_left = selected_route.len();
2395 selected_route.retain(|path| {
2396 if paths_left == 1 {
2399 let path_value_msat = path.get_value_msat();
2400 if path_value_msat <= overpaid_value_msat {
2401 overpaid_value_msat -= path_value_msat;
2407 debug_assert!(selected_route.len() > 0);
2409 if overpaid_value_msat != 0 {
2411 // Now, subtract the remaining overpaid value from the most-expensive path.
2412 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2413 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2414 selected_route.sort_unstable_by(|a, b| {
2415 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2416 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2417 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2419 let expensive_payment_path = selected_route.first_mut().unwrap();
2421 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2422 // can't go negative.
2423 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2424 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2428 // Sort by the path itself and combine redundant paths.
2429 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2430 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2432 selected_route.sort_unstable_by_key(|path| {
2433 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2434 debug_assert!(path.hops.len() <= key.len());
2435 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2440 for idx in 0..(selected_route.len() - 1) {
2441 if idx + 1 >= selected_route.len() { break; }
2442 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2443 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2444 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2445 selected_route[idx].update_value_and_recompute_fees(new_value);
2446 selected_route.remove(idx + 1);
2450 let mut paths = Vec::new();
2451 for payment_path in selected_route {
2452 let mut hops = Vec::with_capacity(payment_path.hops.len());
2453 for (hop, node_features) in payment_path.hops.iter()
2454 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2456 hops.push(RouteHop {
2457 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)})?,
2458 node_features: node_features.clone(),
2459 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2460 channel_features: hop.candidate.features(),
2461 fee_msat: hop.fee_msat,
2462 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2465 let mut final_cltv_delta = final_cltv_expiry_delta;
2466 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2467 if let Some(blinded_path) = h.candidate.blinded_path() {
2468 final_cltv_delta = h.candidate.cltv_expiry_delta();
2470 hops: blinded_path.blinded_hops.clone(),
2471 blinding_point: blinded_path.blinding_point,
2472 excess_final_cltv_expiry_delta: 0,
2473 final_value_msat: h.fee_msat,
2477 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2478 // applicable for the previous hop.
2479 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2480 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2483 paths.push(Path { hops, blinded_tail });
2485 // Make sure we would never create a route with more paths than we allow.
2486 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2488 if let Some(node_features) = payment_params.payee.node_features() {
2489 for path in paths.iter_mut() {
2490 path.hops.last_mut().unwrap().node_features = node_features.clone();
2494 let route = Route { paths, payment_params: Some(payment_params.clone()) };
2495 log_info!(logger, "Got route: {}", log_route!(route));
2499 // When an adversarial intermediary node observes a payment, it may be able to infer its
2500 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2501 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2502 // payment path by adding a randomized 'shadow route' offset to the final hop.
2503 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2504 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2506 let network_channels = network_graph.channels();
2507 let network_nodes = network_graph.nodes();
2509 for path in route.paths.iter_mut() {
2510 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2512 // Remember the last three nodes of the random walk and avoid looping back on them.
2513 // Init with the last three nodes from the actual path, if possible.
2514 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2515 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2516 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2518 // Choose the last publicly known node as the starting point for the random walk.
2519 let mut cur_hop: Option<NodeId> = None;
2520 let mut path_nonce = [0u8; 12];
2521 if let Some(starting_hop) = path.hops.iter().rev()
2522 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2523 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2524 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2527 // Init PRNG with the path-dependant nonce, which is static for private paths.
2528 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2529 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2531 // Pick a random path length in [1 .. 3]
2532 prng.process_in_place(&mut random_path_bytes);
2533 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2535 for random_hop in 0..random_walk_length {
2536 // If we don't find a suitable offset in the public network graph, we default to
2537 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2538 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2540 if let Some(cur_node_id) = cur_hop {
2541 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2542 // Randomly choose the next unvisited hop.
2543 prng.process_in_place(&mut random_path_bytes);
2544 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2545 .checked_rem(cur_node.channels.len())
2546 .and_then(|index| cur_node.channels.get(index))
2547 .and_then(|id| network_channels.get(id)) {
2548 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2549 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2550 nodes_to_avoid[random_hop] = *next_id;
2551 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2552 cur_hop = Some(*next_id);
2559 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2560 .checked_add(random_hop_offset)
2561 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2564 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2565 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2566 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2568 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2569 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2570 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2571 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2572 max_path_offset = cmp::max(
2573 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2574 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2575 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2577 // Add 'shadow' CLTV offset to the final hop
2578 if let Some(tail) = path.blinded_tail.as_mut() {
2579 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2580 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2582 if let Some(last_hop) = path.hops.last_mut() {
2583 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2584 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2589 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2590 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2592 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2593 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2594 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2595 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2596 ) -> Result<Route, LightningError>
2597 where L::Target: Logger, GL::Target: Logger {
2598 let graph_lock = network_graph.read_only();
2599 let mut route = build_route_from_hops_internal(
2600 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2601 route_params.final_value_msat, logger, random_seed_bytes)?;
2602 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2606 fn build_route_from_hops_internal<L: Deref>(
2607 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2608 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, logger: L,
2609 random_seed_bytes: &[u8; 32]
2610 ) -> Result<Route, LightningError> where L::Target: Logger {
2613 our_node_id: NodeId,
2614 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2617 impl Score for HopScorer {
2618 type ScoreParams = ();
2619 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2620 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2622 let mut cur_id = self.our_node_id;
2623 for i in 0..self.hop_ids.len() {
2624 if let Some(next_id) = self.hop_ids[i] {
2625 if cur_id == *source && next_id == *target {
2636 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2638 fn payment_path_successful(&mut self, _path: &Path) {}
2640 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2642 fn probe_successful(&mut self, _path: &Path) {}
2645 impl<'a> Writeable for HopScorer {
2647 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2652 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2653 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2656 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2657 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2658 for i in 0..hops.len() {
2659 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2662 let scorer = HopScorer { our_node_id, hop_ids };
2664 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2665 logger, &scorer, &(), random_seed_bytes)
2670 use crate::blinded_path::{BlindedHop, BlindedPath};
2671 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2672 use crate::routing::utxo::UtxoResult;
2673 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2674 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2675 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2676 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2677 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2678 use crate::chain::transaction::OutPoint;
2679 use crate::sign::EntropySource;
2680 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2681 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2682 use crate::ln::channelmanager;
2683 use crate::offers::invoice::BlindedPayInfo;
2684 use crate::util::config::UserConfig;
2685 use crate::util::test_utils as ln_test_utils;
2686 use crate::util::chacha20::ChaCha20;
2687 use crate::util::ser::{Readable, Writeable};
2689 use crate::util::ser::Writer;
2691 use bitcoin::hashes::Hash;
2692 use bitcoin::network::constants::Network;
2693 use bitcoin::blockdata::constants::genesis_block;
2694 use bitcoin::blockdata::script::Builder;
2695 use bitcoin::blockdata::opcodes;
2696 use bitcoin::blockdata::transaction::TxOut;
2700 use bitcoin::secp256k1::{PublicKey,SecretKey};
2701 use bitcoin::secp256k1::Secp256k1;
2703 use crate::io::Cursor;
2704 use crate::prelude::*;
2705 use crate::sync::Arc;
2707 use core::convert::TryInto;
2709 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2710 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2711 channelmanager::ChannelDetails {
2712 channel_id: [0; 32],
2713 counterparty: channelmanager::ChannelCounterparty {
2716 unspendable_punishment_reserve: 0,
2717 forwarding_info: None,
2718 outbound_htlc_minimum_msat: None,
2719 outbound_htlc_maximum_msat: None,
2721 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2724 outbound_scid_alias: None,
2725 inbound_scid_alias: None,
2726 channel_value_satoshis: 0,
2729 outbound_capacity_msat,
2730 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2731 next_outbound_htlc_minimum_msat: 0,
2732 inbound_capacity_msat: 42,
2733 unspendable_punishment_reserve: None,
2734 confirmations_required: None,
2735 confirmations: None,
2736 force_close_spend_delay: None,
2737 is_outbound: true, is_channel_ready: true,
2738 is_usable: true, is_public: true,
2739 inbound_htlc_minimum_msat: None,
2740 inbound_htlc_maximum_msat: None,
2742 feerate_sat_per_1000_weight: None,
2743 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2748 fn simple_route_test() {
2749 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2750 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2751 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2752 let scorer = ln_test_utils::TestScorer::new();
2753 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2754 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2756 // Simple route to 2 via 1
2758 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) {
2759 assert_eq!(err, "Cannot send a payment of 0 msat");
2760 } else { panic!(); }
2762 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2763 assert_eq!(route.paths[0].hops.len(), 2);
2765 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2766 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2767 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2768 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2769 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2770 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2772 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2773 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2774 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2775 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2776 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2777 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2781 fn invalid_first_hop_test() {
2782 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2783 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2784 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2785 let scorer = ln_test_utils::TestScorer::new();
2786 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2787 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2789 // Simple route to 2 via 1
2791 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2793 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2794 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2795 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2796 } else { panic!(); }
2798 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2799 assert_eq!(route.paths[0].hops.len(), 2);
2803 fn htlc_minimum_test() {
2804 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2805 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2806 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2807 let scorer = ln_test_utils::TestScorer::new();
2808 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2809 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2811 // Simple route to 2 via 1
2813 // Disable other paths
2814 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2816 short_channel_id: 12,
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[0], UnsignedChannelUpdate {
2827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2828 short_channel_id: 3,
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[7], UnsignedChannelUpdate {
2839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2840 short_channel_id: 13,
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: 6,
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()
2862 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2863 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2864 short_channel_id: 7,
2866 flags: 2, // to disable
2867 cltv_expiry_delta: 0,
2868 htlc_minimum_msat: 0,
2869 htlc_maximum_msat: MAX_VALUE_MSAT,
2871 fee_proportional_millionths: 0,
2872 excess_data: Vec::new()
2875 // Check against amount_to_transfer_over_msat.
2876 // Set minimal HTLC of 200_000_000 msat.
2877 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2879 short_channel_id: 2,
2882 cltv_expiry_delta: 0,
2883 htlc_minimum_msat: 200_000_000,
2884 htlc_maximum_msat: MAX_VALUE_MSAT,
2886 fee_proportional_millionths: 0,
2887 excess_data: Vec::new()
2890 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2892 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2893 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2894 short_channel_id: 4,
2897 cltv_expiry_delta: 0,
2898 htlc_minimum_msat: 0,
2899 htlc_maximum_msat: 199_999_999,
2901 fee_proportional_millionths: 0,
2902 excess_data: Vec::new()
2905 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2906 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) {
2907 assert_eq!(err, "Failed to find a path to the given destination");
2908 } else { panic!(); }
2910 // Lift the restriction on the first hop.
2911 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2912 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2913 short_channel_id: 2,
2916 cltv_expiry_delta: 0,
2917 htlc_minimum_msat: 0,
2918 htlc_maximum_msat: MAX_VALUE_MSAT,
2920 fee_proportional_millionths: 0,
2921 excess_data: Vec::new()
2924 // A payment above the minimum should pass
2925 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2926 assert_eq!(route.paths[0].hops.len(), 2);
2930 fn htlc_minimum_overpay_test() {
2931 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2932 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2933 let config = UserConfig::default();
2934 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2935 let scorer = ln_test_utils::TestScorer::new();
2936 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2937 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2939 // A route to node#2 via two paths.
2940 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2941 // Thus, they can't send 60 without overpaying.
2942 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2943 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2944 short_channel_id: 2,
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()
2954 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2955 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2956 short_channel_id: 12,
2959 cltv_expiry_delta: 0,
2960 htlc_minimum_msat: 35_000,
2961 htlc_maximum_msat: 40_000,
2963 fee_proportional_millionths: 0,
2964 excess_data: Vec::new()
2968 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2970 short_channel_id: 13,
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()
2980 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2982 short_channel_id: 4,
2985 cltv_expiry_delta: 0,
2986 htlc_minimum_msat: 0,
2987 htlc_maximum_msat: MAX_VALUE_MSAT,
2989 fee_proportional_millionths: 0,
2990 excess_data: Vec::new()
2993 // Disable other paths
2994 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2995 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2996 short_channel_id: 1,
2998 flags: 2, // to disable
2999 cltv_expiry_delta: 0,
3000 htlc_minimum_msat: 0,
3001 htlc_maximum_msat: MAX_VALUE_MSAT,
3003 fee_proportional_millionths: 0,
3004 excess_data: Vec::new()
3007 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3008 // Overpay fees to hit htlc_minimum_msat.
3009 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3010 // TODO: this could be better balanced to overpay 10k and not 15k.
3011 assert_eq!(overpaid_fees, 15_000);
3013 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3014 // while taking even more fee to match htlc_minimum_msat.
3015 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3017 short_channel_id: 12,
3020 cltv_expiry_delta: 0,
3021 htlc_minimum_msat: 65_000,
3022 htlc_maximum_msat: 80_000,
3024 fee_proportional_millionths: 0,
3025 excess_data: Vec::new()
3027 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3029 short_channel_id: 2,
3032 cltv_expiry_delta: 0,
3033 htlc_minimum_msat: 0,
3034 htlc_maximum_msat: MAX_VALUE_MSAT,
3036 fee_proportional_millionths: 0,
3037 excess_data: Vec::new()
3039 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3041 short_channel_id: 4,
3044 cltv_expiry_delta: 0,
3045 htlc_minimum_msat: 0,
3046 htlc_maximum_msat: MAX_VALUE_MSAT,
3048 fee_proportional_millionths: 100_000,
3049 excess_data: Vec::new()
3052 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3053 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3054 assert_eq!(route.paths.len(), 1);
3055 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3056 let fees = route.paths[0].hops[0].fee_msat;
3057 assert_eq!(fees, 5_000);
3059 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3060 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3061 // the other channel.
3062 assert_eq!(route.paths.len(), 1);
3063 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3064 let fees = route.paths[0].hops[0].fee_msat;
3065 assert_eq!(fees, 5_000);
3069 fn disable_channels_test() {
3070 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3071 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3072 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3073 let scorer = ln_test_utils::TestScorer::new();
3074 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3075 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3077 // // Disable channels 4 and 12 by flags=2
3078 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3080 short_channel_id: 4,
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()
3090 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3092 short_channel_id: 12,
3094 flags: 2, // to disable
3095 cltv_expiry_delta: 0,
3096 htlc_minimum_msat: 0,
3097 htlc_maximum_msat: MAX_VALUE_MSAT,
3099 fee_proportional_millionths: 0,
3100 excess_data: Vec::new()
3103 // If all the channels require some features we don't understand, route should fail
3104 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) {
3105 assert_eq!(err, "Failed to find a path to the given destination");
3106 } else { panic!(); }
3108 // If we specify a channel to node7, that overrides our local channel view and that gets used
3109 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3110 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();
3111 assert_eq!(route.paths[0].hops.len(), 2);
3113 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3114 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3115 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3116 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3117 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3118 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3120 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3121 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3122 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3123 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3124 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3125 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3129 fn disable_node_test() {
3130 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3131 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3132 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3133 let scorer = ln_test_utils::TestScorer::new();
3134 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3135 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3137 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3138 let mut unknown_features = NodeFeatures::empty();
3139 unknown_features.set_unknown_feature_required();
3140 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3141 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3142 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3144 // If all nodes require some features we don't understand, route should fail
3145 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) {
3146 assert_eq!(err, "Failed to find a path to the given destination");
3147 } else { panic!(); }
3149 // If we specify a channel to node7, that overrides our local channel view and that gets used
3150 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3151 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();
3152 assert_eq!(route.paths[0].hops.len(), 2);
3154 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3155 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3156 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3157 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3158 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3159 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3161 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3162 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3163 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3164 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3165 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3166 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3168 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3169 // naively) assume that the user checked the feature bits on the invoice, which override
3170 // the node_announcement.
3174 fn our_chans_test() {
3175 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3176 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3177 let scorer = ln_test_utils::TestScorer::new();
3178 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3179 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3181 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3182 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3183 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3184 assert_eq!(route.paths[0].hops.len(), 3);
3186 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3187 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3188 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3189 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3190 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3191 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3193 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3194 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3195 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3196 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3197 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3198 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3200 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3201 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3202 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3203 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3204 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3205 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3207 // If we specify a channel to node7, that overrides our local channel view and that gets used
3208 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3209 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3210 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();
3211 assert_eq!(route.paths[0].hops.len(), 2);
3213 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3214 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3215 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3216 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3217 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3218 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3220 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3221 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3222 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3223 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3224 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3225 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3228 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3229 let zero_fees = RoutingFees {
3231 proportional_millionths: 0,
3233 vec![RouteHint(vec![RouteHintHop {
3234 src_node_id: nodes[3],
3235 short_channel_id: 8,
3237 cltv_expiry_delta: (8 << 4) | 1,
3238 htlc_minimum_msat: None,
3239 htlc_maximum_msat: None,
3241 ]), RouteHint(vec![RouteHintHop {
3242 src_node_id: nodes[4],
3243 short_channel_id: 9,
3246 proportional_millionths: 0,
3248 cltv_expiry_delta: (9 << 4) | 1,
3249 htlc_minimum_msat: None,
3250 htlc_maximum_msat: None,
3251 }]), RouteHint(vec![RouteHintHop {
3252 src_node_id: nodes[5],
3253 short_channel_id: 10,
3255 cltv_expiry_delta: (10 << 4) | 1,
3256 htlc_minimum_msat: None,
3257 htlc_maximum_msat: None,
3261 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3262 let zero_fees = RoutingFees {
3264 proportional_millionths: 0,
3266 vec![RouteHint(vec![RouteHintHop {
3267 src_node_id: nodes[2],
3268 short_channel_id: 5,
3271 proportional_millionths: 0,
3273 cltv_expiry_delta: (5 << 4) | 1,
3274 htlc_minimum_msat: None,
3275 htlc_maximum_msat: None,
3277 src_node_id: nodes[3],
3278 short_channel_id: 8,
3280 cltv_expiry_delta: (8 << 4) | 1,
3281 htlc_minimum_msat: None,
3282 htlc_maximum_msat: None,
3284 ]), RouteHint(vec![RouteHintHop {
3285 src_node_id: nodes[4],
3286 short_channel_id: 9,
3289 proportional_millionths: 0,
3291 cltv_expiry_delta: (9 << 4) | 1,
3292 htlc_minimum_msat: None,
3293 htlc_maximum_msat: None,
3294 }]), RouteHint(vec![RouteHintHop {
3295 src_node_id: nodes[5],
3296 short_channel_id: 10,
3298 cltv_expiry_delta: (10 << 4) | 1,
3299 htlc_minimum_msat: None,
3300 htlc_maximum_msat: None,
3305 fn partial_route_hint_test() {
3306 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3307 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3308 let scorer = ln_test_utils::TestScorer::new();
3309 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3310 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3312 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3313 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3314 // RouteHint may be partially used by the algo to build the best path.
3316 // First check that last hop can't have its source as the payee.
3317 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3318 src_node_id: nodes[6],
3319 short_channel_id: 8,
3322 proportional_millionths: 0,
3324 cltv_expiry_delta: (8 << 4) | 1,
3325 htlc_minimum_msat: None,
3326 htlc_maximum_msat: None,
3329 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3330 invalid_last_hops.push(invalid_last_hop);
3332 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3333 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) {
3334 assert_eq!(err, "Route hint cannot have the payee as the source.");
3335 } else { panic!(); }
3338 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3339 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3340 assert_eq!(route.paths[0].hops.len(), 5);
3342 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3343 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3344 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3345 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3346 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3347 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3349 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3350 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3351 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3352 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3353 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3354 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3356 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3357 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3358 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3359 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3360 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3361 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3363 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3364 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3365 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3366 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3367 // If we have a peer in the node map, we'll use their features here since we don't have
3368 // a way of figuring out their features from the invoice:
3369 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3370 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3372 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3373 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3374 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3375 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3376 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3377 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3380 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3381 let zero_fees = RoutingFees {
3383 proportional_millionths: 0,
3385 vec![RouteHint(vec![RouteHintHop {
3386 src_node_id: nodes[3],
3387 short_channel_id: 8,
3389 cltv_expiry_delta: (8 << 4) | 1,
3390 htlc_minimum_msat: None,
3391 htlc_maximum_msat: None,
3392 }]), RouteHint(vec![
3394 ]), RouteHint(vec![RouteHintHop {
3395 src_node_id: nodes[5],
3396 short_channel_id: 10,
3398 cltv_expiry_delta: (10 << 4) | 1,
3399 htlc_minimum_msat: None,
3400 htlc_maximum_msat: None,
3405 fn ignores_empty_last_hops_test() {
3406 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3407 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3408 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3409 let scorer = ln_test_utils::TestScorer::new();
3410 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3411 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3413 // Test handling of an empty RouteHint passed in Invoice.
3415 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3416 assert_eq!(route.paths[0].hops.len(), 5);
3418 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3419 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3420 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3421 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3422 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3423 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3425 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3426 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3427 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3428 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3429 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3430 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3432 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3433 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3434 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3435 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3436 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3437 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3439 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3440 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3441 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3442 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3443 // If we have a peer in the node map, we'll use their features here since we don't have
3444 // a way of figuring out their features from the invoice:
3445 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3446 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3448 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3449 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3450 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3451 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3452 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3453 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3456 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3458 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3459 let zero_fees = RoutingFees {
3461 proportional_millionths: 0,
3463 vec![RouteHint(vec![RouteHintHop {
3464 src_node_id: hint_hops[0],
3465 short_channel_id: 0xff00,
3468 proportional_millionths: 0,
3470 cltv_expiry_delta: (5 << 4) | 1,
3471 htlc_minimum_msat: None,
3472 htlc_maximum_msat: None,
3474 src_node_id: hint_hops[1],
3475 short_channel_id: 0xff01,
3477 cltv_expiry_delta: (8 << 4) | 1,
3478 htlc_minimum_msat: None,
3479 htlc_maximum_msat: None,
3484 fn multi_hint_last_hops_test() {
3485 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3486 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3487 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3488 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3489 let scorer = ln_test_utils::TestScorer::new();
3490 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3491 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3492 // Test through channels 2, 3, 0xff00, 0xff01.
3493 // Test shows that multiple hop hints are considered.
3495 // Disabling channels 6 & 7 by flags=2
3496 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3498 short_channel_id: 6,
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()
3508 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3510 short_channel_id: 7,
3512 flags: 2, // to disable
3513 cltv_expiry_delta: 0,
3514 htlc_minimum_msat: 0,
3515 htlc_maximum_msat: MAX_VALUE_MSAT,
3517 fee_proportional_millionths: 0,
3518 excess_data: Vec::new()
3521 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3522 assert_eq!(route.paths[0].hops.len(), 4);
3524 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3525 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3526 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3527 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3528 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3529 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3531 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3532 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3533 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3534 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3535 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3536 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3538 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3539 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3540 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3541 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3542 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3543 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3545 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3546 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3547 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3548 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3549 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3550 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3554 fn private_multi_hint_last_hops_test() {
3555 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3556 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3558 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3559 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3561 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3562 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3563 let scorer = ln_test_utils::TestScorer::new();
3564 // Test through channels 2, 3, 0xff00, 0xff01.
3565 // Test shows that multiple hop hints are considered.
3567 // Disabling channels 6 & 7 by flags=2
3568 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3569 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3570 short_channel_id: 6,
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()
3580 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3582 short_channel_id: 7,
3584 flags: 2, // to disable
3585 cltv_expiry_delta: 0,
3586 htlc_minimum_msat: 0,
3587 htlc_maximum_msat: MAX_VALUE_MSAT,
3589 fee_proportional_millionths: 0,
3590 excess_data: Vec::new()
3593 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3594 assert_eq!(route.paths[0].hops.len(), 4);
3596 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3597 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3598 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3599 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3600 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3601 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3603 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3604 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3605 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3606 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3607 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3608 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3610 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3611 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3612 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3613 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3614 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3615 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3617 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3618 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3619 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3620 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3621 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3622 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3625 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3626 let zero_fees = RoutingFees {
3628 proportional_millionths: 0,
3630 vec![RouteHint(vec![RouteHintHop {
3631 src_node_id: nodes[4],
3632 short_channel_id: 11,
3634 cltv_expiry_delta: (11 << 4) | 1,
3635 htlc_minimum_msat: None,
3636 htlc_maximum_msat: None,
3638 src_node_id: nodes[3],
3639 short_channel_id: 8,
3641 cltv_expiry_delta: (8 << 4) | 1,
3642 htlc_minimum_msat: None,
3643 htlc_maximum_msat: None,
3644 }]), RouteHint(vec![RouteHintHop {
3645 src_node_id: nodes[4],
3646 short_channel_id: 9,
3649 proportional_millionths: 0,
3651 cltv_expiry_delta: (9 << 4) | 1,
3652 htlc_minimum_msat: None,
3653 htlc_maximum_msat: None,
3654 }]), RouteHint(vec![RouteHintHop {
3655 src_node_id: nodes[5],
3656 short_channel_id: 10,
3658 cltv_expiry_delta: (10 << 4) | 1,
3659 htlc_minimum_msat: None,
3660 htlc_maximum_msat: None,
3665 fn last_hops_with_public_channel_test() {
3666 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3667 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3668 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3669 let scorer = ln_test_utils::TestScorer::new();
3670 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3671 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3672 // This test shows that public routes can be present in the invoice
3673 // which would be handled in the same manner.
3675 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3676 assert_eq!(route.paths[0].hops.len(), 5);
3678 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3679 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3680 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3681 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3682 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3683 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3685 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3686 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3687 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3688 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3689 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3690 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3692 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3693 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3694 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3695 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3696 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3697 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3699 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3700 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3701 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3702 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3703 // If we have a peer in the node map, we'll use their features here since we don't have
3704 // a way of figuring out their features from the invoice:
3705 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3706 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3708 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3709 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3710 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3711 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3712 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3713 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3717 fn our_chans_last_hop_connect_test() {
3718 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3719 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3720 let scorer = ln_test_utils::TestScorer::new();
3721 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3722 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3724 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3725 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3726 let mut last_hops = last_hops(&nodes);
3727 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3728 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();
3729 assert_eq!(route.paths[0].hops.len(), 2);
3731 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3732 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3733 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3734 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3735 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3736 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3738 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3739 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3740 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3741 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3742 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3743 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3745 last_hops[0].0[0].fees.base_msat = 1000;
3747 // Revert to via 6 as the fee on 8 goes up
3748 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3749 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3750 assert_eq!(route.paths[0].hops.len(), 4);
3752 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3753 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3754 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3755 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3756 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3757 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3759 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3760 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3761 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3762 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3763 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3764 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3766 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3767 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3768 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3769 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3770 // If we have a peer in the node map, we'll use their features here since we don't have
3771 // a way of figuring out their features from the invoice:
3772 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3773 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3775 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3776 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3777 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3778 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3779 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3780 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3782 // ...but still use 8 for larger payments as 6 has a variable feerate
3783 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3784 assert_eq!(route.paths[0].hops.len(), 5);
3786 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3787 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3788 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3789 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3790 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3791 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3793 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3794 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3795 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3796 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3797 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3798 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3800 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3801 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3802 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3803 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3804 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3805 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3807 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3808 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3809 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3810 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3811 // If we have a peer in the node map, we'll use their features here since we don't have
3812 // a way of figuring out their features from the invoice:
3813 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3814 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3816 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3817 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3818 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3819 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3820 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3821 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3824 fn 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> {
3825 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3826 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3827 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3829 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3830 let last_hops = RouteHint(vec![RouteHintHop {
3831 src_node_id: middle_node_id,
3832 short_channel_id: 8,
3835 proportional_millionths: last_hop_fee_prop,
3837 cltv_expiry_delta: (8 << 4) | 1,
3838 htlc_minimum_msat: None,
3839 htlc_maximum_msat: last_hop_htlc_max,
3841 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3842 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3843 let scorer = ln_test_utils::TestScorer::new();
3844 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3845 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3846 let logger = ln_test_utils::TestLogger::new();
3847 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3848 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3849 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3854 fn unannounced_path_test() {
3855 // We should be able to send a payment to a destination without any help of a routing graph
3856 // if we have a channel with a common counterparty that appears in the first and last hop
3858 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3860 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3861 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3862 assert_eq!(route.paths[0].hops.len(), 2);
3864 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3865 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3866 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3867 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3868 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3869 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3871 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3872 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3873 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3874 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3875 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3876 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3880 fn overflow_unannounced_path_test_liquidity_underflow() {
3881 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3882 // the last-hop had a fee which overflowed a u64, we'd panic.
3883 // This was due to us adding the first-hop from us unconditionally, causing us to think
3884 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3885 // In this test, we previously hit a subtraction underflow due to having less available
3886 // liquidity at the last hop than 0.
3887 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());
3891 fn overflow_unannounced_path_test_feerate_overflow() {
3892 // This tests for the same case as above, except instead of hitting a subtraction
3893 // underflow, we hit a case where the fee charged at a hop overflowed.
3894 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());
3898 fn available_amount_while_routing_test() {
3899 // Tests whether we choose the correct available channel amount while routing.
3901 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3902 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3903 let scorer = ln_test_utils::TestScorer::new();
3904 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3905 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3906 let config = UserConfig::default();
3907 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3909 // We will use a simple single-path route from
3910 // our node to node2 via node0: channels {1, 3}.
3912 // First disable all other paths.
3913 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3915 short_channel_id: 2,
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()
3925 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3927 short_channel_id: 12,
3930 cltv_expiry_delta: 0,
3931 htlc_minimum_msat: 0,
3932 htlc_maximum_msat: 100_000,
3934 fee_proportional_millionths: 0,
3935 excess_data: Vec::new()
3938 // Make the first channel (#1) very permissive,
3939 // and we will be testing all limits on the second channel.
3940 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3942 short_channel_id: 1,
3945 cltv_expiry_delta: 0,
3946 htlc_minimum_msat: 0,
3947 htlc_maximum_msat: 1_000_000_000,
3949 fee_proportional_millionths: 0,
3950 excess_data: Vec::new()
3953 // First, let's see if routing works if we have absolutely no idea about the available amount.
3954 // In this case, it should be set to 250_000 sats.
3955 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3956 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3957 short_channel_id: 3,
3960 cltv_expiry_delta: 0,
3961 htlc_minimum_msat: 0,
3962 htlc_maximum_msat: 250_000_000,
3964 fee_proportional_millionths: 0,
3965 excess_data: Vec::new()
3969 // Attempt to route more than available results in a failure.
3970 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3971 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3972 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3973 } else { panic!(); }
3977 // Now, attempt to route an exact amount we have should be fine.
3978 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3979 assert_eq!(route.paths.len(), 1);
3980 let path = route.paths.last().unwrap();
3981 assert_eq!(path.hops.len(), 2);
3982 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3983 assert_eq!(path.final_value_msat(), 250_000_000);
3986 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3987 // Disable channel #1 and use another first hop.
3988 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3990 short_channel_id: 1,
3993 cltv_expiry_delta: 0,
3994 htlc_minimum_msat: 0,
3995 htlc_maximum_msat: 1_000_000_000,
3997 fee_proportional_millionths: 0,
3998 excess_data: Vec::new()
4001 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4002 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4005 // Attempt to route more than available results in a failure.
4006 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4007 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4008 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4009 } else { panic!(); }
4013 // Now, attempt to route an exact amount we have should be fine.
4014 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();
4015 assert_eq!(route.paths.len(), 1);
4016 let path = route.paths.last().unwrap();
4017 assert_eq!(path.hops.len(), 2);
4018 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4019 assert_eq!(path.final_value_msat(), 200_000_000);
4022 // Enable channel #1 back.
4023 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4024 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4025 short_channel_id: 1,
4028 cltv_expiry_delta: 0,
4029 htlc_minimum_msat: 0,
4030 htlc_maximum_msat: 1_000_000_000,
4032 fee_proportional_millionths: 0,
4033 excess_data: Vec::new()
4037 // Now let's see if routing works if we know only htlc_maximum_msat.
4038 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4039 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4040 short_channel_id: 3,
4043 cltv_expiry_delta: 0,
4044 htlc_minimum_msat: 0,
4045 htlc_maximum_msat: 15_000,
4047 fee_proportional_millionths: 0,
4048 excess_data: Vec::new()
4052 // Attempt to route more than available results in a failure.
4053 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4054 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4055 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4056 } else { panic!(); }
4060 // Now, attempt to route an exact amount we have should be fine.
4061 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4062 assert_eq!(route.paths.len(), 1);
4063 let path = route.paths.last().unwrap();
4064 assert_eq!(path.hops.len(), 2);
4065 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4066 assert_eq!(path.final_value_msat(), 15_000);
4069 // Now let's see if routing works if we know only capacity from the UTXO.
4071 // We can't change UTXO capacity on the fly, so we'll disable
4072 // the existing channel and add another one with the capacity we need.
4073 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4075 short_channel_id: 3,
4078 cltv_expiry_delta: 0,
4079 htlc_minimum_msat: 0,
4080 htlc_maximum_msat: MAX_VALUE_MSAT,
4082 fee_proportional_millionths: 0,
4083 excess_data: Vec::new()
4086 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4087 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4088 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4089 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4090 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4092 *chain_monitor.utxo_ret.lock().unwrap() =
4093 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4094 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4096 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4097 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4098 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4099 short_channel_id: 333,
4102 cltv_expiry_delta: (3 << 4) | 1,
4103 htlc_minimum_msat: 0,
4104 htlc_maximum_msat: 15_000,
4106 fee_proportional_millionths: 0,
4107 excess_data: Vec::new()
4109 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4110 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4111 short_channel_id: 333,
4114 cltv_expiry_delta: (3 << 4) | 2,
4115 htlc_minimum_msat: 0,
4116 htlc_maximum_msat: 15_000,
4118 fee_proportional_millionths: 0,
4119 excess_data: Vec::new()
4123 // Attempt to route more than available results in a failure.
4124 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4125 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4126 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4127 } else { panic!(); }
4131 // Now, attempt to route an exact amount we have should be fine.
4132 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4133 assert_eq!(route.paths.len(), 1);
4134 let path = route.paths.last().unwrap();
4135 assert_eq!(path.hops.len(), 2);
4136 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4137 assert_eq!(path.final_value_msat(), 15_000);
4140 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4141 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4143 short_channel_id: 333,
4146 cltv_expiry_delta: 0,
4147 htlc_minimum_msat: 0,
4148 htlc_maximum_msat: 10_000,
4150 fee_proportional_millionths: 0,
4151 excess_data: Vec::new()
4155 // Attempt to route more than available results in a failure.
4156 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4157 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4158 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4159 } else { panic!(); }
4163 // Now, attempt to route an exact amount we have should be fine.
4164 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4165 assert_eq!(route.paths.len(), 1);
4166 let path = route.paths.last().unwrap();
4167 assert_eq!(path.hops.len(), 2);
4168 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4169 assert_eq!(path.final_value_msat(), 10_000);
4174 fn available_liquidity_last_hop_test() {
4175 // Check that available liquidity properly limits the path even when only
4176 // one of the latter hops is limited.
4177 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4178 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4179 let scorer = ln_test_utils::TestScorer::new();
4180 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4181 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4182 let config = UserConfig::default();
4183 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4185 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4186 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4187 // Total capacity: 50 sats.
4189 // Disable other potential paths.
4190 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4192 short_channel_id: 2,
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()
4202 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4203 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4204 short_channel_id: 7,
4207 cltv_expiry_delta: 0,
4208 htlc_minimum_msat: 0,
4209 htlc_maximum_msat: 100_000,
4211 fee_proportional_millionths: 0,
4212 excess_data: Vec::new()
4217 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4219 short_channel_id: 12,
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()
4229 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4231 short_channel_id: 13,
4234 cltv_expiry_delta: 0,
4235 htlc_minimum_msat: 0,
4236 htlc_maximum_msat: 100_000,
4238 fee_proportional_millionths: 0,
4239 excess_data: Vec::new()
4242 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4244 short_channel_id: 6,
4247 cltv_expiry_delta: 0,
4248 htlc_minimum_msat: 0,
4249 htlc_maximum_msat: 50_000,
4251 fee_proportional_millionths: 0,
4252 excess_data: Vec::new()
4254 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4256 short_channel_id: 11,
4259 cltv_expiry_delta: 0,
4260 htlc_minimum_msat: 0,
4261 htlc_maximum_msat: 100_000,
4263 fee_proportional_millionths: 0,
4264 excess_data: Vec::new()
4267 // Attempt to route more than available results in a failure.
4268 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4269 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4270 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4271 } else { panic!(); }
4275 // Now, attempt to route 49 sats (just a bit below the capacity).
4276 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4277 assert_eq!(route.paths.len(), 1);
4278 let mut total_amount_paid_msat = 0;
4279 for path in &route.paths {
4280 assert_eq!(path.hops.len(), 4);
4281 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4282 total_amount_paid_msat += path.final_value_msat();
4284 assert_eq!(total_amount_paid_msat, 49_000);
4288 // Attempt to route an exact amount is also fine
4289 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4290 assert_eq!(route.paths.len(), 1);
4291 let mut total_amount_paid_msat = 0;
4292 for path in &route.paths {
4293 assert_eq!(path.hops.len(), 4);
4294 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4295 total_amount_paid_msat += path.final_value_msat();
4297 assert_eq!(total_amount_paid_msat, 50_000);
4302 fn ignore_fee_first_hop_test() {
4303 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4304 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4305 let scorer = ln_test_utils::TestScorer::new();
4306 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4307 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4308 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4310 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4311 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4313 short_channel_id: 1,
4316 cltv_expiry_delta: 0,
4317 htlc_minimum_msat: 0,
4318 htlc_maximum_msat: 100_000,
4319 fee_base_msat: 1_000_000,
4320 fee_proportional_millionths: 0,
4321 excess_data: Vec::new()
4323 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4324 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4325 short_channel_id: 3,
4328 cltv_expiry_delta: 0,
4329 htlc_minimum_msat: 0,
4330 htlc_maximum_msat: 50_000,
4332 fee_proportional_millionths: 0,
4333 excess_data: Vec::new()
4337 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4338 assert_eq!(route.paths.len(), 1);
4339 let mut total_amount_paid_msat = 0;
4340 for path in &route.paths {
4341 assert_eq!(path.hops.len(), 2);
4342 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4343 total_amount_paid_msat += path.final_value_msat();
4345 assert_eq!(total_amount_paid_msat, 50_000);
4350 fn simple_mpp_route_test() {
4351 let (secp_ctx, _, _, _, _) = build_graph();
4352 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4353 let config = UserConfig::default();
4354 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4355 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4356 do_simple_mpp_route_test(clear_payment_params);
4358 // MPP to a 1-hop blinded path for nodes[2]
4359 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4360 let blinded_path = BlindedPath {
4361 introduction_node_id: nodes[2],
4362 blinding_point: ln_test_utils::pubkey(42),
4363 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4365 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4367 fee_proportional_millionths: 0,
4368 htlc_minimum_msat: 0,
4369 htlc_maximum_msat: 0,
4370 cltv_expiry_delta: 0,
4371 features: BlindedHopFeatures::empty(),
4373 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4374 .with_bolt12_features(bolt12_features.clone()).unwrap();
4375 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4377 // MPP to 3 2-hop blinded paths
4378 let mut blinded_path_node_0 = blinded_path.clone();
4379 blinded_path_node_0.introduction_node_id = nodes[0];
4380 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4381 let mut node_0_payinfo = blinded_payinfo.clone();
4382 node_0_payinfo.htlc_maximum_msat = 50_000;
4384 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4385 blinded_path_node_7.introduction_node_id = nodes[7];
4386 let mut node_7_payinfo = blinded_payinfo.clone();
4387 node_7_payinfo.htlc_maximum_msat = 60_000;
4389 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4390 blinded_path_node_1.introduction_node_id = nodes[1];
4391 let mut node_1_payinfo = blinded_payinfo.clone();
4392 node_1_payinfo.htlc_maximum_msat = 180_000;
4394 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4396 (node_0_payinfo, blinded_path_node_0),
4397 (node_7_payinfo, blinded_path_node_7),
4398 (node_1_payinfo, blinded_path_node_1)
4400 .with_bolt12_features(bolt12_features).unwrap();
4401 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4405 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4406 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4407 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4408 let scorer = ln_test_utils::TestScorer::new();
4409 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4410 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4412 // We need a route consisting of 3 paths:
4413 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4414 // To achieve this, the amount being transferred should be around
4415 // the total capacity of these 3 paths.
4417 // First, we set limits on these (previously unlimited) channels.
4418 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4420 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4421 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4423 short_channel_id: 1,
4426 cltv_expiry_delta: 0,
4427 htlc_minimum_msat: 0,
4428 htlc_maximum_msat: 100_000,
4430 fee_proportional_millionths: 0,
4431 excess_data: Vec::new()
4433 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4435 short_channel_id: 3,
4438 cltv_expiry_delta: 0,
4439 htlc_minimum_msat: 0,
4440 htlc_maximum_msat: 50_000,
4442 fee_proportional_millionths: 0,
4443 excess_data: Vec::new()
4446 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4447 // (total limit 60).
4448 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4450 short_channel_id: 12,
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()
4460 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4462 short_channel_id: 13,
4465 cltv_expiry_delta: 0,
4466 htlc_minimum_msat: 0,
4467 htlc_maximum_msat: 60_000,
4469 fee_proportional_millionths: 0,
4470 excess_data: Vec::new()
4473 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4474 // (total capacity 180 sats).
4475 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4477 short_channel_id: 2,
4480 cltv_expiry_delta: 0,
4481 htlc_minimum_msat: 0,
4482 htlc_maximum_msat: 200_000,
4484 fee_proportional_millionths: 0,
4485 excess_data: Vec::new()
4487 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4489 short_channel_id: 4,
4492 cltv_expiry_delta: 0,
4493 htlc_minimum_msat: 0,
4494 htlc_maximum_msat: 180_000,
4496 fee_proportional_millionths: 0,
4497 excess_data: Vec::new()
4501 // Attempt to route more than available results in a failure.
4502 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4503 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4504 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4505 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4506 } else { panic!(); }
4510 // Attempt to route while setting max_path_count to 0 results in a failure.
4511 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4512 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4513 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4514 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4515 assert_eq!(err, "Can't find a route with no paths allowed.");
4516 } else { panic!(); }
4520 // Attempt to route while setting max_path_count to 3 results in a failure.
4521 // This is the case because the minimal_value_contribution_msat would require each path
4522 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4523 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4524 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4525 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4526 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4527 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4528 } else { panic!(); }
4532 // Now, attempt to route 250 sats (just a bit below the capacity).
4533 // Our algorithm should provide us with these 3 paths.
4534 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4535 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4536 assert_eq!(route.paths.len(), 3);
4537 let mut total_amount_paid_msat = 0;
4538 for path in &route.paths {
4539 if let Some(bt) = &path.blinded_tail {
4540 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4542 assert_eq!(path.hops.len(), 2);
4543 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4545 total_amount_paid_msat += path.final_value_msat();
4547 assert_eq!(total_amount_paid_msat, 250_000);
4551 // Attempt to route an exact amount is also fine
4552 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4553 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4554 assert_eq!(route.paths.len(), 3);
4555 let mut total_amount_paid_msat = 0;
4556 for path in &route.paths {
4557 if payment_params.payee.blinded_route_hints().len() != 0 {
4558 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4559 if let Some(bt) = &path.blinded_tail {
4560 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4561 if bt.hops.len() > 1 {
4562 assert_eq!(path.hops.last().unwrap().pubkey,
4563 payment_params.payee.blinded_route_hints().iter()
4564 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4565 .map(|(_, p)| p.introduction_node_id).unwrap());
4567 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4570 assert_eq!(path.hops.len(), 2);
4571 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4573 total_amount_paid_msat += path.final_value_msat();
4575 assert_eq!(total_amount_paid_msat, 290_000);
4580 fn long_mpp_route_test() {
4581 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4582 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4583 let scorer = ln_test_utils::TestScorer::new();
4584 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4585 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4586 let config = UserConfig::default();
4587 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4589 // We need a route consisting of 3 paths:
4590 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4591 // Note that these paths overlap (channels 5, 12, 13).
4592 // We will route 300 sats.
4593 // Each path will have 100 sats capacity, those channels which
4594 // are used twice will have 200 sats capacity.
4596 // Disable other potential paths.
4597 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4598 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4599 short_channel_id: 2,
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()
4609 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4611 short_channel_id: 7,
4614 cltv_expiry_delta: 0,
4615 htlc_minimum_msat: 0,
4616 htlc_maximum_msat: 100_000,
4618 fee_proportional_millionths: 0,
4619 excess_data: Vec::new()
4622 // Path via {node0, node2} is channels {1, 3, 5}.
4623 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4625 short_channel_id: 1,
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()
4635 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4637 short_channel_id: 3,
4640 cltv_expiry_delta: 0,
4641 htlc_minimum_msat: 0,
4642 htlc_maximum_msat: 100_000,
4644 fee_proportional_millionths: 0,
4645 excess_data: Vec::new()
4648 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4649 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4650 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4652 short_channel_id: 5,
4655 cltv_expiry_delta: 0,
4656 htlc_minimum_msat: 0,
4657 htlc_maximum_msat: 200_000,
4659 fee_proportional_millionths: 0,
4660 excess_data: Vec::new()
4663 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4664 // Add 100 sats to the capacities of {12, 13}, because these channels
4665 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4666 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4668 short_channel_id: 12,
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()
4678 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4680 short_channel_id: 13,
4683 cltv_expiry_delta: 0,
4684 htlc_minimum_msat: 0,
4685 htlc_maximum_msat: 200_000,
4687 fee_proportional_millionths: 0,
4688 excess_data: Vec::new()
4691 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4693 short_channel_id: 6,
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()
4703 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4705 short_channel_id: 11,
4708 cltv_expiry_delta: 0,
4709 htlc_minimum_msat: 0,
4710 htlc_maximum_msat: 100_000,
4712 fee_proportional_millionths: 0,
4713 excess_data: Vec::new()
4716 // Path via {node7, node2} is channels {12, 13, 5}.
4717 // We already limited them to 200 sats (they are used twice for 100 sats).
4718 // Nothing to do here.
4721 // Attempt to route more than available results in a failure.
4722 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4723 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4724 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4725 } else { panic!(); }
4729 // Now, attempt to route 300 sats (exact amount we can route).
4730 // Our algorithm should provide us with these 3 paths, 100 sats each.
4731 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4732 assert_eq!(route.paths.len(), 3);
4734 let mut total_amount_paid_msat = 0;
4735 for path in &route.paths {
4736 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4737 total_amount_paid_msat += path.final_value_msat();
4739 assert_eq!(total_amount_paid_msat, 300_000);
4745 fn mpp_cheaper_route_test() {
4746 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4747 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4748 let scorer = ln_test_utils::TestScorer::new();
4749 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4750 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4751 let config = UserConfig::default();
4752 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4754 // This test checks that if we have two cheaper paths and one more expensive path,
4755 // so that liquidity-wise any 2 of 3 combination is sufficient,
4756 // two cheaper paths will be taken.
4757 // These paths have equal available liquidity.
4759 // We need a combination of 3 paths:
4760 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4761 // Note that these paths overlap (channels 5, 12, 13).
4762 // Each path will have 100 sats capacity, those channels which
4763 // are used twice will have 200 sats capacity.
4765 // Disable other potential paths.
4766 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4768 short_channel_id: 2,
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()
4778 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4780 short_channel_id: 7,
4783 cltv_expiry_delta: 0,
4784 htlc_minimum_msat: 0,
4785 htlc_maximum_msat: 100_000,
4787 fee_proportional_millionths: 0,
4788 excess_data: Vec::new()
4791 // Path via {node0, node2} is channels {1, 3, 5}.
4792 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4794 short_channel_id: 1,
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()
4804 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4806 short_channel_id: 3,
4809 cltv_expiry_delta: 0,
4810 htlc_minimum_msat: 0,
4811 htlc_maximum_msat: 100_000,
4813 fee_proportional_millionths: 0,
4814 excess_data: Vec::new()
4817 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4818 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4819 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4821 short_channel_id: 5,
4824 cltv_expiry_delta: 0,
4825 htlc_minimum_msat: 0,
4826 htlc_maximum_msat: 200_000,
4828 fee_proportional_millionths: 0,
4829 excess_data: Vec::new()
4832 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4833 // Add 100 sats to the capacities of {12, 13}, because these channels
4834 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4835 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4836 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4837 short_channel_id: 12,
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()
4847 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4848 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4849 short_channel_id: 13,
4852 cltv_expiry_delta: 0,
4853 htlc_minimum_msat: 0,
4854 htlc_maximum_msat: 200_000,
4856 fee_proportional_millionths: 0,
4857 excess_data: Vec::new()
4860 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4862 short_channel_id: 6,
4865 cltv_expiry_delta: 0,
4866 htlc_minimum_msat: 0,
4867 htlc_maximum_msat: 100_000,
4868 fee_base_msat: 1_000,
4869 fee_proportional_millionths: 0,
4870 excess_data: Vec::new()
4872 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4873 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4874 short_channel_id: 11,
4877 cltv_expiry_delta: 0,
4878 htlc_minimum_msat: 0,
4879 htlc_maximum_msat: 100_000,
4881 fee_proportional_millionths: 0,
4882 excess_data: Vec::new()
4885 // Path via {node7, node2} is channels {12, 13, 5}.
4886 // We already limited them to 200 sats (they are used twice for 100 sats).
4887 // Nothing to do here.
4890 // Now, attempt to route 180 sats.
4891 // Our algorithm should provide us with these 2 paths.
4892 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4893 assert_eq!(route.paths.len(), 2);
4895 let mut total_value_transferred_msat = 0;
4896 let mut total_paid_msat = 0;
4897 for path in &route.paths {
4898 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4899 total_value_transferred_msat += path.final_value_msat();
4900 for hop in &path.hops {
4901 total_paid_msat += hop.fee_msat;
4904 // If we paid fee, this would be higher.
4905 assert_eq!(total_value_transferred_msat, 180_000);
4906 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4907 assert_eq!(total_fees_paid, 0);
4912 fn fees_on_mpp_route_test() {
4913 // This test makes sure that MPP algorithm properly takes into account
4914 // fees charged on the channels, by making the fees impactful:
4915 // if the fee is not properly accounted for, the behavior is different.
4916 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4917 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4918 let scorer = ln_test_utils::TestScorer::new();
4919 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4920 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4921 let config = UserConfig::default();
4922 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4924 // We need a route consisting of 2 paths:
4925 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4926 // We will route 200 sats, Each path will have 100 sats capacity.
4928 // This test is not particularly stable: e.g.,
4929 // there's a way to route via {node0, node2, node4}.
4930 // It works while pathfinding is deterministic, but can be broken otherwise.
4931 // It's fine to ignore this concern for now.
4933 // Disable other potential paths.
4934 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4936 short_channel_id: 2,
4939 cltv_expiry_delta: 0,
4940 htlc_minimum_msat: 0,
4941 htlc_maximum_msat: 100_000,
4943 fee_proportional_millionths: 0,
4944 excess_data: Vec::new()
4947 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4948 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4949 short_channel_id: 7,
4952 cltv_expiry_delta: 0,
4953 htlc_minimum_msat: 0,
4954 htlc_maximum_msat: 100_000,
4956 fee_proportional_millionths: 0,
4957 excess_data: Vec::new()
4960 // Path via {node0, node2} is channels {1, 3, 5}.
4961 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4962 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4963 short_channel_id: 1,
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()
4973 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4974 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4975 short_channel_id: 3,
4978 cltv_expiry_delta: 0,
4979 htlc_minimum_msat: 0,
4980 htlc_maximum_msat: 100_000,
4982 fee_proportional_millionths: 0,
4983 excess_data: Vec::new()
4986 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4987 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4988 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4989 short_channel_id: 5,
4992 cltv_expiry_delta: 0,
4993 htlc_minimum_msat: 0,
4994 htlc_maximum_msat: 100_000,
4996 fee_proportional_millionths: 0,
4997 excess_data: Vec::new()
5000 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5001 // All channels should be 100 sats capacity. But for the fee experiment,
5002 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5003 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5004 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5005 // so no matter how large are other channels,
5006 // the whole path will be limited by 100 sats with just these 2 conditions:
5007 // - channel 12 capacity is 250 sats
5008 // - fee for channel 6 is 150 sats
5009 // Let's test this by enforcing these 2 conditions and removing other limits.
5010 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5012 short_channel_id: 12,
5015 cltv_expiry_delta: 0,
5016 htlc_minimum_msat: 0,
5017 htlc_maximum_msat: 250_000,
5019 fee_proportional_millionths: 0,
5020 excess_data: Vec::new()
5022 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5024 short_channel_id: 13,
5027 cltv_expiry_delta: 0,
5028 htlc_minimum_msat: 0,
5029 htlc_maximum_msat: MAX_VALUE_MSAT,
5031 fee_proportional_millionths: 0,
5032 excess_data: Vec::new()
5035 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5036 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5037 short_channel_id: 6,
5040 cltv_expiry_delta: 0,
5041 htlc_minimum_msat: 0,
5042 htlc_maximum_msat: MAX_VALUE_MSAT,
5043 fee_base_msat: 150_000,
5044 fee_proportional_millionths: 0,
5045 excess_data: Vec::new()
5047 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5048 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5049 short_channel_id: 11,
5052 cltv_expiry_delta: 0,
5053 htlc_minimum_msat: 0,
5054 htlc_maximum_msat: MAX_VALUE_MSAT,
5056 fee_proportional_millionths: 0,
5057 excess_data: Vec::new()
5061 // Attempt to route more than available results in a failure.
5062 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5063 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5064 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5065 } else { panic!(); }
5069 // Now, attempt to route 200 sats (exact amount we can route).
5070 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5071 assert_eq!(route.paths.len(), 2);
5073 let mut total_amount_paid_msat = 0;
5074 for path in &route.paths {
5075 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5076 total_amount_paid_msat += path.final_value_msat();
5078 assert_eq!(total_amount_paid_msat, 200_000);
5079 assert_eq!(route.get_total_fees(), 150_000);
5084 fn mpp_with_last_hops() {
5085 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5086 // via a single last-hop route hint, we'd fail to route if we first collected routes
5087 // totaling close but not quite enough to fund the full payment.
5089 // This was because we considered last-hop hints to have exactly the sought payment amount
5090 // instead of the amount we were trying to collect, needlessly limiting our path searching
5091 // at the very first hop.
5093 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5094 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5095 // to only have the remaining to-collect amount in available liquidity.
5097 // This bug appeared in production in some specific channel configurations.
5098 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5099 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5100 let scorer = ln_test_utils::TestScorer::new();
5101 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5102 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5103 let config = UserConfig::default();
5104 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5105 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5106 src_node_id: nodes[2],
5107 short_channel_id: 42,
5108 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5109 cltv_expiry_delta: 42,
5110 htlc_minimum_msat: None,
5111 htlc_maximum_msat: None,
5112 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5114 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5115 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5116 // would first use the no-fee route and then fail to find a path along the second route as
5117 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5118 // under 5% of our payment amount.
5119 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5120 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5121 short_channel_id: 1,
5124 cltv_expiry_delta: (5 << 4) | 5,
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, &our_privkey, UnsignedChannelUpdate {
5132 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5133 short_channel_id: 2,
5136 cltv_expiry_delta: (5 << 4) | 3,
5137 htlc_minimum_msat: 0,
5138 htlc_maximum_msat: 99_000,
5139 fee_base_msat: u32::max_value(),
5140 fee_proportional_millionths: u32::max_value(),
5141 excess_data: Vec::new()
5143 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5144 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5145 short_channel_id: 4,
5148 cltv_expiry_delta: (4 << 4) | 1,
5149 htlc_minimum_msat: 0,
5150 htlc_maximum_msat: MAX_VALUE_MSAT,
5152 fee_proportional_millionths: 0,
5153 excess_data: Vec::new()
5155 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5157 short_channel_id: 13,
5159 flags: 0|2, // Channel disabled
5160 cltv_expiry_delta: (13 << 4) | 1,
5161 htlc_minimum_msat: 0,
5162 htlc_maximum_msat: MAX_VALUE_MSAT,
5164 fee_proportional_millionths: 2000000,
5165 excess_data: Vec::new()
5168 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5170 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5171 assert_eq!(route.paths.len(), 2);
5172 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5173 // Paths are manually ordered ordered by SCID, so:
5174 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5175 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5176 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5177 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5178 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5179 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5180 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5181 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5182 assert_eq!(route.get_total_fees(), 1);
5183 assert_eq!(route.get_total_amount(), 100_000);
5187 fn drop_lowest_channel_mpp_route_test() {
5188 // This test checks that low-capacity channel is dropped when after
5189 // path finding we realize that we found more capacity than we need.
5190 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5191 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5192 let scorer = ln_test_utils::TestScorer::new();
5193 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5194 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5195 let config = UserConfig::default();
5196 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5197 .with_max_channel_saturation_power_of_half(0);
5199 // We need a route consisting of 3 paths:
5200 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5202 // The first and the second paths should be sufficient, but the third should be
5203 // cheaper, so that we select it but drop later.
5205 // First, we set limits on these (previously unlimited) channels.
5206 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5208 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5209 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5211 short_channel_id: 1,
5214 cltv_expiry_delta: 0,
5215 htlc_minimum_msat: 0,
5216 htlc_maximum_msat: 100_000,
5218 fee_proportional_millionths: 0,
5219 excess_data: Vec::new()
5221 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5223 short_channel_id: 3,
5226 cltv_expiry_delta: 0,
5227 htlc_minimum_msat: 0,
5228 htlc_maximum_msat: 50_000,
5230 fee_proportional_millionths: 0,
5231 excess_data: Vec::new()
5234 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5235 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5237 short_channel_id: 12,
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()
5247 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5249 short_channel_id: 13,
5252 cltv_expiry_delta: 0,
5253 htlc_minimum_msat: 0,
5254 htlc_maximum_msat: 60_000,
5256 fee_proportional_millionths: 0,
5257 excess_data: Vec::new()
5260 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5261 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5263 short_channel_id: 2,
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()
5273 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5275 short_channel_id: 4,
5278 cltv_expiry_delta: 0,
5279 htlc_minimum_msat: 0,
5280 htlc_maximum_msat: 20_000,
5282 fee_proportional_millionths: 0,
5283 excess_data: Vec::new()
5287 // Attempt to route more than available results in a failure.
5288 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5289 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5290 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5291 } else { panic!(); }
5295 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5296 // Our algorithm should provide us with these 3 paths.
5297 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5298 assert_eq!(route.paths.len(), 3);
5299 let mut total_amount_paid_msat = 0;
5300 for path in &route.paths {
5301 assert_eq!(path.hops.len(), 2);
5302 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5303 total_amount_paid_msat += path.final_value_msat();
5305 assert_eq!(total_amount_paid_msat, 125_000);
5309 // Attempt to route without the last small cheap channel
5310 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5311 assert_eq!(route.paths.len(), 2);
5312 let mut total_amount_paid_msat = 0;
5313 for path in &route.paths {
5314 assert_eq!(path.hops.len(), 2);
5315 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5316 total_amount_paid_msat += path.final_value_msat();
5318 assert_eq!(total_amount_paid_msat, 90_000);
5323 fn min_criteria_consistency() {
5324 // Test that we don't use an inconsistent metric between updating and walking nodes during
5325 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5326 // was updated with a different criterion from the heap sorting, resulting in loops in
5327 // calculated paths. We test for that specific case here.
5329 // We construct a network that looks like this:
5331 // node2 -1(3)2- node3
5335 // node1 -1(5)2- node4 -1(1)2- node6
5341 // We create a loop on the side of our real path - our destination is node 6, with a
5342 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5343 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5344 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5345 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5346 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5347 // "previous hop" being set to node 3, creating a loop in the path.
5348 let secp_ctx = Secp256k1::new();
5349 let logger = Arc::new(ln_test_utils::TestLogger::new());
5350 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5351 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5352 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5353 let scorer = ln_test_utils::TestScorer::new();
5354 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5355 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5356 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5358 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5359 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5360 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5361 short_channel_id: 6,
5364 cltv_expiry_delta: (6 << 4) | 0,
5365 htlc_minimum_msat: 0,
5366 htlc_maximum_msat: MAX_VALUE_MSAT,
5368 fee_proportional_millionths: 0,
5369 excess_data: Vec::new()
5371 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5373 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5374 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5376 short_channel_id: 5,
5379 cltv_expiry_delta: (5 << 4) | 0,
5380 htlc_minimum_msat: 0,
5381 htlc_maximum_msat: MAX_VALUE_MSAT,
5383 fee_proportional_millionths: 0,
5384 excess_data: Vec::new()
5386 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5388 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5389 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5390 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5391 short_channel_id: 4,
5394 cltv_expiry_delta: (4 << 4) | 0,
5395 htlc_minimum_msat: 0,
5396 htlc_maximum_msat: MAX_VALUE_MSAT,
5398 fee_proportional_millionths: 0,
5399 excess_data: Vec::new()
5401 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5403 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5404 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5406 short_channel_id: 3,
5409 cltv_expiry_delta: (3 << 4) | 0,
5410 htlc_minimum_msat: 0,
5411 htlc_maximum_msat: MAX_VALUE_MSAT,
5413 fee_proportional_millionths: 0,
5414 excess_data: Vec::new()
5416 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5418 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5419 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5420 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5421 short_channel_id: 2,
5424 cltv_expiry_delta: (2 << 4) | 0,
5425 htlc_minimum_msat: 0,
5426 htlc_maximum_msat: MAX_VALUE_MSAT,
5428 fee_proportional_millionths: 0,
5429 excess_data: Vec::new()
5432 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5433 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5435 short_channel_id: 1,
5438 cltv_expiry_delta: (1 << 4) | 0,
5439 htlc_minimum_msat: 100,
5440 htlc_maximum_msat: MAX_VALUE_MSAT,
5442 fee_proportional_millionths: 0,
5443 excess_data: Vec::new()
5445 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5448 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5449 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5450 assert_eq!(route.paths.len(), 1);
5451 assert_eq!(route.paths[0].hops.len(), 3);
5453 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5454 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5455 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5456 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5457 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5458 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5460 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5461 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5462 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5463 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5464 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5465 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5467 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5468 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5469 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5470 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5471 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5472 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5478 fn exact_fee_liquidity_limit() {
5479 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5480 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5481 // we calculated fees on a higher value, resulting in us ignoring such paths.
5482 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5483 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5484 let scorer = ln_test_utils::TestScorer::new();
5485 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5486 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5487 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5489 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5491 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5492 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5493 short_channel_id: 2,
5496 cltv_expiry_delta: 0,
5497 htlc_minimum_msat: 0,
5498 htlc_maximum_msat: 85_000,
5500 fee_proportional_millionths: 0,
5501 excess_data: Vec::new()
5504 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5505 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5506 short_channel_id: 12,
5509 cltv_expiry_delta: (4 << 4) | 1,
5510 htlc_minimum_msat: 0,
5511 htlc_maximum_msat: 270_000,
5513 fee_proportional_millionths: 1000000,
5514 excess_data: Vec::new()
5518 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5519 // 200% fee charged channel 13 in the 1-to-2 direction.
5520 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5521 assert_eq!(route.paths.len(), 1);
5522 assert_eq!(route.paths[0].hops.len(), 2);
5524 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5525 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5526 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5527 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5528 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5529 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5531 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5532 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5533 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5534 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5535 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5536 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5541 fn htlc_max_reduction_below_min() {
5542 // Test that if, while walking the graph, we reduce the value being sent to meet an
5543 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5544 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5545 // resulting in us thinking there is no possible path, even if other paths exist.
5546 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5547 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5548 let scorer = ln_test_utils::TestScorer::new();
5549 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5550 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5551 let config = UserConfig::default();
5552 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5554 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5555 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5556 // then try to send 90_000.
5557 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5559 short_channel_id: 2,
5562 cltv_expiry_delta: 0,
5563 htlc_minimum_msat: 0,
5564 htlc_maximum_msat: 80_000,
5566 fee_proportional_millionths: 0,
5567 excess_data: Vec::new()
5569 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5571 short_channel_id: 4,
5574 cltv_expiry_delta: (4 << 4) | 1,
5575 htlc_minimum_msat: 90_000,
5576 htlc_maximum_msat: MAX_VALUE_MSAT,
5578 fee_proportional_millionths: 0,
5579 excess_data: Vec::new()
5583 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5584 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5585 // expensive) channels 12-13 path.
5586 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5587 assert_eq!(route.paths.len(), 1);
5588 assert_eq!(route.paths[0].hops.len(), 2);
5590 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5591 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5592 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5593 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5594 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5595 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5597 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5598 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5599 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5600 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5601 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5602 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5607 fn multiple_direct_first_hops() {
5608 // Previously we'd only ever considered one first hop path per counterparty.
5609 // However, as we don't restrict users to one channel per peer, we really need to support
5610 // looking at all first hop paths.
5611 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5612 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5613 // route over multiple channels with the same first hop.
5614 let secp_ctx = Secp256k1::new();
5615 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5616 let logger = Arc::new(ln_test_utils::TestLogger::new());
5617 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5618 let scorer = ln_test_utils::TestScorer::new();
5619 let config = UserConfig::default();
5620 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5621 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5622 let random_seed_bytes = keys_manager.get_secure_random_bytes();
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), 200_000),
5627 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5628 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5629 assert_eq!(route.paths.len(), 1);
5630 assert_eq!(route.paths[0].hops.len(), 1);
5632 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5633 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5634 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5637 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5638 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5639 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5640 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5641 assert_eq!(route.paths.len(), 2);
5642 assert_eq!(route.paths[0].hops.len(), 1);
5643 assert_eq!(route.paths[1].hops.len(), 1);
5645 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5646 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5648 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5649 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5651 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5652 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5656 // If we have a bunch of outbound channels to the same node, where most are not
5657 // sufficient to pay the full payment, but one is, we should default to just using the
5658 // one single channel that has sufficient balance, avoiding MPP.
5660 // If we have several options above the 3xpayment value threshold, we should pick the
5661 // smallest of them, avoiding further fragmenting our available outbound balance to
5663 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5664 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5665 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5666 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5667 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5668 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5669 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5670 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5671 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5672 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5673 assert_eq!(route.paths.len(), 1);
5674 assert_eq!(route.paths[0].hops.len(), 1);
5676 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5677 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5678 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5683 fn prefers_shorter_route_with_higher_fees() {
5684 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5685 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5686 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5688 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5689 let scorer = ln_test_utils::TestScorer::new();
5690 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5691 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5692 let route = get_route(
5693 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5694 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5696 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5698 assert_eq!(route.get_total_fees(), 100);
5699 assert_eq!(route.get_total_amount(), 100);
5700 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5702 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5703 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5704 let scorer = FixedPenaltyScorer::with_penalty(100);
5705 let route = get_route(
5706 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5707 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5709 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5711 assert_eq!(route.get_total_fees(), 300);
5712 assert_eq!(route.get_total_amount(), 100);
5713 assert_eq!(path, vec![2, 4, 7, 10]);
5716 struct BadChannelScorer {
5717 short_channel_id: u64,
5721 impl Writeable for BadChannelScorer {
5722 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5724 impl Score for BadChannelScorer {
5725 type ScoreParams = ();
5726 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5727 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5730 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5731 fn payment_path_successful(&mut self, _path: &Path) {}
5732 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5733 fn probe_successful(&mut self, _path: &Path) {}
5736 struct BadNodeScorer {
5741 impl Writeable for BadNodeScorer {
5742 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5745 impl Score for BadNodeScorer {
5746 type ScoreParams = ();
5747 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5748 if *target == self.node_id { u64::max_value() } else { 0 }
5751 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5752 fn payment_path_successful(&mut self, _path: &Path) {}
5753 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5754 fn probe_successful(&mut self, _path: &Path) {}
5758 fn avoids_routing_through_bad_channels_and_nodes() {
5759 let (secp_ctx, network, _, _, logger) = build_graph();
5760 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5761 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5762 let network_graph = network.read_only();
5764 // A path to nodes[6] exists when no penalties are applied to any channel.
5765 let scorer = ln_test_utils::TestScorer::new();
5766 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5767 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5768 let route = get_route(
5769 &our_id, &payment_params, &network_graph, None, 100,
5770 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5772 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5774 assert_eq!(route.get_total_fees(), 100);
5775 assert_eq!(route.get_total_amount(), 100);
5776 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5778 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5779 let scorer = BadChannelScorer { short_channel_id: 6 };
5780 let route = get_route(
5781 &our_id, &payment_params, &network_graph, None, 100,
5782 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5784 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5786 assert_eq!(route.get_total_fees(), 300);
5787 assert_eq!(route.get_total_amount(), 100);
5788 assert_eq!(path, vec![2, 4, 7, 10]);
5790 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5791 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5793 &our_id, &payment_params, &network_graph, None, 100,
5794 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5796 Err(LightningError { err, .. } ) => {
5797 assert_eq!(err, "Failed to find a path to the given destination");
5799 Ok(_) => panic!("Expected error"),
5804 fn total_fees_single_path() {
5806 paths: vec![Path { hops: vec![
5808 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5809 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5810 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5813 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5814 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5815 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5818 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5819 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5820 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5822 ], blinded_tail: None }],
5823 payment_params: None,
5826 assert_eq!(route.get_total_fees(), 250);
5827 assert_eq!(route.get_total_amount(), 225);
5831 fn total_fees_multi_path() {
5833 paths: vec![Path { hops: vec![
5835 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5836 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5837 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5840 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5841 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5842 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5844 ], blinded_tail: None }, Path { hops: vec![
5846 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5847 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5848 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5851 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5852 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5853 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5855 ], blinded_tail: None }],
5856 payment_params: None,
5859 assert_eq!(route.get_total_fees(), 200);
5860 assert_eq!(route.get_total_amount(), 300);
5864 fn total_empty_route_no_panic() {
5865 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5866 // would both panic if the route was completely empty. We test to ensure they return 0
5867 // here, even though its somewhat nonsensical as a route.
5868 let route = Route { paths: Vec::new(), payment_params: None };
5870 assert_eq!(route.get_total_fees(), 0);
5871 assert_eq!(route.get_total_amount(), 0);
5875 fn limits_total_cltv_delta() {
5876 let (secp_ctx, network, _, _, logger) = build_graph();
5877 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5878 let network_graph = network.read_only();
5880 let scorer = ln_test_utils::TestScorer::new();
5882 // Make sure that generally there is at least one route available
5883 let feasible_max_total_cltv_delta = 1008;
5884 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5885 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5886 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5887 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5888 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5889 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5890 assert_ne!(path.len(), 0);
5892 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5893 let fail_max_total_cltv_delta = 23;
5894 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5895 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5896 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5898 Err(LightningError { err, .. } ) => {
5899 assert_eq!(err, "Failed to find a path to the given destination");
5901 Ok(_) => panic!("Expected error"),
5906 fn avoids_recently_failed_paths() {
5907 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5908 // randomly inserting channels into it until we can't find a route anymore.
5909 let (secp_ctx, network, _, _, logger) = build_graph();
5910 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5911 let network_graph = network.read_only();
5913 let scorer = ln_test_utils::TestScorer::new();
5914 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5915 .with_max_path_count(1);
5916 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5917 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5919 // We should be able to find a route initially, and then after we fail a few random
5920 // channels eventually we won't be able to any longer.
5921 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5923 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5924 for chan in route.paths[0].hops.iter() {
5925 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5927 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5928 % route.paths[0].hops.len();
5929 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5935 fn limits_path_length() {
5936 let (secp_ctx, network, _, _, logger) = build_line_graph();
5937 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5938 let network_graph = network.read_only();
5940 let scorer = ln_test_utils::TestScorer::new();
5941 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5942 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5944 // First check we can actually create a long route on this graph.
5945 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5946 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5947 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5948 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5949 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5951 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5952 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5953 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5954 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5956 Err(LightningError { err, .. } ) => {
5957 assert_eq!(err, "Failed to find a path to the given destination");
5959 Ok(_) => panic!("Expected error"),
5964 fn adds_and_limits_cltv_offset() {
5965 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5966 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5968 let scorer = ln_test_utils::TestScorer::new();
5970 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5971 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5972 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5973 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5974 assert_eq!(route.paths.len(), 1);
5976 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5978 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5979 let mut route_default = route.clone();
5980 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5981 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5982 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5983 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5984 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5986 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5987 let mut route_limited = route.clone();
5988 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5989 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5990 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5991 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5992 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5996 fn adds_plausible_cltv_offset() {
5997 let (secp_ctx, network, _, _, logger) = build_graph();
5998 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5999 let network_graph = network.read_only();
6000 let network_nodes = network_graph.nodes();
6001 let network_channels = network_graph.channels();
6002 let scorer = ln_test_utils::TestScorer::new();
6003 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6004 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6005 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6007 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
6008 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6009 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6011 let mut path_plausibility = vec![];
6013 for p in route.paths {
6014 // 1. Select random observation point
6015 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6016 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6018 prng.process_in_place(&mut random_bytes);
6019 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6020 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6022 // 2. Calculate what CLTV expiry delta we would observe there
6023 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6025 // 3. Starting from the observation point, find candidate paths
6026 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6027 candidates.push_back((observation_point, vec![]));
6029 let mut found_plausible_candidate = false;
6031 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6032 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6033 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6034 found_plausible_candidate = true;
6035 break 'candidate_loop;
6039 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6040 for channel_id in &cur_node.channels {
6041 if let Some(channel_info) = network_channels.get(&channel_id) {
6042 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6043 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6044 if cur_path_cltv_deltas.iter().sum::<u32>()
6045 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6046 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6047 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6048 candidates.push_back((*next_id, new_path_cltv_deltas));
6056 path_plausibility.push(found_plausible_candidate);
6058 assert!(path_plausibility.iter().all(|x| *x));
6062 fn builds_correct_path_from_hops() {
6063 let (secp_ctx, network, _, _, logger) = build_graph();
6064 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6065 let network_graph = network.read_only();
6067 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6068 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6070 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6071 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6072 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
6073 &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
6074 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6075 assert_eq!(hops.len(), route.paths[0].hops.len());
6076 for (idx, hop_pubkey) in hops.iter().enumerate() {
6077 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6082 fn avoids_saturating_channels() {
6083 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6084 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6085 let decay_params = ProbabilisticScoringDecayParameters::default();
6086 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6088 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6089 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6090 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6092 short_channel_id: 4,
6095 cltv_expiry_delta: (4 << 4) | 1,
6096 htlc_minimum_msat: 0,
6097 htlc_maximum_msat: 250_000_000,
6099 fee_proportional_millionths: 0,
6100 excess_data: Vec::new()
6102 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6104 short_channel_id: 13,
6107 cltv_expiry_delta: (13 << 4) | 1,
6108 htlc_minimum_msat: 0,
6109 htlc_maximum_msat: 250_000_000,
6111 fee_proportional_millionths: 0,
6112 excess_data: Vec::new()
6115 let config = UserConfig::default();
6116 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6117 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6118 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6119 // 100,000 sats is less than the available liquidity on each channel, set above.
6120 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();
6121 assert_eq!(route.paths.len(), 2);
6122 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6123 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6126 #[cfg(not(feature = "no-std"))]
6127 pub(super) fn random_init_seed() -> u64 {
6128 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6129 use core::hash::{BuildHasher, Hasher};
6130 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6131 println!("Using seed of {}", seed);
6136 #[cfg(not(feature = "no-std"))]
6137 fn generate_routes() {
6138 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6140 let logger = ln_test_utils::TestLogger::new();
6141 let graph = match super::bench_utils::read_network_graph(&logger) {
6149 let params = ProbabilisticScoringFeeParameters::default();
6150 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6151 let features = super::Bolt11InvoiceFeatures::empty();
6153 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6157 #[cfg(not(feature = "no-std"))]
6158 fn generate_routes_mpp() {
6159 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6161 let logger = ln_test_utils::TestLogger::new();
6162 let graph = match super::bench_utils::read_network_graph(&logger) {
6170 let params = ProbabilisticScoringFeeParameters::default();
6171 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6172 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6174 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6178 #[cfg(not(feature = "no-std"))]
6179 fn generate_large_mpp_routes() {
6180 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6182 let logger = ln_test_utils::TestLogger::new();
6183 let graph = match super::bench_utils::read_network_graph(&logger) {
6191 let params = ProbabilisticScoringFeeParameters::default();
6192 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6193 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6195 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6199 fn honors_manual_penalties() {
6200 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6201 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6203 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6204 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6206 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6207 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6209 // First check set manual penalties are returned by the scorer.
6210 let usage = ChannelUsage {
6212 inflight_htlc_msat: 0,
6213 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6215 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6216 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6217 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6219 // Then check we can get a normal route
6220 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6221 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6222 assert!(route.is_ok());
6224 // Then check that we can't get a route if we ban an intermediate node.
6225 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6226 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6227 assert!(route.is_err());
6229 // Finally make sure we can route again, when we remove the ban.
6230 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6231 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6232 assert!(route.is_ok());
6236 fn abide_by_route_hint_max_htlc() {
6237 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6238 // params in the final route.
6239 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6240 let netgraph = network_graph.read_only();
6241 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6242 let scorer = ln_test_utils::TestScorer::new();
6243 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6244 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6245 let config = UserConfig::default();
6247 let max_htlc_msat = 50_000;
6248 let route_hint_1 = RouteHint(vec![RouteHintHop {
6249 src_node_id: nodes[2],
6250 short_channel_id: 42,
6253 proportional_millionths: 0,
6255 cltv_expiry_delta: 10,
6256 htlc_minimum_msat: None,
6257 htlc_maximum_msat: Some(max_htlc_msat),
6259 let dest_node_id = ln_test_utils::pubkey(42);
6260 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6261 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6262 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6264 // Make sure we'll error if our route hints don't have enough liquidity according to their
6265 // htlc_maximum_msat.
6266 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6267 &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6270 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6271 } else { panic!(); }
6273 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6274 let mut route_hint_2 = route_hint_1.clone();
6275 route_hint_2.0[0].short_channel_id = 43;
6276 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6277 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6278 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6279 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6280 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6281 assert_eq!(route.paths.len(), 2);
6282 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6283 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6287 fn direct_channel_to_hints_with_max_htlc() {
6288 // Check that if we have a first hop channel peer that's connected to multiple provided route
6289 // hints, that we properly split the payment between the route hints if needed.
6290 let logger = Arc::new(ln_test_utils::TestLogger::new());
6291 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6292 let scorer = ln_test_utils::TestScorer::new();
6293 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6294 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6295 let config = UserConfig::default();
6297 let our_node_id = ln_test_utils::pubkey(42);
6298 let intermed_node_id = ln_test_utils::pubkey(43);
6299 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6301 let amt_msat = 900_000;
6302 let max_htlc_msat = 500_000;
6303 let route_hint_1 = RouteHint(vec![RouteHintHop {
6304 src_node_id: intermed_node_id,
6305 short_channel_id: 44,
6308 proportional_millionths: 0,
6310 cltv_expiry_delta: 10,
6311 htlc_minimum_msat: None,
6312 htlc_maximum_msat: Some(max_htlc_msat),
6314 src_node_id: intermed_node_id,
6315 short_channel_id: 45,
6318 proportional_millionths: 0,
6320 cltv_expiry_delta: 10,
6321 htlc_minimum_msat: None,
6322 // Check that later route hint max htlcs don't override earlier ones
6323 htlc_maximum_msat: Some(max_htlc_msat - 50),
6325 let mut route_hint_2 = route_hint_1.clone();
6326 route_hint_2.0[0].short_channel_id = 46;
6327 route_hint_2.0[1].short_channel_id = 47;
6328 let dest_node_id = ln_test_utils::pubkey(44);
6329 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6330 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6331 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6333 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6334 Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6335 &random_seed_bytes).unwrap();
6336 assert_eq!(route.paths.len(), 2);
6337 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6338 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6339 assert_eq!(route.get_total_amount(), amt_msat);
6341 // Re-run but with two first hop channels connected to the same route hint peers that must be
6343 let first_hops = vec![
6344 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6345 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6347 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6348 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6349 &random_seed_bytes).unwrap();
6350 assert_eq!(route.paths.len(), 2);
6351 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6352 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6353 assert_eq!(route.get_total_amount(), amt_msat);
6355 // Make sure this works for blinded route hints.
6356 let blinded_path = BlindedPath {
6357 introduction_node_id: intermed_node_id,
6358 blinding_point: ln_test_utils::pubkey(42),
6360 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6361 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6364 let blinded_payinfo = BlindedPayInfo {
6366 fee_proportional_millionths: 0,
6367 htlc_minimum_msat: 1,
6368 htlc_maximum_msat: max_htlc_msat,
6369 cltv_expiry_delta: 10,
6370 features: BlindedHopFeatures::empty(),
6372 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6373 let payment_params = PaymentParameters::blinded(vec![
6374 (blinded_payinfo.clone(), blinded_path.clone()),
6375 (blinded_payinfo.clone(), blinded_path.clone())])
6376 .with_bolt12_features(bolt12_features).unwrap();
6377 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6378 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6379 &random_seed_bytes).unwrap();
6380 assert_eq!(route.paths.len(), 2);
6381 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6382 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6383 assert_eq!(route.get_total_amount(), amt_msat);
6387 fn blinded_route_ser() {
6388 let blinded_path_1 = BlindedPath {
6389 introduction_node_id: ln_test_utils::pubkey(42),
6390 blinding_point: ln_test_utils::pubkey(43),
6392 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6393 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6396 let blinded_path_2 = BlindedPath {
6397 introduction_node_id: ln_test_utils::pubkey(46),
6398 blinding_point: ln_test_utils::pubkey(47),
6400 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6401 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6404 // (De)serialize a Route with 1 blinded path out of two total paths.
6405 let mut route = Route { paths: vec![Path {
6406 hops: vec![RouteHop {
6407 pubkey: ln_test_utils::pubkey(50),
6408 node_features: NodeFeatures::empty(),
6409 short_channel_id: 42,
6410 channel_features: ChannelFeatures::empty(),
6412 cltv_expiry_delta: 0,
6414 blinded_tail: Some(BlindedTail {
6415 hops: blinded_path_1.blinded_hops,
6416 blinding_point: blinded_path_1.blinding_point,
6417 excess_final_cltv_expiry_delta: 40,
6418 final_value_msat: 100,
6420 hops: vec![RouteHop {
6421 pubkey: ln_test_utils::pubkey(51),
6422 node_features: NodeFeatures::empty(),
6423 short_channel_id: 43,
6424 channel_features: ChannelFeatures::empty(),
6426 cltv_expiry_delta: 0,
6427 }], blinded_tail: None }],
6428 payment_params: None,
6430 let encoded_route = route.encode();
6431 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6432 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6433 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6435 // (De)serialize a Route with two paths, each containing a blinded tail.
6436 route.paths[1].blinded_tail = Some(BlindedTail {
6437 hops: blinded_path_2.blinded_hops,
6438 blinding_point: blinded_path_2.blinding_point,
6439 excess_final_cltv_expiry_delta: 41,
6440 final_value_msat: 101,
6442 let encoded_route = route.encode();
6443 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6444 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6445 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6449 fn blinded_path_inflight_processing() {
6450 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6451 // account for the blinded tail's final amount_msat.
6452 let mut inflight_htlcs = InFlightHtlcs::new();
6453 let blinded_path = BlindedPath {
6454 introduction_node_id: ln_test_utils::pubkey(43),
6455 blinding_point: ln_test_utils::pubkey(48),
6456 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6459 hops: vec![RouteHop {
6460 pubkey: ln_test_utils::pubkey(42),
6461 node_features: NodeFeatures::empty(),
6462 short_channel_id: 42,
6463 channel_features: ChannelFeatures::empty(),
6465 cltv_expiry_delta: 0,
6468 pubkey: blinded_path.introduction_node_id,
6469 node_features: NodeFeatures::empty(),
6470 short_channel_id: 43,
6471 channel_features: ChannelFeatures::empty(),
6473 cltv_expiry_delta: 0,
6475 blinded_tail: Some(BlindedTail {
6476 hops: blinded_path.blinded_hops,
6477 blinding_point: blinded_path.blinding_point,
6478 excess_final_cltv_expiry_delta: 0,
6479 final_value_msat: 200,
6482 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6483 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6484 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6488 fn blinded_path_cltv_shadow_offset() {
6489 // Make sure we add a shadow offset when sending to blinded paths.
6490 let blinded_path = BlindedPath {
6491 introduction_node_id: ln_test_utils::pubkey(43),
6492 blinding_point: ln_test_utils::pubkey(44),
6494 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6495 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6498 let mut route = Route { paths: vec![Path {
6499 hops: vec![RouteHop {
6500 pubkey: ln_test_utils::pubkey(42),
6501 node_features: NodeFeatures::empty(),
6502 short_channel_id: 42,
6503 channel_features: ChannelFeatures::empty(),
6505 cltv_expiry_delta: 0,
6508 pubkey: blinded_path.introduction_node_id,
6509 node_features: NodeFeatures::empty(),
6510 short_channel_id: 43,
6511 channel_features: ChannelFeatures::empty(),
6513 cltv_expiry_delta: 0,
6516 blinded_tail: Some(BlindedTail {
6517 hops: blinded_path.blinded_hops,
6518 blinding_point: blinded_path.blinding_point,
6519 excess_final_cltv_expiry_delta: 0,
6520 final_value_msat: 200,
6522 }], payment_params: None};
6524 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6525 let (_, network_graph, _, _, _) = build_line_graph();
6526 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6527 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6528 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6532 fn simple_blinded_route_hints() {
6533 do_simple_blinded_route_hints(1);
6534 do_simple_blinded_route_hints(2);
6535 do_simple_blinded_route_hints(3);
6538 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6539 // Check that we can generate a route to a blinded path with the expected hops.
6540 let (secp_ctx, network, _, _, logger) = build_graph();
6541 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6542 let network_graph = network.read_only();
6544 let scorer = ln_test_utils::TestScorer::new();
6545 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6546 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6548 let mut blinded_path = BlindedPath {
6549 introduction_node_id: nodes[2],
6550 blinding_point: ln_test_utils::pubkey(42),
6551 blinded_hops: Vec::with_capacity(num_blinded_hops),
6553 for i in 0..num_blinded_hops {
6554 blinded_path.blinded_hops.push(
6555 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6558 let blinded_payinfo = BlindedPayInfo {
6560 fee_proportional_millionths: 500,
6561 htlc_minimum_msat: 1000,
6562 htlc_maximum_msat: 100_000_000,
6563 cltv_expiry_delta: 15,
6564 features: BlindedHopFeatures::empty(),
6567 let final_amt_msat = 1001;
6568 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6569 let route = get_route(&our_id, &payment_params, &network_graph, None, final_amt_msat , Arc::clone(&logger),
6570 &scorer, &(), &random_seed_bytes).unwrap();
6571 assert_eq!(route.paths.len(), 1);
6572 assert_eq!(route.paths[0].hops.len(), 2);
6574 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6575 assert_eq!(tail.hops, blinded_path.blinded_hops);
6576 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6577 assert_eq!(tail.final_value_msat, 1001);
6579 let final_hop = route.paths[0].hops.last().unwrap();
6580 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6581 if tail.hops.len() > 1 {
6582 assert_eq!(final_hop.fee_msat,
6583 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6584 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6586 assert_eq!(final_hop.fee_msat, 0);
6587 assert_eq!(final_hop.cltv_expiry_delta, 0);
6592 fn blinded_path_routing_errors() {
6593 // Check that we can generate a route to a blinded path with the expected hops.
6594 let (secp_ctx, network, _, _, logger) = build_graph();
6595 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6596 let network_graph = network.read_only();
6598 let scorer = ln_test_utils::TestScorer::new();
6599 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6600 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6602 let mut invalid_blinded_path = BlindedPath {
6603 introduction_node_id: nodes[2],
6604 blinding_point: ln_test_utils::pubkey(42),
6606 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6609 let blinded_payinfo = BlindedPayInfo {
6611 fee_proportional_millionths: 500,
6612 htlc_minimum_msat: 1000,
6613 htlc_maximum_msat: 100_000_000,
6614 cltv_expiry_delta: 15,
6615 features: BlindedHopFeatures::empty(),
6618 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6619 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6620 let payment_params = PaymentParameters::blinded(vec![
6621 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6622 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6623 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6624 &scorer, &(), &random_seed_bytes)
6626 Err(LightningError { err, .. }) => {
6627 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6629 _ => panic!("Expected error")
6632 invalid_blinded_path.introduction_node_id = our_id;
6633 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6634 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6635 &scorer, &(), &random_seed_bytes)
6637 Err(LightningError { err, .. }) => {
6638 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6640 _ => panic!("Expected error")
6643 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6644 invalid_blinded_path.blinded_hops.clear();
6645 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6646 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6647 &scorer, &(), &random_seed_bytes)
6649 Err(LightningError { err, .. }) => {
6650 assert_eq!(err, "0-hop blinded path provided");
6652 _ => panic!("Expected error")
6657 fn matching_intro_node_paths_provided() {
6658 // Check that if multiple blinded paths with the same intro node are provided in payment
6659 // parameters, we'll return the correct paths in the resulting MPP route.
6660 let (secp_ctx, network, _, _, logger) = build_graph();
6661 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6662 let network_graph = network.read_only();
6664 let scorer = ln_test_utils::TestScorer::new();
6665 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6666 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6667 let config = UserConfig::default();
6669 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6670 let blinded_path_1 = BlindedPath {
6671 introduction_node_id: nodes[2],
6672 blinding_point: ln_test_utils::pubkey(42),
6674 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6675 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6678 let blinded_payinfo_1 = BlindedPayInfo {
6680 fee_proportional_millionths: 0,
6681 htlc_minimum_msat: 0,
6682 htlc_maximum_msat: 30_000,
6683 cltv_expiry_delta: 0,
6684 features: BlindedHopFeatures::empty(),
6687 let mut blinded_path_2 = blinded_path_1.clone();
6688 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6689 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6690 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6692 let blinded_hints = vec![
6693 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6694 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6696 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6697 .with_bolt12_features(bolt12_features.clone()).unwrap();
6699 let route = get_route(&our_id, &payment_params, &network_graph, None,
6700 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6701 assert_eq!(route.paths.len(), 2);
6702 let mut total_amount_paid_msat = 0;
6703 for path in route.paths.into_iter() {
6704 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6705 if let Some(bt) = &path.blinded_tail {
6706 assert_eq!(bt.blinding_point,
6707 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6708 .map(|(_, bp)| bp.blinding_point).unwrap());
6709 } else { panic!(); }
6710 total_amount_paid_msat += path.final_value_msat();
6712 assert_eq!(total_amount_paid_msat, 100_000);
6716 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6717 pub(crate) mod bench_utils {
6721 use bitcoin::hashes::Hash;
6722 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6724 use crate::chain::transaction::OutPoint;
6725 use crate::sign::{EntropySource, KeysManager};
6726 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6727 use crate::ln::features::Bolt11InvoiceFeatures;
6728 use crate::routing::gossip::NetworkGraph;
6729 use crate::util::config::UserConfig;
6730 use crate::util::ser::ReadableArgs;
6731 use crate::util::test_utils::TestLogger;
6733 /// Tries to open a network graph file, or panics with a URL to fetch it.
6734 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6735 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6736 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6737 .or_else(|_| { // Fall back to guessing based on the binary location
6738 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6739 let mut path = std::env::current_exe().unwrap();
6740 path.pop(); // lightning-...
6742 path.pop(); // debug
6743 path.pop(); // target
6744 path.push("lightning");
6745 path.push("net_graph-2023-01-18.bin");
6748 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6749 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6750 let mut path = std::env::current_exe().unwrap();
6751 path.pop(); // bench...
6753 path.pop(); // debug
6754 path.pop(); // target
6755 path.pop(); // bench
6756 path.push("lightning");
6757 path.push("net_graph-2023-01-18.bin");
6760 .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");
6761 #[cfg(require_route_graph_test)]
6762 return Ok(res.unwrap());
6763 #[cfg(not(require_route_graph_test))]
6767 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6768 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6771 pub(crate) fn payer_pubkey() -> PublicKey {
6772 let secp_ctx = Secp256k1::new();
6773 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6777 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6779 channel_id: [0; 32],
6780 counterparty: ChannelCounterparty {
6781 features: channelmanager::provided_init_features(&UserConfig::default()),
6783 unspendable_punishment_reserve: 0,
6784 forwarding_info: None,
6785 outbound_htlc_minimum_msat: None,
6786 outbound_htlc_maximum_msat: None,
6788 funding_txo: Some(OutPoint {
6789 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6792 short_channel_id: Some(1),
6793 inbound_scid_alias: None,
6794 outbound_scid_alias: None,
6795 channel_value_satoshis: 10_000_000_000,
6797 balance_msat: 10_000_000_000,
6798 outbound_capacity_msat: 10_000_000_000,
6799 next_outbound_htlc_minimum_msat: 0,
6800 next_outbound_htlc_limit_msat: 10_000_000_000,
6801 inbound_capacity_msat: 0,
6802 unspendable_punishment_reserve: None,
6803 confirmations_required: None,
6804 confirmations: None,
6805 force_close_spend_delay: None,
6807 is_channel_ready: true,
6810 inbound_htlc_minimum_msat: None,
6811 inbound_htlc_maximum_msat: None,
6813 feerate_sat_per_1000_weight: None,
6814 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
6818 pub(crate) fn generate_test_routes<S: Score>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6819 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
6820 starting_amount: u64, route_count: usize,
6821 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6822 let payer = payer_pubkey();
6823 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6824 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6826 let nodes = graph.read_only().nodes().clone();
6827 let mut route_endpoints = Vec::new();
6828 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6829 // with some routes we picked being un-routable.
6830 for _ in 0..route_count * 3 / 2 {
6832 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6833 let src = PublicKey::from_slice(nodes.unordered_keys()
6834 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6835 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6836 let dst = PublicKey::from_slice(nodes.unordered_keys()
6837 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6838 let params = PaymentParameters::from_node_id(dst, 42)
6839 .with_bolt11_features(features.clone()).unwrap();
6840 let first_hop = first_hop(src);
6841 let amt = starting_amount + seed % 1_000_000;
6843 get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]),
6844 amt, &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok();
6846 // ...and seed the scorer with success and failure data...
6847 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6848 let mut score_amt = seed % 1_000_000_000;
6850 // Generate fail/success paths for a wider range of potential amounts with
6851 // MPP enabled to give us a chance to apply penalties for more potential
6853 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6854 let params = PaymentParameters::from_node_id(dst, 42)
6855 .with_bolt11_features(mpp_features).unwrap();
6857 let route_res = get_route(&payer, ¶ms, &graph.read_only(),
6858 Some(&[&first_hop]), score_amt, &TestLogger::new(), &scorer,
6859 score_params, &random_seed_bytes);
6860 if let Ok(route) = route_res {
6861 for path in route.paths {
6862 if seed & 0x80 == 0 {
6863 scorer.payment_path_successful(&path);
6865 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6866 scorer.payment_path_failed(&path, short_channel_id);
6868 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6872 // If we couldn't find a path with a higer amount, reduce and try again.
6876 route_endpoints.push((first_hop, params, amt));
6882 // Because we've changed channel scores, it's possible we'll take different routes to the
6883 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
6884 // requires a too-high CLTV delta.
6885 route_endpoints.retain(|(first_hop, params, amt)| {
6886 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6887 &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok()
6889 route_endpoints.truncate(route_count);
6890 assert_eq!(route_endpoints.len(), route_count);
6898 use crate::sign::{EntropySource, KeysManager};
6899 use crate::ln::channelmanager;
6900 use crate::ln::features::Bolt11InvoiceFeatures;
6901 use crate::routing::gossip::NetworkGraph;
6902 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
6903 use crate::util::config::UserConfig;
6904 use crate::util::logger::{Logger, Record};
6905 use crate::util::test_utils::TestLogger;
6907 use criterion::Criterion;
6909 struct DummyLogger {}
6910 impl Logger for DummyLogger {
6911 fn log(&self, _record: &Record) {}
6914 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6915 let logger = TestLogger::new();
6916 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6917 let scorer = FixedPenaltyScorer::with_penalty(0);
6918 generate_routes(bench, &network_graph, scorer, &(), Bolt11InvoiceFeatures::empty(), 0,
6919 "generate_routes_with_zero_penalty_scorer");
6922 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6923 let logger = TestLogger::new();
6924 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6925 let scorer = FixedPenaltyScorer::with_penalty(0);
6926 generate_routes(bench, &network_graph, scorer, &(),
6927 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6928 "generate_mpp_routes_with_zero_penalty_scorer");
6931 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6932 let logger = TestLogger::new();
6933 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6934 let params = ProbabilisticScoringFeeParameters::default();
6935 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6936 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
6937 "generate_routes_with_probabilistic_scorer");
6940 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6941 let logger = TestLogger::new();
6942 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6943 let params = ProbabilisticScoringFeeParameters::default();
6944 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6945 generate_routes(bench, &network_graph, scorer, ¶ms,
6946 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6947 "generate_mpp_routes_with_probabilistic_scorer");
6950 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6951 let logger = TestLogger::new();
6952 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6953 let params = ProbabilisticScoringFeeParameters::default();
6954 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6955 generate_routes(bench, &network_graph, scorer, ¶ms,
6956 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
6957 "generate_large_mpp_routes_with_probabilistic_scorer");
6960 fn generate_routes<S: Score>(
6961 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
6962 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
6963 bench_name: &'static str,
6965 let payer = bench_utils::payer_pubkey();
6966 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6967 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6969 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
6970 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
6972 // ...then benchmark finding paths between the nodes we learned.
6974 bench.bench_function(bench_name, |b| b.iter(|| {
6975 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
6976 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6977 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());