1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
29 use crate::prelude::*;
30 use crate::sync::Mutex;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
51 /// Creates a new router.
52 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
53 let random_seed_bytes = Mutex::new(random_seed_bytes);
54 Self { network_graph, logger, random_seed_bytes, scorer, score_params }
58 impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
65 params: &RouteParameters,
66 first_hops: Option<&[&ChannelDetails]>,
67 inflight_htlcs: InFlightHtlcs
68 ) -> Result<Route, LightningError> {
69 let random_seed_bytes = {
70 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
71 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).to_byte_array();
72 *locked_random_seed_bytes
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
83 /// A trait defining behavior for routing a payment.
85 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
87 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
88 /// and [`RouteParameters::final_value_msat`], respectively.
90 &self, payer: &PublicKey, route_params: &RouteParameters,
91 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
92 ) -> Result<Route, LightningError>;
94 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
96 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
97 /// and [`RouteParameters::final_value_msat`], respectively.
99 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
101 fn find_route_with_id(
102 &self, payer: &PublicKey, route_params: &RouteParameters,
103 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
104 _payment_hash: PaymentHash, _payment_id: PaymentId
105 ) -> Result<Route, LightningError> {
106 self.find_route(payer, route_params, first_hops, inflight_htlcs)
110 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
112 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
115 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
116 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
118 // Maps a channel's short channel id and its direction to the liquidity used up.
119 inflight_htlcs: &'a InFlightHtlcs,
121 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
122 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
123 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
124 ScorerAccountingForInFlightHtlcs {
131 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
132 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
133 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
134 let target = match candidate.target() {
135 Some(target) => target,
136 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
138 let short_channel_id = match candidate.short_channel_id() {
139 Some(short_channel_id) => short_channel_id,
140 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
142 let source = candidate.source();
143 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
144 &source, &target, short_channel_id
146 let usage = ChannelUsage {
147 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
151 self.scorer.channel_penalty_msat(candidate, usage, score_params)
153 self.scorer.channel_penalty_msat(candidate, usage, score_params)
158 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
159 /// in-use channel liquidity.
161 pub struct InFlightHtlcs(
162 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
163 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
164 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
166 HashMap<(u64, bool), u64>
170 /// Constructs an empty `InFlightHtlcs`.
171 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
173 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
174 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
175 if path.hops.is_empty() { return };
177 let mut cumulative_msat = 0;
178 if let Some(tail) = &path.blinded_tail {
179 cumulative_msat += tail.final_value_msat;
182 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
183 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
184 // the router excludes the payer node. In the following lines, the payer's information is
185 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
186 // in our sliding window of two.
187 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
188 .map(|hop| hop.pubkey)
189 .chain(core::iter::once(payer_node_id));
191 // Taking the reversed vector from above, we zip it with just the reversed hops list to
192 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
193 // the total amount sent.
194 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
195 cumulative_msat += next_hop.fee_msat;
197 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
198 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
199 .or_insert(cumulative_msat);
203 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
205 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
207 .entry((channel_scid, source < target))
208 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
209 .or_insert(used_msat);
212 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
214 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
215 self.0.get(&(channel_scid, source < target)).map(|v| *v)
219 impl Writeable for InFlightHtlcs {
220 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
223 impl Readable for InFlightHtlcs {
224 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
225 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
226 Ok(Self(infight_map))
230 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
231 /// that leads to it.
232 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
233 pub struct RouteHop {
234 /// The node_id of the node at this hop.
235 pub pubkey: PublicKey,
236 /// The node_announcement features of the node at this hop. For the last hop, these may be
237 /// amended to match the features present in the invoice this node generated.
238 pub node_features: NodeFeatures,
239 /// The channel that should be used from the previous hop to reach this node.
240 pub short_channel_id: u64,
241 /// The channel_announcement features of the channel that should be used from the previous hop
242 /// to reach this node.
243 pub channel_features: ChannelFeatures,
244 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
245 /// If this is the last hop in [`Path::hops`]:
246 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
247 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
249 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
251 /// The CLTV delta added for this hop.
252 /// If this is the last hop in [`Path::hops`]:
253 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
254 /// * otherwise, this is the CLTV delta expected at the destination
256 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
257 pub cltv_expiry_delta: u32,
258 /// Indicates whether this hop is possibly announced in the public network graph.
260 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
261 /// either know for sure it's announced in the public graph, or if any public channels exist
262 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
263 /// the channel to be unannounced.
265 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
266 pub maybe_announced_channel: bool,
269 impl_writeable_tlv_based!(RouteHop, {
270 (0, pubkey, required),
271 (1, maybe_announced_channel, (default_value, true)),
272 (2, node_features, required),
273 (4, short_channel_id, required),
274 (6, channel_features, required),
275 (8, fee_msat, required),
276 (10, cltv_expiry_delta, required),
279 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
280 /// their [`Bolt12Invoice`].
282 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
283 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
284 pub struct BlindedTail {
285 /// The hops of the [`BlindedPath`] provided by the recipient.
287 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
288 pub hops: Vec<BlindedHop>,
289 /// The blinding point of the [`BlindedPath`] provided by the recipient.
291 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
292 pub blinding_point: PublicKey,
293 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
294 /// inferring the destination. May be 0.
295 pub excess_final_cltv_expiry_delta: u32,
296 /// The total amount paid on this [`Path`], excluding the fees.
297 pub final_value_msat: u64,
300 impl_writeable_tlv_based!(BlindedTail, {
301 (0, hops, required_vec),
302 (2, blinding_point, required),
303 (4, excess_final_cltv_expiry_delta, required),
304 (6, final_value_msat, required),
307 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
308 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
309 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
311 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
312 pub hops: Vec<RouteHop>,
313 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
314 pub blinded_tail: Option<BlindedTail>,
318 /// Gets the fees for a given path, excluding any excess paid to the recipient.
319 pub fn fee_msat(&self) -> u64 {
320 match &self.blinded_tail {
321 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
323 // Do not count last hop of each path since that's the full value of the payment
324 self.hops.split_last().map_or(0,
325 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
330 /// Gets the total amount paid on this [`Path`], excluding the fees.
331 pub fn final_value_msat(&self) -> u64 {
332 match &self.blinded_tail {
333 Some(blinded_tail) => blinded_tail.final_value_msat,
334 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
338 /// Gets the final hop's CLTV expiry delta.
339 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
340 match &self.blinded_tail {
342 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
347 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
348 /// it can take multiple paths. Each path is composed of one or more hops through the network.
349 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
351 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
352 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
354 pub paths: Vec<Path>,
355 /// The `route_params` parameter passed to [`find_route`].
357 /// This is used by `ChannelManager` to track information which may be required for retries.
359 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
360 pub route_params: Option<RouteParameters>,
364 /// Returns the total amount of fees paid on this [`Route`].
366 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
367 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
368 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
370 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
371 pub fn get_total_fees(&self) -> u64 {
372 let overpaid_value_msat = self.route_params.as_ref()
373 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
374 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
377 /// Returns the total amount paid on this [`Route`], excluding the fees.
379 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
380 /// we had to reach the [`htlc_minimum_msat`] limits.
382 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
383 pub fn get_total_amount(&self) -> u64 {
384 self.paths.iter().map(|path| path.final_value_msat()).sum()
388 impl fmt::Display for Route {
389 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
390 log_route!(self).fmt(f)
394 const SERIALIZATION_VERSION: u8 = 1;
395 const MIN_SERIALIZATION_VERSION: u8 = 1;
397 impl Writeable for Route {
398 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
399 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
400 (self.paths.len() as u64).write(writer)?;
401 let mut blinded_tails = Vec::new();
402 for path in self.paths.iter() {
403 (path.hops.len() as u8).write(writer)?;
404 for (idx, hop) in path.hops.iter().enumerate() {
406 if let Some(blinded_tail) = &path.blinded_tail {
407 if blinded_tails.is_empty() {
408 blinded_tails = Vec::with_capacity(path.hops.len());
410 blinded_tails.push(None);
413 blinded_tails.push(Some(blinded_tail));
414 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
417 write_tlv_fields!(writer, {
418 // For compatibility with LDK versions prior to 0.0.117, we take the individual
419 // RouteParameters' fields and reconstruct them on read.
420 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
421 (2, blinded_tails, optional_vec),
422 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
423 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
429 impl Readable for Route {
430 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
431 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
432 let path_count: u64 = Readable::read(reader)?;
433 if path_count == 0 { return Err(DecodeError::InvalidValue); }
434 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
435 let mut min_final_cltv_expiry_delta = u32::max_value();
436 for _ in 0..path_count {
437 let hop_count: u8 = Readable::read(reader)?;
438 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
439 for _ in 0..hop_count {
440 hops.push(Readable::read(reader)?);
442 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
443 min_final_cltv_expiry_delta =
444 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
445 paths.push(Path { hops, blinded_tail: None });
447 _init_and_read_len_prefixed_tlv_fields!(reader, {
448 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
449 (2, blinded_tails, optional_vec),
450 (3, final_value_msat, option),
451 (5, max_total_routing_fee_msat, option)
453 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
454 if blinded_tails.len() != 0 {
455 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
456 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
457 path.blinded_tail = blinded_tail_opt;
461 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
462 let route_params = match (payment_params, final_value_msat) {
463 (Some(payment_params), Some(final_value_msat)) => {
464 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
469 Ok(Route { paths, route_params })
473 /// Parameters needed to find a [`Route`].
475 /// Passed to [`find_route`] and [`build_route_from_hops`].
476 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
477 pub struct RouteParameters {
478 /// The parameters of the failed payment path.
479 pub payment_params: PaymentParameters,
481 /// The amount in msats sent on the failed payment path.
482 pub final_value_msat: u64,
484 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
486 /// This limit also applies to the total fees that may arise while retrying failed payment
489 /// Note that values below a few sats may result in some paths being spuriously ignored.
490 pub max_total_routing_fee_msat: Option<u64>,
493 impl RouteParameters {
494 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
496 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
497 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
498 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
502 impl Writeable for RouteParameters {
503 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
504 write_tlv_fields!(writer, {
505 (0, self.payment_params, required),
506 (1, self.max_total_routing_fee_msat, option),
507 (2, self.final_value_msat, required),
508 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
509 // `RouteParameters` directly. For compatibility, we write it here.
510 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
516 impl Readable for RouteParameters {
517 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
518 _init_and_read_len_prefixed_tlv_fields!(reader, {
519 (0, payment_params, (required: ReadableArgs, 0)),
520 (1, max_total_routing_fee_msat, option),
521 (2, final_value_msat, required),
522 (4, final_cltv_delta, option),
524 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
525 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
526 if final_cltv_expiry_delta == &0 {
527 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
532 final_value_msat: final_value_msat.0.unwrap(),
533 max_total_routing_fee_msat,
538 /// Maximum total CTLV difference we allow for a full payment path.
539 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
541 /// Maximum number of paths we allow an (MPP) payment to have.
542 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
543 // limits, but for now more than 10 paths likely carries too much one-path failure.
544 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
546 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
548 // The median hop CLTV expiry delta currently seen in the network.
549 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
551 // During routing, we only consider paths shorter than our maximum length estimate.
552 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
553 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
554 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
556 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
557 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
558 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
559 // (payment_secret and total_msat) = 93 bytes for the final hop.
560 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
561 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
562 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
564 /// Information used to route a payment.
565 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
566 pub struct PaymentParameters {
567 /// Information about the payee, such as their features and route hints for their channels.
570 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
571 pub expiry_time: Option<u64>,
573 /// The maximum total CLTV delta we accept for the route.
574 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
575 pub max_total_cltv_expiry_delta: u32,
577 /// The maximum number of paths that may be used by (MPP) payments.
578 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
579 pub max_path_count: u8,
581 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
582 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
583 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
584 /// increasing failure probability for those paths.
586 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
587 /// restriction have been found. While paths which meet this criteria will be searched for, it
588 /// is ultimately up to the scorer to select them over other paths.
590 /// A value of 0 will allow payments up to and including a channel's total announced usable
591 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
594 pub max_channel_saturation_power_of_half: u8,
596 /// A list of SCIDs which this payment was previously attempted over and which caused the
597 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
599 pub previously_failed_channels: Vec<u64>,
602 impl Writeable for PaymentParameters {
603 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
604 let mut clear_hints = &vec![];
605 let mut blinded_hints = &vec![];
607 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
608 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
610 write_tlv_fields!(writer, {
611 (0, self.payee.node_id(), option),
612 (1, self.max_total_cltv_expiry_delta, required),
613 (2, self.payee.features(), option),
614 (3, self.max_path_count, required),
615 (4, *clear_hints, required_vec),
616 (5, self.max_channel_saturation_power_of_half, required),
617 (6, self.expiry_time, option),
618 (7, self.previously_failed_channels, required_vec),
619 (8, *blinded_hints, optional_vec),
620 (9, self.payee.final_cltv_expiry_delta(), option),
626 impl ReadableArgs<u32> for PaymentParameters {
627 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
628 _init_and_read_len_prefixed_tlv_fields!(reader, {
629 (0, payee_pubkey, option),
630 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
631 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
632 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
633 (4, clear_route_hints, required_vec),
634 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
635 (6, expiry_time, option),
636 (7, previously_failed_channels, optional_vec),
637 (8, blinded_route_hints, optional_vec),
638 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
640 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
641 let payee = if blinded_route_hints.len() != 0 {
642 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
644 route_hints: blinded_route_hints,
645 features: features.and_then(|f: Features| f.bolt12()),
649 route_hints: clear_route_hints,
650 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
651 features: features.and_then(|f| f.bolt11()),
652 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
656 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
657 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
659 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
661 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
667 impl PaymentParameters {
668 /// Creates a payee with the node id of the given `pubkey`.
670 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
672 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
674 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
676 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
677 max_path_count: DEFAULT_MAX_PATH_COUNT,
678 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
679 previously_failed_channels: Vec::new(),
683 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
685 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
688 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
689 /// whether your router will be allowed to find a multi-part route for this payment. If you
690 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
691 /// [`RecipientOnionFields::secret_only`].
693 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
694 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
695 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
696 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
697 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
700 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
701 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
702 /// [`PaymentParameters::expiry_time`].
703 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
704 Self::blinded(invoice.payment_paths().to_vec())
705 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
706 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
709 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
710 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
712 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
714 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
715 max_path_count: DEFAULT_MAX_PATH_COUNT,
716 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
717 previously_failed_channels: Vec::new(),
721 /// Includes the payee's features. Errors if the parameters were not initialized with
722 /// [`PaymentParameters::from_bolt12_invoice`].
724 /// This is not exported to bindings users since bindings don't support move semantics
725 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
727 Payee::Clear { .. } => Err(()),
728 Payee::Blinded { route_hints, .. } =>
729 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
733 /// Includes the payee's features. Errors if the parameters were initialized with
734 /// [`PaymentParameters::from_bolt12_invoice`].
736 /// This is not exported to bindings users since bindings don't support move semantics
737 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
739 Payee::Blinded { .. } => Err(()),
740 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
742 payee: Payee::Clear {
743 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
749 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
750 /// [`PaymentParameters::from_bolt12_invoice`].
752 /// This is not exported to bindings users since bindings don't support move semantics
753 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
755 Payee::Blinded { .. } => Err(()),
756 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
758 payee: Payee::Clear {
759 route_hints, node_id, features, final_cltv_expiry_delta,
765 /// Includes a payment expiration in seconds relative to the UNIX epoch.
767 /// This is not exported to bindings users since bindings don't support move semantics
768 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
769 Self { expiry_time: Some(expiry_time), ..self }
772 /// Includes a limit for the total CLTV expiry delta which is considered during routing
774 /// This is not exported to bindings users since bindings don't support move semantics
775 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
776 Self { max_total_cltv_expiry_delta, ..self }
779 /// Includes a limit for the maximum number of payment paths that may be used.
781 /// This is not exported to bindings users since bindings don't support move semantics
782 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
783 Self { max_path_count, ..self }
786 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
787 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
789 /// This is not exported to bindings users since bindings don't support move semantics
790 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
791 Self { max_channel_saturation_power_of_half, ..self }
795 /// The recipient of a payment, differing based on whether they've hidden their identity with route
797 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
799 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
800 /// will be included in the final [`Route`].
802 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
804 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
805 /// Features supported by the payee.
807 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
809 features: Option<Bolt12InvoiceFeatures>,
811 /// The recipient included these route hints in their BOLT11 invoice.
813 /// The node id of the payee.
815 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
816 route_hints: Vec<RouteHint>,
817 /// Features supported by the payee.
819 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
820 /// does not contain any features.
822 /// [`for_keysend`]: PaymentParameters::for_keysend
823 features: Option<Bolt11InvoiceFeatures>,
824 /// The minimum CLTV delta at the end of the route. This value must not be zero.
825 final_cltv_expiry_delta: u32,
830 fn node_id(&self) -> Option<PublicKey> {
832 Self::Clear { node_id, .. } => Some(*node_id),
836 fn node_features(&self) -> Option<NodeFeatures> {
838 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
839 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
842 fn supports_basic_mpp(&self) -> bool {
844 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
845 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
848 fn features(&self) -> Option<FeaturesRef> {
850 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
851 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
854 fn final_cltv_expiry_delta(&self) -> Option<u32> {
856 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
860 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
862 Self::Blinded { route_hints, .. } => &route_hints[..],
863 Self::Clear { .. } => &[]
867 fn unblinded_route_hints(&self) -> &[RouteHint] {
869 Self::Blinded { .. } => &[],
870 Self::Clear { route_hints, .. } => &route_hints[..]
875 enum FeaturesRef<'a> {
876 Bolt11(&'a Bolt11InvoiceFeatures),
877 Bolt12(&'a Bolt12InvoiceFeatures),
880 Bolt11(Bolt11InvoiceFeatures),
881 Bolt12(Bolt12InvoiceFeatures),
885 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
887 Self::Bolt12(f) => Some(f),
891 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
893 Self::Bolt11(f) => Some(f),
899 impl<'a> Writeable for FeaturesRef<'a> {
900 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
902 Self::Bolt11(f) => Ok(f.write(w)?),
903 Self::Bolt12(f) => Ok(f.write(w)?),
908 impl ReadableArgs<bool> for Features {
909 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
910 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
911 Ok(Self::Bolt12(Readable::read(reader)?))
915 /// A list of hops along a payment path terminating with a channel to the recipient.
916 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
917 pub struct RouteHint(pub Vec<RouteHintHop>);
919 impl Writeable for RouteHint {
920 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
921 (self.0.len() as u64).write(writer)?;
922 for hop in self.0.iter() {
929 impl Readable for RouteHint {
930 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
931 let hop_count: u64 = Readable::read(reader)?;
932 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
933 for _ in 0..hop_count {
934 hops.push(Readable::read(reader)?);
940 /// A channel descriptor for a hop along a payment path.
942 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
943 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
944 /// fields not supported in BOLT 11 will be stripped.
945 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
946 pub struct RouteHintHop {
947 /// The node_id of the non-target end of the route
948 pub src_node_id: PublicKey,
949 /// The short_channel_id of this channel
950 pub short_channel_id: u64,
951 /// The fees which must be paid to use this channel
952 pub fees: RoutingFees,
953 /// The difference in CLTV values between this node and the next node.
954 pub cltv_expiry_delta: u16,
955 /// The minimum value, in msat, which must be relayed to the next hop.
956 pub htlc_minimum_msat: Option<u64>,
957 /// The maximum value in msat available for routing with a single HTLC.
958 pub htlc_maximum_msat: Option<u64>,
961 impl_writeable_tlv_based!(RouteHintHop, {
962 (0, src_node_id, required),
963 (1, htlc_minimum_msat, option),
964 (2, short_channel_id, required),
965 (3, htlc_maximum_msat, option),
967 (6, cltv_expiry_delta, required),
970 #[derive(Eq, PartialEq)]
971 struct RouteGraphNode {
973 lowest_fee_to_node: u64,
974 total_cltv_delta: u32,
975 // The maximum value a yet-to-be-constructed payment path might flow through this node.
976 // This value is upper-bounded by us by:
977 // - how much is needed for a path being constructed
978 // - how much value can channels following this node (up to the destination) can contribute,
979 // considering their capacity and fees
980 value_contribution_msat: u64,
981 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
982 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
983 path_htlc_minimum_msat: u64,
984 /// All penalties incurred from this hop on the way to the destination, as calculated using
986 path_penalty_msat: u64,
987 /// The number of hops walked up to this node.
988 path_length_to_node: u8,
991 impl cmp::Ord for RouteGraphNode {
992 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
993 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
994 .saturating_add(other.path_penalty_msat);
995 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
996 .saturating_add(self.path_penalty_msat);
997 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
1001 impl cmp::PartialOrd for RouteGraphNode {
1002 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1003 Some(self.cmp(other))
1007 /// A wrapper around the various hop representations.
1009 /// Can be used to examine the properties of a hop,
1010 /// potentially to decide whether to include it in a route.
1011 #[derive(Clone, Debug)]
1012 pub enum CandidateRouteHop<'a> {
1013 /// A hop from the payer, where the outbound liquidity is known.
1015 /// Channel details of the first hop
1017 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1018 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1020 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1021 details: &'a ChannelDetails,
1022 /// The node id of the payer, which is also the source side of this candidate route hop.
1025 /// A hop found in the [`ReadOnlyNetworkGraph`].
1027 /// Information about the channel, including potentially its capacity and
1028 /// direction-specific information.
1029 info: DirectedChannelInfo<'a>,
1030 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1032 short_channel_id: u64,
1034 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1036 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1037 /// terminate at the payee.
1039 /// Information about the private hop communicated via BOLT 11.
1040 hint: &'a RouteHintHop,
1041 /// Node id of the next hop in BOLT 11 route hint.
1042 target_node_id: NodeId
1044 /// A blinded path which starts with an introduction point and ultimately terminates with the
1047 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1048 /// `None` in this state.
1050 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1051 /// path, the full path is treated as a single [`CandidateRouteHop`].
1053 /// Information about the blinded path including the fee, HTLC amount limits, and
1054 /// cryptographic material required to build an HTLC through the given path.
1055 hint: &'a (BlindedPayInfo, BlindedPath),
1056 /// Index of the hint in the original list of blinded hints.
1058 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1059 /// a short channel ID for this hop.
1062 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1064 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1065 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1066 /// payee's identity - it's the introduction point!
1068 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1069 /// to the hops *between* the introduction node and the destination.
1071 /// This primarily exists to track that we need to included a blinded path at the end of our
1072 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1074 /// Information about the blinded path including the fee, HTLC amount limits, and
1075 /// cryptographic material required to build an HTLC terminating with the given path.
1077 /// Note that the [`BlindedPayInfo`] is ignored here.
1078 hint: &'a (BlindedPayInfo, BlindedPath),
1079 /// Index of the hint in the original list of blinded hints.
1081 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1082 /// a short channel ID for this hop.
1087 impl<'a> CandidateRouteHop<'a> {
1088 /// Returns the short channel ID for this hop, if one is known.
1090 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1091 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1093 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1094 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1095 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1096 /// (which is always true for channels which are funded and ready for use).
1098 /// In other words, this should always return `Some` as long as the candidate hop is not a
1099 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1101 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1102 /// define a global namespace.
1103 fn short_channel_id(&self) -> Option<u64> {
1105 CandidateRouteHop::FirstHop { details, .. } => details.get_outbound_payment_scid(),
1106 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1107 CandidateRouteHop::PrivateHop { hint, .. } => Some(hint.short_channel_id),
1108 CandidateRouteHop::Blinded { .. } => None,
1109 CandidateRouteHop::OneHopBlinded { .. } => None,
1113 /// Returns the globally unique short channel ID for this hop, if one is known.
1115 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1116 /// from the public network graph), and thus the short channel ID we have for this channel is
1117 /// globally unique and identifies this channel in a global namespace.
1118 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1120 CandidateRouteHop::FirstHop { details, .. } => if details.is_public { details.short_channel_id } else { None },
1121 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1122 CandidateRouteHop::PrivateHop { .. } => None,
1123 CandidateRouteHop::Blinded { .. } => None,
1124 CandidateRouteHop::OneHopBlinded { .. } => None,
1128 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1129 fn features(&self) -> ChannelFeatures {
1131 CandidateRouteHop::FirstHop { details, .. } => details.counterparty.features.to_context(),
1132 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1133 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1134 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1135 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1139 /// Returns cltv_expiry_delta for this hop.
1140 pub fn cltv_expiry_delta(&self) -> u32 {
1142 CandidateRouteHop::FirstHop { .. } => 0,
1143 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1144 CandidateRouteHop::PrivateHop { hint, .. } => hint.cltv_expiry_delta as u32,
1145 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1146 CandidateRouteHop::OneHopBlinded { .. } => 0,
1150 /// Returns the htlc_minimum_msat for this hop.
1151 pub fn htlc_minimum_msat(&self) -> u64 {
1153 CandidateRouteHop::FirstHop { details, .. } => details.next_outbound_htlc_minimum_msat,
1154 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1155 CandidateRouteHop::PrivateHop { hint, .. } => hint.htlc_minimum_msat.unwrap_or(0),
1156 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1157 CandidateRouteHop::OneHopBlinded { .. } => 0,
1161 /// Returns the fees for this hop.
1162 pub fn fees(&self) -> RoutingFees {
1164 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1165 base_msat: 0, proportional_millionths: 0,
1167 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1168 CandidateRouteHop::PrivateHop { hint, .. } => hint.fees,
1169 CandidateRouteHop::Blinded { hint, .. } => {
1171 base_msat: hint.0.fee_base_msat,
1172 proportional_millionths: hint.0.fee_proportional_millionths
1175 CandidateRouteHop::OneHopBlinded { .. } =>
1176 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1180 fn effective_capacity(&self) -> EffectiveCapacity {
1182 CandidateRouteHop::FirstHop { details, .. } => EffectiveCapacity::ExactLiquidity {
1183 liquidity_msat: details.next_outbound_htlc_limit_msat,
1185 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1186 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. } =>
1187 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1188 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. } =>
1189 EffectiveCapacity::Infinite,
1190 CandidateRouteHop::Blinded { hint, .. } =>
1191 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1192 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1196 /// Returns an ID describing the given hop.
1198 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1199 fn id(&self) -> CandidateHopId {
1201 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1202 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1203 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1206 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1208 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1214 /// Returns the source node id of current hop.
1216 /// Source node id refers to the hop forwarding the payment.
1218 /// For `FirstHop` we return payer's node id.
1219 pub fn source(&self) -> NodeId {
1221 CandidateRouteHop::FirstHop { node_id, .. } => *node_id,
1222 CandidateRouteHop::PublicHop { info, .. } => *info.source(),
1223 CandidateRouteHop::PrivateHop { hint, .. } => hint.src_node_id.into(),
1224 CandidateRouteHop::Blinded { hint, .. } => hint.1.introduction_node_id.into(),
1225 CandidateRouteHop::OneHopBlinded { hint, .. } => hint.1.introduction_node_id.into(),
1228 /// Returns the target node id of this hop, if known.
1230 /// Target node id refers to the hop receiving the payment.
1232 /// For `Blinded` and `OneHopBlinded` we return `None` because next hop is blinded.
1233 pub fn target(&self) -> Option<NodeId> {
1235 CandidateRouteHop::FirstHop { details, .. } => Some(details.counterparty.node_id.into()),
1236 CandidateRouteHop::PublicHop { info, .. } => Some(*info.target()),
1237 CandidateRouteHop::PrivateHop { target_node_id, .. } => Some(*target_node_id),
1238 CandidateRouteHop::Blinded { .. } => None,
1239 CandidateRouteHop::OneHopBlinded { .. } => None,
1244 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1246 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1248 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1249 /// isn't guaranteed to be unique at all.
1251 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1252 /// difficult-to-use API.
1253 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1254 enum CandidateHopId {
1255 /// Contains (scid, src_node_id < target_node_id)
1257 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1262 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1263 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1265 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1266 EffectiveCapacity::Infinite => u64::max_value(),
1267 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1268 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1269 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1270 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1271 // expected to have been generated from up-to-date capacity information.
1272 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1273 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1274 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1278 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1279 -> bool where I1::Item: PartialEq<I2::Item> {
1281 let a = iter_a.next();
1282 let b = iter_b.next();
1283 if a.is_none() && b.is_none() { return true; }
1284 if a.is_none() || b.is_none() { return false; }
1285 if a.unwrap().ne(&b.unwrap()) { return false; }
1289 /// It's useful to keep track of the hops associated with the fees required to use them,
1290 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1291 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1292 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1294 struct PathBuildingHop<'a> {
1295 candidate: CandidateRouteHop<'a>,
1298 /// All the fees paid *after* this channel on the way to the destination
1299 next_hops_fee_msat: u64,
1300 /// Fee paid for the use of the current channel (see candidate.fees()).
1301 /// The value will be actually deducted from the counterparty balance on the previous link.
1302 hop_use_fee_msat: u64,
1303 /// Used to compare channels when choosing the for routing.
1304 /// Includes paying for the use of a hop and the following hops, as well as
1305 /// an estimated cost of reaching this hop.
1306 /// Might get stale when fees are recomputed. Primarily for internal use.
1307 total_fee_msat: u64,
1308 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1309 /// walk and may be invalid thereafter.
1310 path_htlc_minimum_msat: u64,
1311 /// All penalties incurred from this channel on the way to the destination, as calculated using
1312 /// channel scoring.
1313 path_penalty_msat: u64,
1314 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1315 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1316 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1317 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1318 /// avoid processing them again.
1319 was_processed: bool,
1320 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1321 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1322 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1323 // value_contribution_msat, which requires tracking it here. See comments below where it is
1324 // used for more info.
1325 value_contribution_msat: u64,
1328 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1329 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1330 let mut debug_struct = f.debug_struct("PathBuildingHop");
1332 .field("node_id", &self.candidate.target())
1333 .field("short_channel_id", &self.candidate.short_channel_id())
1334 .field("total_fee_msat", &self.total_fee_msat)
1335 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1336 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1337 .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)))
1338 .field("path_penalty_msat", &self.path_penalty_msat)
1339 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1340 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1341 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1342 let debug_struct = debug_struct
1343 .field("value_contribution_msat", &self.value_contribution_msat);
1344 debug_struct.finish()
1348 // Instantiated with a list of hops with correct data in them collected during path finding,
1349 // an instance of this struct should be further modified only via given methods.
1351 struct PaymentPath<'a> {
1352 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1355 impl<'a> PaymentPath<'a> {
1356 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1357 fn get_value_msat(&self) -> u64 {
1358 self.hops.last().unwrap().0.fee_msat
1361 fn get_path_penalty_msat(&self) -> u64 {
1362 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1365 fn get_total_fee_paid_msat(&self) -> u64 {
1366 if self.hops.len() < 1 {
1370 // Can't use next_hops_fee_msat because it gets outdated.
1371 for (i, (hop, _)) in self.hops.iter().enumerate() {
1372 if i != self.hops.len() - 1 {
1373 result += hop.fee_msat;
1379 fn get_cost_msat(&self) -> u64 {
1380 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1383 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1384 // to change fees may result in an inconsistency.
1386 // Sometimes we call this function right after constructing a path which is inconsistent in
1387 // that it the value being transferred has decreased while we were doing path finding, leading
1388 // to the fees being paid not lining up with the actual limits.
1390 // Note that this function is not aware of the available_liquidity limit, and thus does not
1391 // support increasing the value being transferred beyond what was selected during the initial
1394 // Returns the amount that this path contributes to the total payment value, which may be greater
1395 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1396 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1397 let mut extra_contribution_msat = 0;
1398 let mut total_fee_paid_msat = 0 as u64;
1399 for i in (0..self.hops.len()).rev() {
1400 let last_hop = i == self.hops.len() - 1;
1402 // For non-last-hop, this value will represent the fees paid on the current hop. It
1403 // will consist of the fees for the use of the next hop, and extra fees to match
1404 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1405 let mut cur_hop_fees_msat = 0;
1407 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1410 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1411 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1412 cur_hop.path_penalty_msat += extra_contribution_msat;
1413 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1414 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1415 // set it too high just to maliciously take more fees by exploiting this
1416 // match htlc_minimum_msat logic.
1417 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1418 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1419 // Note that there is a risk that *previous hops* (those closer to us, as we go
1420 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1422 // This might make us end up with a broken route, although this should be super-rare
1423 // in practice, both because of how healthy channels look like, and how we pick
1424 // channels in add_entry.
1425 // Also, this can't be exploited more heavily than *announce a free path and fail
1427 cur_hop_transferred_amount_msat += extra_fees_msat;
1429 // We remember and return the extra fees on the final hop to allow accounting for
1430 // them in the path's value contribution.
1432 extra_contribution_msat = extra_fees_msat;
1434 total_fee_paid_msat += extra_fees_msat;
1435 cur_hop_fees_msat += extra_fees_msat;
1440 // Final hop is a special case: it usually has just value_msat (by design), but also
1441 // it still could overpay for the htlc_minimum_msat.
1442 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1444 // Propagate updated fees for the use of the channels to one hop back, where they
1445 // will be actually paid (fee_msat). The last hop is handled above separately.
1446 cur_hop.fee_msat = cur_hop_fees_msat;
1449 // Fee for the use of the current hop which will be deducted on the previous hop.
1450 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1451 // this channel is free for us.
1453 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1454 cur_hop.hop_use_fee_msat = new_fee;
1455 total_fee_paid_msat += new_fee;
1457 // It should not be possible because this function is called only to reduce the
1458 // value. In that case, compute_fee was already called with the same fees for
1459 // larger amount and there was no overflow.
1464 value_msat + extra_contribution_msat
1469 /// Calculate the fees required to route the given amount over a channel with the given fees.
1470 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1471 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1472 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1476 /// Calculate the fees required to route the given amount over a channel with the given fees,
1477 /// saturating to [`u64::max_value`].
1478 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1479 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1480 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1481 .saturating_add(channel_fees.base_msat as u64)
1484 /// The default `features` we assume for a node in a route, when no `features` are known about that
1487 /// Default features are:
1488 /// * variable_length_onion_optional
1489 fn default_node_features() -> NodeFeatures {
1490 let mut features = NodeFeatures::empty();
1491 features.set_variable_length_onion_optional();
1495 struct LoggedPayeePubkey(Option<PublicKey>);
1496 impl fmt::Display for LoggedPayeePubkey {
1497 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1500 "payee node id ".fmt(f)?;
1504 "blinded payee".fmt(f)
1510 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1511 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1514 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1515 "blinded route hint with introduction node id ".fmt(f)?;
1516 hint.1.introduction_node_id.fmt(f)?;
1517 " and blinding point ".fmt(f)?;
1518 hint.1.blinding_point.fmt(f)
1520 CandidateRouteHop::FirstHop { .. } => {
1521 "first hop with SCID ".fmt(f)?;
1522 self.0.short_channel_id().unwrap().fmt(f)
1524 CandidateRouteHop::PrivateHop { .. } => {
1525 "route hint with SCID ".fmt(f)?;
1526 self.0.short_channel_id().unwrap().fmt(f)
1530 self.0.short_channel_id().unwrap().fmt(f)
1537 fn sort_first_hop_channels(
1538 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1539 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1541 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1542 // most like to use.
1544 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1545 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1548 // Second, because simply always sorting in descending order would always use our largest
1549 // available outbound capacity, needlessly fragmenting our available channel capacities,
1550 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1551 // which have enough, but not too much, capacity for the payment.
1553 // Available outbound balances factor in liquidity already reserved for previously found paths.
1554 channels.sort_unstable_by(|chan_a, chan_b| {
1555 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1556 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1557 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1558 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1559 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1560 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1561 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1562 // Sort in descending order
1563 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1565 // Sort in ascending order
1566 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1571 /// Finds a route from us (payer) to the given target node (payee).
1573 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1574 /// in the given [`RouteParameters::payment_params`].
1575 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1577 /// Private routing paths between a public node and the target may be included in the `payee` field
1578 /// of [`RouteParameters::payment_params`].
1580 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1581 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1582 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1584 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1585 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1586 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1590 /// Panics if first_hops contains channels without `short_channel_id`s;
1591 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1593 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1594 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1595 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1596 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1597 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1598 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1599 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1600 ) -> Result<Route, LightningError>
1601 where L::Target: Logger, GL::Target: Logger {
1602 let graph_lock = network_graph.read_only();
1603 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1604 scorer, score_params, random_seed_bytes)?;
1605 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1609 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1610 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1611 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1612 _random_seed_bytes: &[u8; 32]
1613 ) -> Result<Route, LightningError>
1614 where L::Target: Logger {
1616 let payment_params = &route_params.payment_params;
1617 let final_value_msat = route_params.final_value_msat;
1618 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1619 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1620 // so use a dummy id for this in the blinded case.
1621 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1622 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1623 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1624 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1625 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1627 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1628 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1630 if our_node_id == maybe_dummy_payee_node_id {
1631 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1634 if final_value_msat > MAX_VALUE_MSAT {
1635 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1638 if final_value_msat == 0 {
1639 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1642 match &payment_params.payee {
1643 Payee::Clear { route_hints, node_id, .. } => {
1644 for route in route_hints.iter() {
1645 for hop in &route.0 {
1646 if hop.src_node_id == *node_id {
1647 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1652 Payee::Blinded { route_hints, .. } => {
1653 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1654 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});
1656 for (_, blinded_path) in route_hints.iter() {
1657 if blinded_path.blinded_hops.len() == 0 {
1658 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1659 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1660 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1661 } else if blinded_path.blinded_hops.len() == 1 &&
1662 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1663 && p.introduction_node_id != blinded_path.introduction_node_id)
1665 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1670 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1671 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1672 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});
1675 // The general routing idea is the following:
1676 // 1. Fill first/last hops communicated by the caller.
1677 // 2. Attempt to construct a path from payer to payee for transferring
1678 // any ~sufficient (described later) value.
1679 // If succeed, remember which channels were used and how much liquidity they have available,
1680 // so that future paths don't rely on the same liquidity.
1681 // 3. Proceed to the next step if:
1682 // - we hit the recommended target value;
1683 // - OR if we could not construct a new path. Any next attempt will fail too.
1684 // Otherwise, repeat step 2.
1685 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1686 // (not recommended value).
1687 // 5. If yes, proceed. If not, fail routing.
1688 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1689 // transferred up to the transfer target value.
1690 // 7. Reduce the value of the last path until we are sending only the target value.
1691 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1692 // them so that we're not sending two HTLCs along the same path.
1694 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1695 // distance from the payee
1697 // We are not a faithful Dijkstra's implementation because we can change values which impact
1698 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1699 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1700 // the value we are currently attempting to send over a path, we simply reduce the value being
1701 // sent along the path for any hops after that channel. This may imply that later fees (which
1702 // we've already tabulated) are lower because a smaller value is passing through the channels
1703 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1704 // channels which were selected earlier (and which may still be used for other paths without a
1705 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1708 // One potentially problematic case for this algorithm would be if there are many
1709 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1710 // graph walking), we may never find a path which is not liquidity-limited and has lower
1711 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1712 // Because we only consider paths with at least 5% of the total value being sent, the damage
1713 // from such a case should be limited, however this could be further reduced in the future by
1714 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1715 // limits for the purposes of fee calculation.
1717 // Alternatively, we could store more detailed path information in the heap (targets, below)
1718 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1719 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1720 // and practically (as we would need to store dynamically-allocated path information in heap
1721 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1722 // results of such an algorithm would likely be biased towards lower-value paths.
1724 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1725 // outside of our current search value, running a path search more times to gather candidate
1726 // paths at different values. While this may be acceptable, further path searches may increase
1727 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1728 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1729 // the same time, remaining generic across different payment values.
1731 let network_channels = network_graph.channels();
1732 let network_nodes = network_graph.nodes();
1734 if payment_params.max_path_count == 0 {
1735 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1738 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1739 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1741 let allow_mpp = if payment_params.max_path_count == 1 {
1743 } else if payment_params.payee.supports_basic_mpp() {
1745 } else if let Some(payee) = payee_node_id_opt {
1746 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1747 |info| info.features.supports_basic_mpp()))
1750 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1752 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1753 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1754 if allow_mpp { "with" } else { "without" },
1755 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1756 max_total_routing_fee_msat);
1759 // Prepare the data we'll use for payee-to-payer search by
1760 // inserting first hops suggested by the caller as targets.
1761 // Our search will then attempt to reach them while traversing from the payee node.
1762 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1763 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1764 if let Some(hops) = first_hops {
1766 if chan.get_outbound_payment_scid().is_none() {
1767 panic!("first_hops should be filled in with usable channels, not pending ones");
1769 if chan.counterparty.node_id == *our_node_pubkey {
1770 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1773 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1774 .or_insert(Vec::new())
1777 if first_hop_targets.is_empty() {
1778 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1782 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1783 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1784 // adding duplicate entries when we find a better path to a given node.
1785 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1787 // Map from node_id to information about the best current path to that node, including feerate
1789 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1791 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1792 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1793 // htlc_minimum with extra fees while still finding a cheaper path.
1794 let mut hit_minimum_limit;
1796 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1797 // We start with a path_value of the exact amount we want, and if that generates a route we may
1798 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1799 // amount we want in total across paths, selecting the best subset at the end.
1800 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1801 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1802 let mut path_value_msat = final_value_msat;
1804 // Routing Fragmentation Mitigation heuristic:
1806 // Routing fragmentation across many payment paths increases the overall routing
1807 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1808 // Taking too many smaller paths also increases the chance of payment failure.
1809 // Thus to avoid this effect, we require from our collected links to provide
1810 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1811 // This requirement is currently set to be 1/max_path_count of the payment
1812 // value to ensure we only ever return routes that do not violate this limit.
1813 let minimal_value_contribution_msat: u64 = if allow_mpp {
1814 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1819 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1820 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1821 // drop the requirement by setting this to 0.
1822 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1824 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1825 // determine if the channel can be used by additional MPP paths or to inform path finding
1826 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1827 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1829 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1830 HashMap::with_capacity(network_nodes.len());
1832 // Keeping track of how much value we already collected across other paths. Helps to decide
1833 // when we want to stop looking for new paths.
1834 let mut already_collected_value_msat = 0;
1836 for (_, channels) in first_hop_targets.iter_mut() {
1837 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1841 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1842 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1844 // Remember how many candidates we ignored to allow for some logging afterwards.
1845 let mut num_ignored_value_contribution: u32 = 0;
1846 let mut num_ignored_path_length_limit: u32 = 0;
1847 let mut num_ignored_cltv_delta_limit: u32 = 0;
1848 let mut num_ignored_previously_failed: u32 = 0;
1849 let mut num_ignored_total_fee_limit: u32 = 0;
1850 let mut num_ignored_avoid_overpayment: u32 = 0;
1851 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
1853 macro_rules! add_entry {
1854 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
1855 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1856 // since that value has to be transferred over this channel.
1857 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
1858 ( $candidate: expr, $next_hops_fee_msat: expr,
1859 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1860 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1861 // We "return" whether we updated the path at the end, and how much we can route via
1862 // this channel, via this:
1863 let mut hop_contribution_amt_msat = None;
1864 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1865 // practice these cases should be caught earlier:
1866 // - for regular channels at channel announcement (TODO)
1867 // - for first and last hops early in get_route
1868 let src_node_id = $candidate.source();
1869 if Some(src_node_id) != $candidate.target() {
1870 let scid_opt = $candidate.short_channel_id();
1871 let effective_capacity = $candidate.effective_capacity();
1872 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1874 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1875 // It may be misleading because we might later choose to reduce the value transferred
1876 // over these channels, and the channel which was insufficient might become sufficient.
1877 // Worst case: we drop a good channel here because it can't cover the high following
1878 // fees caused by one expensive channel, but then this channel could have been used
1879 // if the amount being transferred over this path is lower.
1880 // We do this for now, but this is a subject for removal.
1881 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1882 let used_liquidity_msat = used_liquidities
1883 .get(&$candidate.id())
1884 .map_or(0, |used_liquidity_msat| {
1885 available_value_contribution_msat = available_value_contribution_msat
1886 .saturating_sub(*used_liquidity_msat);
1887 *used_liquidity_msat
1890 // Verify the liquidity offered by this channel complies to the minimal contribution.
1891 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1892 // Do not consider candidate hops that would exceed the maximum path length.
1893 let path_length_to_node = $next_hops_path_length + 1;
1894 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1896 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1897 // In order to already account for some of the privacy enhancing random CLTV
1898 // expiry delta offset we add on top later, we subtract a rough estimate
1899 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1900 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1901 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1902 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1903 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1904 .saturating_add($candidate.cltv_expiry_delta());
1905 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1907 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1908 // Includes paying fees for the use of the following channels.
1909 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1910 Some(result) => result,
1911 // Can't overflow due to how the values were computed right above.
1912 None => unreachable!(),
1914 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1915 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1916 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1918 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1919 let may_overpay_to_meet_path_minimum_msat =
1920 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1921 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
1922 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1923 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
1925 let payment_failed_on_this_channel = scid_opt.map_or(false,
1926 |scid| payment_params.previously_failed_channels.contains(&scid));
1928 let (should_log_candidate, first_hop_details) = match $candidate {
1929 CandidateRouteHop::FirstHop { details, .. } => (true, Some(details)),
1930 CandidateRouteHop::PrivateHop { .. } => (true, None),
1931 CandidateRouteHop::Blinded { .. } => (true, None),
1932 CandidateRouteHop::OneHopBlinded { .. } => (true, None),
1936 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1937 // bother considering this channel. If retrying with recommended_value_msat may
1938 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1939 // around again with a higher amount.
1940 if !contributes_sufficient_value {
1941 if should_log_candidate {
1942 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1944 if let Some(details) = first_hop_details {
1946 "First hop candidate next_outbound_htlc_limit_msat: {}",
1947 details.next_outbound_htlc_limit_msat,
1951 num_ignored_value_contribution += 1;
1952 } else if exceeds_max_path_length {
1953 if should_log_candidate {
1954 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1956 num_ignored_path_length_limit += 1;
1957 } else if exceeds_cltv_delta_limit {
1958 if should_log_candidate {
1959 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1961 if let Some(_) = first_hop_details {
1963 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
1964 hop_total_cltv_delta,
1965 max_total_cltv_expiry_delta,
1969 num_ignored_cltv_delta_limit += 1;
1970 } else if payment_failed_on_this_channel {
1971 if should_log_candidate {
1972 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1974 num_ignored_previously_failed += 1;
1975 } else if may_overpay_to_meet_path_minimum_msat {
1976 if should_log_candidate {
1978 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
1979 LoggedCandidateHop(&$candidate));
1981 if let Some(details) = first_hop_details {
1983 "First hop candidate next_outbound_htlc_minimum_msat: {}",
1984 details.next_outbound_htlc_minimum_msat,
1988 num_ignored_avoid_overpayment += 1;
1989 hit_minimum_limit = true;
1990 } else if over_path_minimum_msat {
1991 // Note that low contribution here (limited by available_liquidity_msat)
1992 // might violate htlc_minimum_msat on the hops which are next along the
1993 // payment path (upstream to the payee). To avoid that, we recompute
1994 // path fees knowing the final path contribution after constructing it.
1995 let curr_min = cmp::max(
1996 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
1998 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
1999 .saturating_add(curr_min);
2000 let hm_entry = dist.entry(src_node_id);
2001 let old_entry = hm_entry.or_insert_with(|| {
2002 // If there was previously no known way to access the source node
2003 // (recall it goes payee-to-payer) of short_channel_id, first add a
2004 // semi-dummy record just to compute the fees to reach the source node.
2005 // This will affect our decision on selecting short_channel_id
2006 // as a way to reach the $candidate.target() node.
2008 candidate: $candidate.clone(),
2010 next_hops_fee_msat: u64::max_value(),
2011 hop_use_fee_msat: u64::max_value(),
2012 total_fee_msat: u64::max_value(),
2013 path_htlc_minimum_msat,
2014 path_penalty_msat: u64::max_value(),
2015 was_processed: false,
2016 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2017 value_contribution_msat,
2021 #[allow(unused_mut)] // We only use the mut in cfg(test)
2022 let mut should_process = !old_entry.was_processed;
2023 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2025 // In test/fuzzing builds, we do extra checks to make sure the skipping
2026 // of already-seen nodes only happens in cases we expect (see below).
2027 if !should_process { should_process = true; }
2031 let mut hop_use_fee_msat = 0;
2032 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2034 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2035 // will have the same effective-fee
2036 if src_node_id != our_node_id {
2037 // Note that `u64::max_value` means we'll always fail the
2038 // `old_entry.total_fee_msat > total_fee_msat` check below
2039 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2040 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2043 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2044 if total_fee_msat > max_total_routing_fee_msat {
2045 if should_log_candidate {
2046 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2048 if let Some(_) = first_hop_details {
2050 "First hop candidate routing fee: {}. Limit: {}",
2052 max_total_routing_fee_msat,
2056 num_ignored_total_fee_limit += 1;
2058 let channel_usage = ChannelUsage {
2059 amount_msat: amount_to_transfer_over_msat,
2060 inflight_htlc_msat: used_liquidity_msat,
2063 let channel_penalty_msat =
2064 scorer.channel_penalty_msat($candidate,
2067 let path_penalty_msat = $next_hops_path_penalty_msat
2068 .saturating_add(channel_penalty_msat);
2069 let new_graph_node = RouteGraphNode {
2070 node_id: src_node_id,
2071 lowest_fee_to_node: total_fee_msat,
2072 total_cltv_delta: hop_total_cltv_delta,
2073 value_contribution_msat,
2074 path_htlc_minimum_msat,
2076 path_length_to_node,
2079 // Update the way of reaching $candidate.source()
2080 // with the given short_channel_id (from $candidate.target()),
2081 // if this way is cheaper than the already known
2082 // (considering the cost to "reach" this channel from the route destination,
2083 // the cost of using this channel,
2084 // and the cost of routing to the source node of this channel).
2085 // Also, consider that htlc_minimum_msat_difference, because we might end up
2086 // paying it. Consider the following exploit:
2087 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2088 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2089 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2090 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2092 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2093 // but it may require additional tracking - we don't want to double-count
2094 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2095 // can't use something that may decrease on future hops.
2096 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2097 .saturating_add(old_entry.path_penalty_msat);
2098 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2099 .saturating_add(path_penalty_msat);
2101 if !old_entry.was_processed && new_cost < old_cost {
2102 targets.push(new_graph_node);
2103 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2104 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2105 old_entry.total_fee_msat = total_fee_msat;
2106 old_entry.candidate = $candidate.clone();
2107 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2108 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2109 old_entry.path_penalty_msat = path_penalty_msat;
2110 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2112 old_entry.value_contribution_msat = value_contribution_msat;
2114 hop_contribution_amt_msat = Some(value_contribution_msat);
2115 } else if old_entry.was_processed && new_cost < old_cost {
2116 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2118 // If we're skipping processing a node which was previously
2119 // processed even though we found another path to it with a
2120 // cheaper fee, check that it was because the second path we
2121 // found (which we are processing now) has a lower value
2122 // contribution due to an HTLC minimum limit.
2124 // e.g. take a graph with two paths from node 1 to node 2, one
2125 // through channel A, and one through channel B. Channel A and
2126 // B are both in the to-process heap, with their scores set by
2127 // a higher htlc_minimum than fee.
2128 // Channel A is processed first, and the channels onwards from
2129 // node 1 are added to the to-process heap. Thereafter, we pop
2130 // Channel B off of the heap, note that it has a much more
2131 // restrictive htlc_maximum_msat, and recalculate the fees for
2132 // all of node 1's channels using the new, reduced, amount.
2134 // This would be bogus - we'd be selecting a higher-fee path
2135 // with a lower htlc_maximum_msat instead of the one we'd
2136 // already decided to use.
2137 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2139 value_contribution_msat + path_penalty_msat <
2140 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2147 if should_log_candidate {
2149 "Ignoring {} due to its htlc_minimum_msat limit.",
2150 LoggedCandidateHop(&$candidate));
2152 if let Some(details) = first_hop_details {
2154 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2155 details.next_outbound_htlc_minimum_msat,
2159 num_ignored_htlc_minimum_msat_limit += 1;
2163 hop_contribution_amt_msat
2167 let default_node_features = default_node_features();
2169 // Find ways (channels with destination) to reach a given node and store them
2170 // in the corresponding data structures (routing graph etc).
2171 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2172 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2173 // This data can later be helpful to optimize routing (pay lower fees).
2174 macro_rules! add_entries_to_cheapest_to_target_node {
2175 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
2176 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
2177 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2178 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2179 let was_processed = elem.was_processed;
2180 elem.was_processed = true;
2183 // Entries are added to dist in add_entry!() when there is a channel from a node.
2184 // Because there are no channels from payee, it will not have a dist entry at this point.
2185 // If we're processing any other node, it is always be the result of a channel from it.
2186 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2191 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2192 for details in first_channels {
2193 let candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id };
2194 add_entry!(&candidate, $fee_to_target_msat,
2195 $next_hops_value_contribution,
2196 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
2197 $next_hops_cltv_delta, $next_hops_path_length);
2201 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2204 &default_node_features
2207 if !features.requires_unknown_bits() {
2208 for chan_id in $node.channels.iter() {
2209 let chan = network_channels.get(chan_id).unwrap();
2210 if !chan.features.requires_unknown_bits() {
2211 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2212 if first_hops.is_none() || *source != our_node_id {
2213 if directed_channel.direction().enabled {
2214 let candidate = CandidateRouteHop::PublicHop {
2215 info: directed_channel,
2216 short_channel_id: *chan_id,
2218 add_entry!(&candidate,
2219 $fee_to_target_msat,
2220 $next_hops_value_contribution,
2221 $next_hops_path_htlc_minimum_msat,
2222 $next_hops_path_penalty_msat,
2223 $next_hops_cltv_delta, $next_hops_path_length);
2234 let mut payment_paths = Vec::<PaymentPath>::new();
2236 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2237 'paths_collection: loop {
2238 // For every new path, start from scratch, except for used_liquidities, which
2239 // helps to avoid reusing previously selected paths in future iterations.
2242 hit_minimum_limit = false;
2244 // If first hop is a private channel and the only way to reach the payee, this is the only
2245 // place where it could be added.
2246 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2247 for details in first_channels {
2248 let candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id };
2249 let added = add_entry!(&candidate, 0, path_value_msat,
2250 0, 0u64, 0, 0).is_some();
2251 log_trace!(logger, "{} direct route to payee via {}",
2252 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2256 // Add the payee as a target, so that the payee-to-payer
2257 // search algorithm knows what to start with.
2258 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2259 // The payee is not in our network graph, so nothing to add here.
2260 // There is still a chance of reaching them via last_hops though,
2261 // so don't yet fail the payment here.
2262 // If not, targets.pop() will not even let us enter the loop in step 2.
2265 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2270 // If a caller provided us with last hops, add them to routing targets. Since this happens
2271 // earlier than general path finding, they will be somewhat prioritized, although currently
2272 // it matters only if the fees are exactly the same.
2273 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2274 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2275 let have_intro_node_in_graph =
2276 // Only add the hops in this route to our candidate set if either
2277 // we have a direct channel to the first hop or the first hop is
2278 // in the regular network graph.
2279 first_hop_targets.get(&intro_node_id).is_some() ||
2280 network_nodes.get(&intro_node_id).is_some();
2281 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2282 let candidate = if hint.1.blinded_hops.len() == 1 {
2283 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2284 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2285 let mut path_contribution_msat = path_value_msat;
2286 if let Some(hop_used_msat) = add_entry!(&candidate,
2287 0, path_contribution_msat, 0, 0_u64, 0, 0)
2289 path_contribution_msat = hop_used_msat;
2291 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2292 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2294 for details in first_channels {
2295 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2296 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2300 let path_min = candidate.htlc_minimum_msat().saturating_add(
2301 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2302 add_entry!(&first_hop_candidate, blinded_path_fee,
2303 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2304 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2308 for route in payment_params.payee.unblinded_route_hints().iter()
2309 .filter(|route| !route.0.is_empty())
2311 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2312 let first_hop_src_is_reachable =
2313 // Only add the hops in this route to our candidate set if either we are part of
2314 // the first hop, we have a direct channel to the first hop, or the first hop is in
2315 // the regular network graph.
2316 our_node_id == first_hop_src_id ||
2317 first_hop_targets.get(&first_hop_src_id).is_some() ||
2318 network_nodes.get(&first_hop_src_id).is_some();
2319 if first_hop_src_is_reachable {
2320 // We start building the path from reverse, i.e., from payee
2321 // to the first RouteHintHop in the path.
2322 let hop_iter = route.0.iter().rev();
2323 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2324 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2325 let mut hop_used = true;
2326 let mut aggregate_next_hops_fee_msat: u64 = 0;
2327 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2328 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2329 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2330 let mut aggregate_next_hops_path_length: u8 = 0;
2331 let mut aggregate_path_contribution_msat = path_value_msat;
2333 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2334 let source = NodeId::from_pubkey(&hop.src_node_id);
2335 let target = NodeId::from_pubkey(&prev_hop_id);
2337 if let Some(first_channels) = first_hop_targets.get(&target) {
2338 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2339 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2340 hop.short_channel_id);
2345 let candidate = network_channels
2346 .get(&hop.short_channel_id)
2347 .and_then(|channel| channel.as_directed_to(&target))
2348 .map(|(info, _)| CandidateRouteHop::PublicHop {
2350 short_channel_id: hop.short_channel_id,
2352 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop, target_node_id: target });
2354 if let Some(hop_used_msat) = add_entry!(&candidate,
2355 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2356 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2357 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2359 aggregate_path_contribution_msat = hop_used_msat;
2361 // If this hop was not used then there is no use checking the preceding
2362 // hops in the RouteHint. We can break by just searching for a direct
2363 // channel between last checked hop and first_hop_targets.
2367 let used_liquidity_msat = used_liquidities
2368 .get(&candidate.id()).copied()
2370 let channel_usage = ChannelUsage {
2371 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2372 inflight_htlc_msat: used_liquidity_msat,
2373 effective_capacity: candidate.effective_capacity(),
2375 let channel_penalty_msat = scorer.channel_penalty_msat(
2376 &candidate, channel_usage, score_params
2378 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2379 .saturating_add(channel_penalty_msat);
2381 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2382 .saturating_add(hop.cltv_expiry_delta as u32);
2384 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2387 // Searching for a direct channel between last checked hop and first_hop_targets
2388 if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2389 sort_first_hop_channels(first_channels, &used_liquidities,
2390 recommended_value_msat, our_node_pubkey);
2391 for details in first_channels {
2392 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2393 add_entry!(&first_hop_candidate,
2394 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2395 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2396 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2404 // In the next values of the iterator, the aggregate fees already reflects
2405 // the sum of value sent from payer (final_value_msat) and routing fees
2406 // for the last node in the RouteHint. We need to just add the fees to
2407 // route through the current node so that the preceding node (next iteration)
2409 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2410 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2411 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2413 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2414 // this route hint's source node to forward said min over this channel.
2415 aggregate_next_hops_path_htlc_minimum_msat = {
2416 let curr_htlc_min = cmp::max(
2417 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2419 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2420 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2423 if idx == route.0.len() - 1 {
2424 // The last hop in this iterator is the first hop in
2425 // overall RouteHint.
2426 // If this hop connects to a node with which we have a direct channel,
2427 // ignore the network graph and, if the last hop was added, add our
2428 // direct channel to the candidate set.
2430 // Note that we *must* check if the last hop was added as `add_entry`
2431 // always assumes that the third argument is a node to which we have a
2433 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2434 sort_first_hop_channels(first_channels, &used_liquidities,
2435 recommended_value_msat, our_node_pubkey);
2436 for details in first_channels {
2437 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2438 add_entry!(&first_hop_candidate,
2439 aggregate_next_hops_fee_msat,
2440 aggregate_path_contribution_msat,
2441 aggregate_next_hops_path_htlc_minimum_msat,
2442 aggregate_next_hops_path_penalty_msat,
2443 aggregate_next_hops_cltv_delta,
2444 aggregate_next_hops_path_length);
2452 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2454 // At this point, targets are filled with the data from first and
2455 // last hops communicated by the caller, and the payment receiver.
2456 let mut found_new_path = false;
2459 // If this loop terminates due the exhaustion of targets, two situations are possible:
2460 // - not enough outgoing liquidity:
2461 // 0 < already_collected_value_msat < final_value_msat
2462 // - enough outgoing liquidity:
2463 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2464 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2465 // paths_collection will be stopped because found_new_path==false.
2466 // This is not necessarily a routing failure.
2467 '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() {
2469 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2470 // traversing the graph and arrange the path out of what we found.
2471 if node_id == our_node_id {
2472 let mut new_entry = dist.remove(&our_node_id).unwrap();
2473 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2476 let mut features_set = false;
2477 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2478 if let Some(first_channels) = first_hop_targets.get(&target) {
2479 for details in first_channels {
2480 if let CandidateRouteHop::FirstHop { details: last_hop_details, .. }
2481 = ordered_hops.last().unwrap().0.candidate
2483 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2484 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2485 features_set = true;
2492 if let Some(node) = network_nodes.get(&target) {
2493 if let Some(node_info) = node.announcement_info.as_ref() {
2494 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2496 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2499 // We can fill in features for everything except hops which were
2500 // provided via the invoice we're paying. We could guess based on the
2501 // recipient's features but for now we simply avoid guessing at all.
2505 // Means we succesfully traversed from the payer to the payee, now
2506 // save this path for the payment route. Also, update the liquidity
2507 // remaining on the used hops, so that we take them into account
2508 // while looking for more paths.
2509 if target == maybe_dummy_payee_node_id {
2513 new_entry = match dist.remove(&target) {
2514 Some(payment_hop) => payment_hop,
2515 // We can't arrive at None because, if we ever add an entry to targets,
2516 // we also fill in the entry in dist (see add_entry!).
2517 None => unreachable!(),
2519 // We "propagate" the fees one hop backward (topologically) here,
2520 // so that fees paid for a HTLC forwarding on the current channel are
2521 // associated with the previous channel (where they will be subtracted).
2522 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2523 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2525 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2526 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2528 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2529 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2531 let mut payment_path = PaymentPath {hops: ordered_hops};
2533 // We could have possibly constructed a slightly inconsistent path: since we reduce
2534 // value being transferred along the way, we could have violated htlc_minimum_msat
2535 // on some channels we already passed (assuming dest->source direction). Here, we
2536 // recompute the fees again, so that if that's the case, we match the currently
2537 // underpaid htlc_minimum_msat with fees.
2538 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2539 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2540 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2542 // Since a path allows to transfer as much value as
2543 // the smallest channel it has ("bottleneck"), we should recompute
2544 // the fees so sender HTLC don't overpay fees when traversing
2545 // larger channels than the bottleneck. This may happen because
2546 // when we were selecting those channels we were not aware how much value
2547 // this path will transfer, and the relative fee for them
2548 // might have been computed considering a larger value.
2549 // Remember that we used these channels so that we don't rely
2550 // on the same liquidity in future paths.
2551 let mut prevented_redundant_path_selection = false;
2552 for (hop, _) in payment_path.hops.iter() {
2553 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2554 let used_liquidity_msat = used_liquidities
2555 .entry(hop.candidate.id())
2556 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2557 .or_insert(spent_on_hop_msat);
2558 let hop_capacity = hop.candidate.effective_capacity();
2559 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2560 if *used_liquidity_msat == hop_max_msat {
2561 // If this path used all of this channel's available liquidity, we know
2562 // this path will not be selected again in the next loop iteration.
2563 prevented_redundant_path_selection = true;
2565 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2567 if !prevented_redundant_path_selection {
2568 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2569 // we'll probably end up picking the same path again on the next iteration.
2570 // Decrease the available liquidity of a hop in the middle of the path.
2571 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2572 let exhausted = u64::max_value();
2574 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2575 LoggedCandidateHop(victim_candidate));
2576 if let Some(scid) = victim_candidate.short_channel_id() {
2577 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2578 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2582 // Track the total amount all our collected paths allow to send so that we know
2583 // when to stop looking for more paths
2584 already_collected_value_msat += value_contribution_msat;
2586 payment_paths.push(payment_path);
2587 found_new_path = true;
2588 break 'path_construction;
2591 // If we found a path back to the payee, we shouldn't try to process it again. This is
2592 // the equivalent of the `elem.was_processed` check in
2593 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2594 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2596 // Otherwise, since the current target node is not us,
2597 // keep "unrolling" the payment graph from payee to payer by
2598 // finding a way to reach the current target from the payer side.
2599 match network_nodes.get(&node_id) {
2602 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2603 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2604 total_cltv_delta, path_length_to_node);
2610 if !found_new_path && channel_saturation_pow_half != 0 {
2611 channel_saturation_pow_half = 0;
2612 continue 'paths_collection;
2614 // If we don't support MPP, no use trying to gather more value ever.
2615 break 'paths_collection;
2619 // Stop either when the recommended value is reached or if no new path was found in this
2621 // In the latter case, making another path finding attempt won't help,
2622 // because we deterministically terminated the search due to low liquidity.
2623 if !found_new_path && channel_saturation_pow_half != 0 {
2624 channel_saturation_pow_half = 0;
2625 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2626 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2627 path_value_msat = recommended_value_msat;
2628 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2629 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2630 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2631 break 'paths_collection;
2632 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2633 // Further, if this was our first walk of the graph, and we weren't limited by an
2634 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2635 // limited by an htlc_minimum_msat value, find another path with a higher value,
2636 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2637 // still keeping a lower total fee than this path.
2638 if !hit_minimum_limit {
2639 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2640 break 'paths_collection;
2642 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher value to meet htlc_minimum_msat limit.");
2643 path_value_msat = recommended_value_msat;
2647 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2648 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2649 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2650 num_ignored_total_fee_limit;
2651 if num_ignored_total > 0 {
2653 "Ignored {} candidate hops due to insufficient value contribution, {} due to path length limit, {} due to CLTV delta limit, {} due to previous payment failure, {} due to htlc_minimum_msat limit, {} to avoid overpaying, {} due to maximum total fee limit. Total: {} ignored candidates.",
2654 num_ignored_value_contribution, num_ignored_path_length_limit,
2655 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2656 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2657 num_ignored_total_fee_limit, num_ignored_total);
2661 if payment_paths.len() == 0 {
2662 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2665 if already_collected_value_msat < final_value_msat {
2666 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2670 let mut selected_route = payment_paths;
2672 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2673 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2675 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2676 // the value they contribute towards the payment amount.
2677 // We sort in descending order as we will remove from the front in `retain`, next.
2678 selected_route.sort_unstable_by(|a, b|
2679 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2680 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2683 // We should make sure that at least 1 path left.
2684 let mut paths_left = selected_route.len();
2685 selected_route.retain(|path| {
2686 if paths_left == 1 {
2689 let path_value_msat = path.get_value_msat();
2690 if path_value_msat <= overpaid_value_msat {
2691 overpaid_value_msat -= path_value_msat;
2697 debug_assert!(selected_route.len() > 0);
2699 if overpaid_value_msat != 0 {
2701 // Now, subtract the remaining overpaid value from the most-expensive path.
2702 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2703 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2704 selected_route.sort_unstable_by(|a, b| {
2705 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2706 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2707 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2709 let expensive_payment_path = selected_route.first_mut().unwrap();
2711 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2712 // can't go negative.
2713 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2714 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2718 // Sort by the path itself and combine redundant paths.
2719 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2720 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2722 selected_route.sort_unstable_by_key(|path| {
2723 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2724 debug_assert!(path.hops.len() <= key.len());
2725 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2730 for idx in 0..(selected_route.len() - 1) {
2731 if idx + 1 >= selected_route.len() { break; }
2732 if iter_equal(selected_route[idx].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2733 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2734 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2735 selected_route[idx].update_value_and_recompute_fees(new_value);
2736 selected_route.remove(idx + 1);
2740 let mut paths = Vec::new();
2741 for payment_path in selected_route {
2742 let mut hops = Vec::with_capacity(payment_path.hops.len());
2743 for (hop, node_features) in payment_path.hops.iter()
2744 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2746 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2747 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2748 // If we sourced the hop from the graph we're sure the target node is announced.
2750 } else if let CandidateRouteHop::FirstHop { details, .. } = hop.candidate {
2751 // If this is a first hop we also know if it's announced.
2754 // If we sourced it any other way, we double-check the network graph to see if
2755 // there are announced channels between the endpoints. If so, the hop might be
2756 // referring to any of the announced channels, as its `short_channel_id` might be
2757 // an alias, in which case we don't take any chances here.
2758 network_graph.node(&target).map_or(false, |hop_node|
2759 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2760 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
2764 hops.push(RouteHop {
2765 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2766 node_features: node_features.clone(),
2767 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2768 channel_features: hop.candidate.features(),
2769 fee_msat: hop.fee_msat,
2770 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2771 maybe_announced_channel,
2774 let mut final_cltv_delta = final_cltv_expiry_delta;
2775 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2776 if let Some(blinded_path) = h.candidate.blinded_path() {
2777 final_cltv_delta = h.candidate.cltv_expiry_delta();
2779 hops: blinded_path.blinded_hops.clone(),
2780 blinding_point: blinded_path.blinding_point,
2781 excess_final_cltv_expiry_delta: 0,
2782 final_value_msat: h.fee_msat,
2786 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2787 // applicable for the previous hop.
2788 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2789 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2792 paths.push(Path { hops, blinded_tail });
2794 // Make sure we would never create a route with more paths than we allow.
2795 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2797 if let Some(node_features) = payment_params.payee.node_features() {
2798 for path in paths.iter_mut() {
2799 path.hops.last_mut().unwrap().node_features = node_features.clone();
2803 let route = Route { paths, route_params: Some(route_params.clone()) };
2805 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2806 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2807 if route.get_total_fees() > max_total_routing_fee_msat {
2808 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2809 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2813 log_info!(logger, "Got route: {}", log_route!(route));
2817 // When an adversarial intermediary node observes a payment, it may be able to infer its
2818 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2819 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2820 // payment path by adding a randomized 'shadow route' offset to the final hop.
2821 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2822 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2824 let network_channels = network_graph.channels();
2825 let network_nodes = network_graph.nodes();
2827 for path in route.paths.iter_mut() {
2828 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2830 // Remember the last three nodes of the random walk and avoid looping back on them.
2831 // Init with the last three nodes from the actual path, if possible.
2832 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2833 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2834 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2836 // Choose the last publicly known node as the starting point for the random walk.
2837 let mut cur_hop: Option<NodeId> = None;
2838 let mut path_nonce = [0u8; 12];
2839 if let Some(starting_hop) = path.hops.iter().rev()
2840 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2841 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2842 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2845 // Init PRNG with the path-dependant nonce, which is static for private paths.
2846 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2847 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2849 // Pick a random path length in [1 .. 3]
2850 prng.process_in_place(&mut random_path_bytes);
2851 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2853 for random_hop in 0..random_walk_length {
2854 // If we don't find a suitable offset in the public network graph, we default to
2855 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2856 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2858 if let Some(cur_node_id) = cur_hop {
2859 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2860 // Randomly choose the next unvisited hop.
2861 prng.process_in_place(&mut random_path_bytes);
2862 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2863 .checked_rem(cur_node.channels.len())
2864 .and_then(|index| cur_node.channels.get(index))
2865 .and_then(|id| network_channels.get(id)) {
2866 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2867 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2868 nodes_to_avoid[random_hop] = *next_id;
2869 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2870 cur_hop = Some(*next_id);
2877 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2878 .checked_add(random_hop_offset)
2879 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2882 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2883 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2884 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2886 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2887 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2888 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2889 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2890 max_path_offset = cmp::max(
2891 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2892 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2893 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2895 // Add 'shadow' CLTV offset to the final hop
2896 if let Some(tail) = path.blinded_tail.as_mut() {
2897 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2898 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2900 if let Some(last_hop) = path.hops.last_mut() {
2901 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2902 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2907 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2908 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2910 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2911 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2912 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2913 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2914 ) -> Result<Route, LightningError>
2915 where L::Target: Logger, GL::Target: Logger {
2916 let graph_lock = network_graph.read_only();
2917 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2918 &graph_lock, logger, random_seed_bytes)?;
2919 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2923 fn build_route_from_hops_internal<L: Deref>(
2924 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2925 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2926 ) -> Result<Route, LightningError> where L::Target: Logger {
2929 our_node_id: NodeId,
2930 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2933 impl ScoreLookUp for HopScorer {
2934 type ScoreParams = ();
2935 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
2936 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2938 let mut cur_id = self.our_node_id;
2939 for i in 0..self.hop_ids.len() {
2940 if let Some(next_id) = self.hop_ids[i] {
2941 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
2953 impl<'a> Writeable for HopScorer {
2955 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2960 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2961 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2964 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2965 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2966 for i in 0..hops.len() {
2967 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2970 let scorer = HopScorer { our_node_id, hop_ids };
2972 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2977 use crate::blinded_path::{BlindedHop, BlindedPath};
2978 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2979 use crate::routing::utxo::UtxoResult;
2980 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2981 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2982 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop};
2983 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2984 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2985 use crate::chain::transaction::OutPoint;
2986 use crate::sign::EntropySource;
2987 use crate::ln::ChannelId;
2988 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2989 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2990 use crate::ln::channelmanager;
2991 use crate::offers::invoice::BlindedPayInfo;
2992 use crate::util::config::UserConfig;
2993 use crate::util::test_utils as ln_test_utils;
2994 use crate::util::chacha20::ChaCha20;
2995 use crate::util::ser::{Readable, Writeable};
2997 use crate::util::ser::Writer;
2999 use bitcoin::hashes::Hash;
3000 use bitcoin::network::constants::Network;
3001 use bitcoin::blockdata::constants::ChainHash;
3002 use bitcoin::blockdata::script::Builder;
3003 use bitcoin::blockdata::opcodes;
3004 use bitcoin::blockdata::transaction::TxOut;
3005 use bitcoin::hashes::hex::FromHex;
3006 use bitcoin::secp256k1::{PublicKey,SecretKey};
3007 use bitcoin::secp256k1::Secp256k1;
3009 use crate::io::Cursor;
3010 use crate::prelude::*;
3011 use crate::sync::Arc;
3013 use core::convert::TryInto;
3015 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3016 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3017 channelmanager::ChannelDetails {
3018 channel_id: ChannelId::new_zero(),
3019 counterparty: channelmanager::ChannelCounterparty {
3022 unspendable_punishment_reserve: 0,
3023 forwarding_info: None,
3024 outbound_htlc_minimum_msat: None,
3025 outbound_htlc_maximum_msat: None,
3027 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3030 outbound_scid_alias: None,
3031 inbound_scid_alias: None,
3032 channel_value_satoshis: 0,
3035 outbound_capacity_msat,
3036 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3037 next_outbound_htlc_minimum_msat: 0,
3038 inbound_capacity_msat: 42,
3039 unspendable_punishment_reserve: None,
3040 confirmations_required: None,
3041 confirmations: None,
3042 force_close_spend_delay: None,
3043 is_outbound: true, is_channel_ready: true,
3044 is_usable: true, is_public: true,
3045 inbound_htlc_minimum_msat: None,
3046 inbound_htlc_maximum_msat: None,
3048 feerate_sat_per_1000_weight: None,
3049 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3054 fn simple_route_test() {
3055 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3056 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3057 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3058 let scorer = ln_test_utils::TestScorer::new();
3059 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3060 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3062 // Simple route to 2 via 1
3064 let route_params = RouteParameters::from_payment_params_and_value(
3065 payment_params.clone(), 0);
3066 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3067 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3068 &Default::default(), &random_seed_bytes) {
3069 assert_eq!(err, "Cannot send a payment of 0 msat");
3070 } else { panic!(); }
3072 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3073 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3074 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3075 assert_eq!(route.paths[0].hops.len(), 2);
3077 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3078 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3079 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3080 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3081 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3082 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3084 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3085 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3086 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3087 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3088 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3089 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3093 fn invalid_first_hop_test() {
3094 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3095 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3096 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3097 let scorer = ln_test_utils::TestScorer::new();
3098 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3099 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3101 // Simple route to 2 via 1
3103 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3105 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3106 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3107 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3108 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3109 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3110 } else { panic!(); }
3112 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3113 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3114 assert_eq!(route.paths[0].hops.len(), 2);
3118 fn htlc_minimum_test() {
3119 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3120 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3121 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3122 let scorer = ln_test_utils::TestScorer::new();
3123 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3124 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3126 // Simple route to 2 via 1
3128 // Disable other paths
3129 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3130 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3131 short_channel_id: 12,
3133 flags: 2, // to disable
3134 cltv_expiry_delta: 0,
3135 htlc_minimum_msat: 0,
3136 htlc_maximum_msat: MAX_VALUE_MSAT,
3138 fee_proportional_millionths: 0,
3139 excess_data: Vec::new()
3141 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3142 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3143 short_channel_id: 3,
3145 flags: 2, // to disable
3146 cltv_expiry_delta: 0,
3147 htlc_minimum_msat: 0,
3148 htlc_maximum_msat: MAX_VALUE_MSAT,
3150 fee_proportional_millionths: 0,
3151 excess_data: Vec::new()
3153 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3154 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3155 short_channel_id: 13,
3157 flags: 2, // to disable
3158 cltv_expiry_delta: 0,
3159 htlc_minimum_msat: 0,
3160 htlc_maximum_msat: MAX_VALUE_MSAT,
3162 fee_proportional_millionths: 0,
3163 excess_data: Vec::new()
3165 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3166 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3167 short_channel_id: 6,
3169 flags: 2, // to disable
3170 cltv_expiry_delta: 0,
3171 htlc_minimum_msat: 0,
3172 htlc_maximum_msat: MAX_VALUE_MSAT,
3174 fee_proportional_millionths: 0,
3175 excess_data: Vec::new()
3177 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3178 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3179 short_channel_id: 7,
3181 flags: 2, // to disable
3182 cltv_expiry_delta: 0,
3183 htlc_minimum_msat: 0,
3184 htlc_maximum_msat: MAX_VALUE_MSAT,
3186 fee_proportional_millionths: 0,
3187 excess_data: Vec::new()
3190 // Check against amount_to_transfer_over_msat.
3191 // Set minimal HTLC of 200_000_000 msat.
3192 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3193 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3194 short_channel_id: 2,
3197 cltv_expiry_delta: 0,
3198 htlc_minimum_msat: 200_000_000,
3199 htlc_maximum_msat: MAX_VALUE_MSAT,
3201 fee_proportional_millionths: 0,
3202 excess_data: Vec::new()
3205 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3207 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3208 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3209 short_channel_id: 4,
3212 cltv_expiry_delta: 0,
3213 htlc_minimum_msat: 0,
3214 htlc_maximum_msat: 199_999_999,
3216 fee_proportional_millionths: 0,
3217 excess_data: Vec::new()
3220 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3221 let route_params = RouteParameters::from_payment_params_and_value(
3222 payment_params, 199_999_999);
3223 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3224 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3225 &Default::default(), &random_seed_bytes) {
3226 assert_eq!(err, "Failed to find a path to the given destination");
3227 } else { panic!(); }
3229 // Lift the restriction on the first hop.
3230 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3231 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3232 short_channel_id: 2,
3235 cltv_expiry_delta: 0,
3236 htlc_minimum_msat: 0,
3237 htlc_maximum_msat: MAX_VALUE_MSAT,
3239 fee_proportional_millionths: 0,
3240 excess_data: Vec::new()
3243 // A payment above the minimum should pass
3244 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3245 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3246 assert_eq!(route.paths[0].hops.len(), 2);
3250 fn htlc_minimum_overpay_test() {
3251 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3252 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3253 let config = UserConfig::default();
3254 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3255 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3257 let scorer = ln_test_utils::TestScorer::new();
3258 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3259 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3261 // A route to node#2 via two paths.
3262 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3263 // Thus, they can't send 60 without overpaying.
3264 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3265 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3266 short_channel_id: 2,
3269 cltv_expiry_delta: 0,
3270 htlc_minimum_msat: 35_000,
3271 htlc_maximum_msat: 40_000,
3273 fee_proportional_millionths: 0,
3274 excess_data: Vec::new()
3276 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3277 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3278 short_channel_id: 12,
3281 cltv_expiry_delta: 0,
3282 htlc_minimum_msat: 35_000,
3283 htlc_maximum_msat: 40_000,
3285 fee_proportional_millionths: 0,
3286 excess_data: Vec::new()
3290 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3291 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3292 short_channel_id: 13,
3295 cltv_expiry_delta: 0,
3296 htlc_minimum_msat: 0,
3297 htlc_maximum_msat: MAX_VALUE_MSAT,
3299 fee_proportional_millionths: 0,
3300 excess_data: Vec::new()
3302 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3303 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3304 short_channel_id: 4,
3307 cltv_expiry_delta: 0,
3308 htlc_minimum_msat: 0,
3309 htlc_maximum_msat: MAX_VALUE_MSAT,
3311 fee_proportional_millionths: 0,
3312 excess_data: Vec::new()
3315 // Disable other paths
3316 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3317 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3318 short_channel_id: 1,
3320 flags: 2, // to disable
3321 cltv_expiry_delta: 0,
3322 htlc_minimum_msat: 0,
3323 htlc_maximum_msat: MAX_VALUE_MSAT,
3325 fee_proportional_millionths: 0,
3326 excess_data: Vec::new()
3329 let mut route_params = RouteParameters::from_payment_params_and_value(
3330 payment_params.clone(), 60_000);
3331 route_params.max_total_routing_fee_msat = Some(15_000);
3332 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3333 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3334 // Overpay fees to hit htlc_minimum_msat.
3335 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3336 // TODO: this could be better balanced to overpay 10k and not 15k.
3337 assert_eq!(overpaid_fees, 15_000);
3339 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3340 // while taking even more fee to match htlc_minimum_msat.
3341 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3342 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3343 short_channel_id: 12,
3346 cltv_expiry_delta: 0,
3347 htlc_minimum_msat: 65_000,
3348 htlc_maximum_msat: 80_000,
3350 fee_proportional_millionths: 0,
3351 excess_data: Vec::new()
3353 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3354 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3355 short_channel_id: 2,
3358 cltv_expiry_delta: 0,
3359 htlc_minimum_msat: 0,
3360 htlc_maximum_msat: MAX_VALUE_MSAT,
3362 fee_proportional_millionths: 0,
3363 excess_data: Vec::new()
3365 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3366 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3367 short_channel_id: 4,
3370 cltv_expiry_delta: 0,
3371 htlc_minimum_msat: 0,
3372 htlc_maximum_msat: MAX_VALUE_MSAT,
3374 fee_proportional_millionths: 100_000,
3375 excess_data: Vec::new()
3378 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3379 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3380 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3381 assert_eq!(route.paths.len(), 1);
3382 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3383 let fees = route.paths[0].hops[0].fee_msat;
3384 assert_eq!(fees, 5_000);
3386 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3387 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3388 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3389 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3390 // the other channel.
3391 assert_eq!(route.paths.len(), 1);
3392 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3393 let fees = route.paths[0].hops[0].fee_msat;
3394 assert_eq!(fees, 5_000);
3398 fn htlc_minimum_recipient_overpay_test() {
3399 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3400 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3401 let config = UserConfig::default();
3402 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3403 let scorer = ln_test_utils::TestScorer::new();
3404 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3405 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3407 // Route to node2 over a single path which requires overpaying the recipient themselves.
3409 // First disable all paths except the us -> node1 -> node2 path
3410 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3411 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3412 short_channel_id: 13,
3415 cltv_expiry_delta: 0,
3416 htlc_minimum_msat: 0,
3417 htlc_maximum_msat: 0,
3419 fee_proportional_millionths: 0,
3420 excess_data: Vec::new()
3423 // Set channel 4 to free but with a high htlc_minimum_msat
3424 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3425 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3426 short_channel_id: 4,
3429 cltv_expiry_delta: 0,
3430 htlc_minimum_msat: 15_000,
3431 htlc_maximum_msat: MAX_VALUE_MSAT,
3433 fee_proportional_millionths: 0,
3434 excess_data: Vec::new()
3437 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3438 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3439 // what we try to find a route for, so this test only just happens to work out to exactly
3441 let mut route_params = RouteParameters::from_payment_params_and_value(
3442 payment_params.clone(), 5_000);
3443 route_params.max_total_routing_fee_msat = Some(9_999);
3444 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3445 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3446 &Default::default(), &random_seed_bytes) {
3447 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3448 } else { panic!(); }
3450 let mut route_params = RouteParameters::from_payment_params_and_value(
3451 payment_params.clone(), 5_000);
3452 route_params.max_total_routing_fee_msat = Some(10_000);
3453 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3454 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3455 assert_eq!(route.get_total_fees(), 10_000);
3459 fn disable_channels_test() {
3460 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3461 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3462 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3463 let scorer = ln_test_utils::TestScorer::new();
3464 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3465 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3467 // // Disable channels 4 and 12 by flags=2
3468 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3469 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3470 short_channel_id: 4,
3472 flags: 2, // to disable
3473 cltv_expiry_delta: 0,
3474 htlc_minimum_msat: 0,
3475 htlc_maximum_msat: MAX_VALUE_MSAT,
3477 fee_proportional_millionths: 0,
3478 excess_data: Vec::new()
3480 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3481 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3482 short_channel_id: 12,
3484 flags: 2, // to disable
3485 cltv_expiry_delta: 0,
3486 htlc_minimum_msat: 0,
3487 htlc_maximum_msat: MAX_VALUE_MSAT,
3489 fee_proportional_millionths: 0,
3490 excess_data: Vec::new()
3493 // If all the channels require some features we don't understand, route should fail
3494 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3495 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3496 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3497 &Default::default(), &random_seed_bytes) {
3498 assert_eq!(err, "Failed to find a path to the given destination");
3499 } else { panic!(); }
3501 // If we specify a channel to node7, that overrides our local channel view and that gets used
3502 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3503 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3504 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3505 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3506 &Default::default(), &random_seed_bytes).unwrap();
3507 assert_eq!(route.paths[0].hops.len(), 2);
3509 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3510 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3511 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3512 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3513 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3514 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3516 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3517 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3518 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3519 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3520 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3521 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3525 fn disable_node_test() {
3526 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3527 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3528 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3529 let scorer = ln_test_utils::TestScorer::new();
3530 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3531 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3533 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3534 let mut unknown_features = NodeFeatures::empty();
3535 unknown_features.set_unknown_feature_required();
3536 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3537 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3538 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3540 // If all nodes require some features we don't understand, route should fail
3541 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3542 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3543 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3544 &Default::default(), &random_seed_bytes) {
3545 assert_eq!(err, "Failed to find a path to the given destination");
3546 } else { panic!(); }
3548 // If we specify a channel to node7, that overrides our local channel view and that gets used
3549 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3550 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3551 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3552 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3553 &Default::default(), &random_seed_bytes).unwrap();
3554 assert_eq!(route.paths[0].hops.len(), 2);
3556 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3557 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3558 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3559 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3560 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3561 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3563 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3564 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3565 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3566 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3567 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3568 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3570 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3571 // naively) assume that the user checked the feature bits on the invoice, which override
3572 // the node_announcement.
3576 fn our_chans_test() {
3577 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3578 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3579 let scorer = ln_test_utils::TestScorer::new();
3580 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3581 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3583 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3584 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3585 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3586 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3587 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3588 assert_eq!(route.paths[0].hops.len(), 3);
3590 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3591 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3592 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3593 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3594 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3595 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3597 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3598 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3599 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3600 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3601 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3602 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3604 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3605 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3606 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3607 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3608 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3609 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3611 // If we specify a channel to node7, that overrides our local channel view and that gets used
3612 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3613 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3614 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3615 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3616 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3617 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3618 &Default::default(), &random_seed_bytes).unwrap();
3619 assert_eq!(route.paths[0].hops.len(), 2);
3621 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3622 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3623 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3624 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3625 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3626 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3628 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3629 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3630 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3631 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3632 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3633 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3636 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3637 let zero_fees = RoutingFees {
3639 proportional_millionths: 0,
3641 vec![RouteHint(vec![RouteHintHop {
3642 src_node_id: nodes[3],
3643 short_channel_id: 8,
3645 cltv_expiry_delta: (8 << 4) | 1,
3646 htlc_minimum_msat: None,
3647 htlc_maximum_msat: None,
3649 ]), RouteHint(vec![RouteHintHop {
3650 src_node_id: nodes[4],
3651 short_channel_id: 9,
3654 proportional_millionths: 0,
3656 cltv_expiry_delta: (9 << 4) | 1,
3657 htlc_minimum_msat: None,
3658 htlc_maximum_msat: None,
3659 }]), RouteHint(vec![RouteHintHop {
3660 src_node_id: nodes[5],
3661 short_channel_id: 10,
3663 cltv_expiry_delta: (10 << 4) | 1,
3664 htlc_minimum_msat: None,
3665 htlc_maximum_msat: None,
3669 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3670 let zero_fees = RoutingFees {
3672 proportional_millionths: 0,
3674 vec![RouteHint(vec![RouteHintHop {
3675 src_node_id: nodes[2],
3676 short_channel_id: 5,
3679 proportional_millionths: 0,
3681 cltv_expiry_delta: (5 << 4) | 1,
3682 htlc_minimum_msat: None,
3683 htlc_maximum_msat: None,
3685 src_node_id: nodes[3],
3686 short_channel_id: 8,
3688 cltv_expiry_delta: (8 << 4) | 1,
3689 htlc_minimum_msat: None,
3690 htlc_maximum_msat: None,
3692 ]), RouteHint(vec![RouteHintHop {
3693 src_node_id: nodes[4],
3694 short_channel_id: 9,
3697 proportional_millionths: 0,
3699 cltv_expiry_delta: (9 << 4) | 1,
3700 htlc_minimum_msat: None,
3701 htlc_maximum_msat: None,
3702 }]), RouteHint(vec![RouteHintHop {
3703 src_node_id: nodes[5],
3704 short_channel_id: 10,
3706 cltv_expiry_delta: (10 << 4) | 1,
3707 htlc_minimum_msat: None,
3708 htlc_maximum_msat: None,
3713 fn partial_route_hint_test() {
3714 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3715 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3716 let scorer = ln_test_utils::TestScorer::new();
3717 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3718 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3720 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3721 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3722 // RouteHint may be partially used by the algo to build the best path.
3724 // First check that last hop can't have its source as the payee.
3725 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3726 src_node_id: nodes[6],
3727 short_channel_id: 8,
3730 proportional_millionths: 0,
3732 cltv_expiry_delta: (8 << 4) | 1,
3733 htlc_minimum_msat: None,
3734 htlc_maximum_msat: None,
3737 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3738 invalid_last_hops.push(invalid_last_hop);
3740 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3741 .with_route_hints(invalid_last_hops).unwrap();
3742 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3743 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3744 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3745 &Default::default(), &random_seed_bytes) {
3746 assert_eq!(err, "Route hint cannot have the payee as the source.");
3747 } else { panic!(); }
3750 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3751 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3752 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3753 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3754 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3755 assert_eq!(route.paths[0].hops.len(), 5);
3757 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3758 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3759 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3760 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3761 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3762 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3764 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3765 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3766 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3767 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3768 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3769 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3771 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3772 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3773 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3774 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3775 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3776 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3778 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3779 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3780 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3781 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3782 // If we have a peer in the node map, we'll use their features here since we don't have
3783 // a way of figuring out their features from the invoice:
3784 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3785 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3787 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3788 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3789 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3790 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3791 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3792 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3795 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3796 let zero_fees = RoutingFees {
3798 proportional_millionths: 0,
3800 vec![RouteHint(vec![RouteHintHop {
3801 src_node_id: nodes[3],
3802 short_channel_id: 8,
3804 cltv_expiry_delta: (8 << 4) | 1,
3805 htlc_minimum_msat: None,
3806 htlc_maximum_msat: None,
3807 }]), RouteHint(vec![
3809 ]), RouteHint(vec![RouteHintHop {
3810 src_node_id: nodes[5],
3811 short_channel_id: 10,
3813 cltv_expiry_delta: (10 << 4) | 1,
3814 htlc_minimum_msat: None,
3815 htlc_maximum_msat: None,
3820 fn ignores_empty_last_hops_test() {
3821 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3822 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3823 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3824 let scorer = ln_test_utils::TestScorer::new();
3825 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3826 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3828 // Test handling of an empty RouteHint passed in Invoice.
3829 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3830 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3831 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3832 assert_eq!(route.paths[0].hops.len(), 5);
3834 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3835 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3836 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3837 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3838 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3839 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3841 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3842 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3843 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3844 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3845 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3846 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3848 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3849 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3850 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3851 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3852 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3853 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3855 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3856 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3857 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3858 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3859 // If we have a peer in the node map, we'll use their features here since we don't have
3860 // a way of figuring out their features from the invoice:
3861 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3862 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3864 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3865 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3866 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3867 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3868 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3869 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3872 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3874 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3875 let zero_fees = RoutingFees {
3877 proportional_millionths: 0,
3879 vec![RouteHint(vec![RouteHintHop {
3880 src_node_id: hint_hops[0],
3881 short_channel_id: 0xff00,
3884 proportional_millionths: 0,
3886 cltv_expiry_delta: (5 << 4) | 1,
3887 htlc_minimum_msat: None,
3888 htlc_maximum_msat: None,
3890 src_node_id: hint_hops[1],
3891 short_channel_id: 0xff01,
3893 cltv_expiry_delta: (8 << 4) | 1,
3894 htlc_minimum_msat: None,
3895 htlc_maximum_msat: None,
3900 fn multi_hint_last_hops_test() {
3901 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3902 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3903 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3904 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3905 let scorer = ln_test_utils::TestScorer::new();
3906 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3907 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3908 // Test through channels 2, 3, 0xff00, 0xff01.
3909 // Test shows that multiple hop hints are considered.
3911 // Disabling channels 6 & 7 by flags=2
3912 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3913 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3914 short_channel_id: 6,
3916 flags: 2, // to disable
3917 cltv_expiry_delta: 0,
3918 htlc_minimum_msat: 0,
3919 htlc_maximum_msat: MAX_VALUE_MSAT,
3921 fee_proportional_millionths: 0,
3922 excess_data: Vec::new()
3924 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3925 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3926 short_channel_id: 7,
3928 flags: 2, // to disable
3929 cltv_expiry_delta: 0,
3930 htlc_minimum_msat: 0,
3931 htlc_maximum_msat: MAX_VALUE_MSAT,
3933 fee_proportional_millionths: 0,
3934 excess_data: Vec::new()
3937 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3938 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3939 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3940 assert_eq!(route.paths[0].hops.len(), 4);
3942 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3943 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3944 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3945 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3946 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3947 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3949 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3950 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3951 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3952 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3953 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3954 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3956 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3957 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3958 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3959 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3960 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3961 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3963 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3964 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3965 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3966 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3967 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3968 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3972 fn private_multi_hint_last_hops_test() {
3973 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3974 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3976 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3977 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3979 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3980 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3981 let scorer = ln_test_utils::TestScorer::new();
3982 // Test through channels 2, 3, 0xff00, 0xff01.
3983 // Test shows that multiple hop hints are considered.
3985 // Disabling channels 6 & 7 by flags=2
3986 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3987 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3988 short_channel_id: 6,
3990 flags: 2, // to disable
3991 cltv_expiry_delta: 0,
3992 htlc_minimum_msat: 0,
3993 htlc_maximum_msat: MAX_VALUE_MSAT,
3995 fee_proportional_millionths: 0,
3996 excess_data: Vec::new()
3998 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3999 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4000 short_channel_id: 7,
4002 flags: 2, // to disable
4003 cltv_expiry_delta: 0,
4004 htlc_minimum_msat: 0,
4005 htlc_maximum_msat: MAX_VALUE_MSAT,
4007 fee_proportional_millionths: 0,
4008 excess_data: Vec::new()
4011 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4012 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4013 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4014 assert_eq!(route.paths[0].hops.len(), 4);
4016 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4017 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4018 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4019 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4020 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4021 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4023 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4024 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4025 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4026 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4027 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4028 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4030 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4031 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4032 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4033 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4034 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4035 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4037 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4038 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4039 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4040 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4041 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4042 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4045 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4046 let zero_fees = RoutingFees {
4048 proportional_millionths: 0,
4050 vec![RouteHint(vec![RouteHintHop {
4051 src_node_id: nodes[4],
4052 short_channel_id: 11,
4054 cltv_expiry_delta: (11 << 4) | 1,
4055 htlc_minimum_msat: None,
4056 htlc_maximum_msat: None,
4058 src_node_id: nodes[3],
4059 short_channel_id: 8,
4061 cltv_expiry_delta: (8 << 4) | 1,
4062 htlc_minimum_msat: None,
4063 htlc_maximum_msat: None,
4064 }]), RouteHint(vec![RouteHintHop {
4065 src_node_id: nodes[4],
4066 short_channel_id: 9,
4069 proportional_millionths: 0,
4071 cltv_expiry_delta: (9 << 4) | 1,
4072 htlc_minimum_msat: None,
4073 htlc_maximum_msat: None,
4074 }]), RouteHint(vec![RouteHintHop {
4075 src_node_id: nodes[5],
4076 short_channel_id: 10,
4078 cltv_expiry_delta: (10 << 4) | 1,
4079 htlc_minimum_msat: None,
4080 htlc_maximum_msat: None,
4085 fn last_hops_with_public_channel_test() {
4086 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4087 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4088 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4089 let scorer = ln_test_utils::TestScorer::new();
4090 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4091 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4092 // This test shows that public routes can be present in the invoice
4093 // which would be handled in the same manner.
4095 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4096 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4097 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4098 assert_eq!(route.paths[0].hops.len(), 5);
4100 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4101 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4102 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4103 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4104 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4105 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4107 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4108 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4109 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4110 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4111 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4112 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4114 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4115 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4116 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4117 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4118 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4119 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4121 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4122 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4123 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4124 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4125 // If we have a peer in the node map, we'll use their features here since we don't have
4126 // a way of figuring out their features from the invoice:
4127 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4128 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4130 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4131 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4132 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4133 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4134 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4135 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4139 fn our_chans_last_hop_connect_test() {
4140 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4141 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4142 let scorer = ln_test_utils::TestScorer::new();
4143 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4144 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4146 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4147 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4148 let mut last_hops = last_hops(&nodes);
4149 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4150 .with_route_hints(last_hops.clone()).unwrap();
4151 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4152 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4153 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4154 &Default::default(), &random_seed_bytes).unwrap();
4155 assert_eq!(route.paths[0].hops.len(), 2);
4157 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4158 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4159 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4160 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4161 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4162 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4164 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4165 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4166 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4167 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4168 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4169 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4171 last_hops[0].0[0].fees.base_msat = 1000;
4173 // Revert to via 6 as the fee on 8 goes up
4174 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4175 .with_route_hints(last_hops).unwrap();
4176 let route_params = RouteParameters::from_payment_params_and_value(
4177 payment_params.clone(), 100);
4178 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4179 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4180 assert_eq!(route.paths[0].hops.len(), 4);
4182 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4183 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4184 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4185 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4186 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4187 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4189 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4190 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4191 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4192 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4193 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4194 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4196 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4197 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4198 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4199 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4200 // If we have a peer in the node map, we'll use their features here since we don't have
4201 // a way of figuring out their features from the invoice:
4202 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4203 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4205 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4206 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4207 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4208 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4209 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4210 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4212 // ...but still use 8 for larger payments as 6 has a variable feerate
4213 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4214 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4215 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4216 assert_eq!(route.paths[0].hops.len(), 5);
4218 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4219 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4220 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4221 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4222 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4223 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4225 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4226 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4227 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4228 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4229 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4230 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4232 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4233 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4234 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4235 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4236 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4237 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4239 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4240 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4241 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4242 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4243 // If we have a peer in the node map, we'll use their features here since we don't have
4244 // a way of figuring out their features from the invoice:
4245 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4246 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4248 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4249 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4250 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4251 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4252 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4253 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4256 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> {
4257 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4258 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4259 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4261 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4262 let last_hops = RouteHint(vec![RouteHintHop {
4263 src_node_id: middle_node_id,
4264 short_channel_id: 8,
4267 proportional_millionths: last_hop_fee_prop,
4269 cltv_expiry_delta: (8 << 4) | 1,
4270 htlc_minimum_msat: None,
4271 htlc_maximum_msat: last_hop_htlc_max,
4273 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4274 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4275 let scorer = ln_test_utils::TestScorer::new();
4276 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4277 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4278 let logger = ln_test_utils::TestLogger::new();
4279 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4280 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4281 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4282 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4283 &random_seed_bytes);
4288 fn unannounced_path_test() {
4289 // We should be able to send a payment to a destination without any help of a routing graph
4290 // if we have a channel with a common counterparty that appears in the first and last hop
4292 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4294 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4295 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4296 assert_eq!(route.paths[0].hops.len(), 2);
4298 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4299 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4300 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4301 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4302 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4303 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4305 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4306 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4307 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4308 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4309 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4310 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4314 fn overflow_unannounced_path_test_liquidity_underflow() {
4315 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4316 // the last-hop had a fee which overflowed a u64, we'd panic.
4317 // This was due to us adding the first-hop from us unconditionally, causing us to think
4318 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4319 // In this test, we previously hit a subtraction underflow due to having less available
4320 // liquidity at the last hop than 0.
4321 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());
4325 fn overflow_unannounced_path_test_feerate_overflow() {
4326 // This tests for the same case as above, except instead of hitting a subtraction
4327 // underflow, we hit a case where the fee charged at a hop overflowed.
4328 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());
4332 fn available_amount_while_routing_test() {
4333 // Tests whether we choose the correct available channel amount while routing.
4335 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4336 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4337 let scorer = ln_test_utils::TestScorer::new();
4338 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4339 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4340 let config = UserConfig::default();
4341 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4342 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4345 // We will use a simple single-path route from
4346 // our node to node2 via node0: channels {1, 3}.
4348 // First disable all other paths.
4349 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4350 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4351 short_channel_id: 2,
4354 cltv_expiry_delta: 0,
4355 htlc_minimum_msat: 0,
4356 htlc_maximum_msat: 100_000,
4358 fee_proportional_millionths: 0,
4359 excess_data: Vec::new()
4361 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4362 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4363 short_channel_id: 12,
4366 cltv_expiry_delta: 0,
4367 htlc_minimum_msat: 0,
4368 htlc_maximum_msat: 100_000,
4370 fee_proportional_millionths: 0,
4371 excess_data: Vec::new()
4374 // Make the first channel (#1) very permissive,
4375 // and we will be testing all limits on the second channel.
4376 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4377 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4378 short_channel_id: 1,
4381 cltv_expiry_delta: 0,
4382 htlc_minimum_msat: 0,
4383 htlc_maximum_msat: 1_000_000_000,
4385 fee_proportional_millionths: 0,
4386 excess_data: Vec::new()
4389 // First, let's see if routing works if we have absolutely no idea about the available amount.
4390 // In this case, it should be set to 250_000 sats.
4391 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4392 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4393 short_channel_id: 3,
4396 cltv_expiry_delta: 0,
4397 htlc_minimum_msat: 0,
4398 htlc_maximum_msat: 250_000_000,
4400 fee_proportional_millionths: 0,
4401 excess_data: Vec::new()
4405 // Attempt to route more than available results in a failure.
4406 let route_params = RouteParameters::from_payment_params_and_value(
4407 payment_params.clone(), 250_000_001);
4408 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4409 &our_id, &route_params, &network_graph.read_only(), None,
4410 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4411 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4412 } else { panic!(); }
4416 // Now, attempt to route an exact amount we have should be fine.
4417 let route_params = RouteParameters::from_payment_params_and_value(
4418 payment_params.clone(), 250_000_000);
4419 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4420 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4421 assert_eq!(route.paths.len(), 1);
4422 let path = route.paths.last().unwrap();
4423 assert_eq!(path.hops.len(), 2);
4424 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4425 assert_eq!(path.final_value_msat(), 250_000_000);
4428 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4429 // Disable channel #1 and use another first hop.
4430 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4431 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4432 short_channel_id: 1,
4435 cltv_expiry_delta: 0,
4436 htlc_minimum_msat: 0,
4437 htlc_maximum_msat: 1_000_000_000,
4439 fee_proportional_millionths: 0,
4440 excess_data: Vec::new()
4443 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4444 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4447 // Attempt to route more than available results in a failure.
4448 let route_params = RouteParameters::from_payment_params_and_value(
4449 payment_params.clone(), 200_000_001);
4450 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4451 &our_id, &route_params, &network_graph.read_only(),
4452 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4453 &Default::default(), &random_seed_bytes) {
4454 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4455 } else { panic!(); }
4459 // Now, attempt to route an exact amount we have should be fine.
4460 let route_params = RouteParameters::from_payment_params_and_value(
4461 payment_params.clone(), 200_000_000);
4462 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4463 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4464 &Default::default(), &random_seed_bytes).unwrap();
4465 assert_eq!(route.paths.len(), 1);
4466 let path = route.paths.last().unwrap();
4467 assert_eq!(path.hops.len(), 2);
4468 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4469 assert_eq!(path.final_value_msat(), 200_000_000);
4472 // Enable channel #1 back.
4473 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4474 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4475 short_channel_id: 1,
4478 cltv_expiry_delta: 0,
4479 htlc_minimum_msat: 0,
4480 htlc_maximum_msat: 1_000_000_000,
4482 fee_proportional_millionths: 0,
4483 excess_data: Vec::new()
4487 // Now let's see if routing works if we know only htlc_maximum_msat.
4488 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4489 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4490 short_channel_id: 3,
4493 cltv_expiry_delta: 0,
4494 htlc_minimum_msat: 0,
4495 htlc_maximum_msat: 15_000,
4497 fee_proportional_millionths: 0,
4498 excess_data: Vec::new()
4502 // Attempt to route more than available results in a failure.
4503 let route_params = RouteParameters::from_payment_params_and_value(
4504 payment_params.clone(), 15_001);
4505 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4506 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4507 &scorer, &Default::default(), &random_seed_bytes) {
4508 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4509 } else { panic!(); }
4513 // Now, attempt to route an exact amount we have should be fine.
4514 let route_params = RouteParameters::from_payment_params_and_value(
4515 payment_params.clone(), 15_000);
4516 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4517 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4518 assert_eq!(route.paths.len(), 1);
4519 let path = route.paths.last().unwrap();
4520 assert_eq!(path.hops.len(), 2);
4521 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4522 assert_eq!(path.final_value_msat(), 15_000);
4525 // Now let's see if routing works if we know only capacity from the UTXO.
4527 // We can't change UTXO capacity on the fly, so we'll disable
4528 // the existing channel and add another one with the capacity we need.
4529 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4530 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4531 short_channel_id: 3,
4534 cltv_expiry_delta: 0,
4535 htlc_minimum_msat: 0,
4536 htlc_maximum_msat: MAX_VALUE_MSAT,
4538 fee_proportional_millionths: 0,
4539 excess_data: Vec::new()
4542 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4543 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4544 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4545 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4546 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4548 *chain_monitor.utxo_ret.lock().unwrap() =
4549 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4550 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4552 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4553 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4554 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4555 short_channel_id: 333,
4558 cltv_expiry_delta: (3 << 4) | 1,
4559 htlc_minimum_msat: 0,
4560 htlc_maximum_msat: 15_000,
4562 fee_proportional_millionths: 0,
4563 excess_data: Vec::new()
4565 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4566 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4567 short_channel_id: 333,
4570 cltv_expiry_delta: (3 << 4) | 2,
4571 htlc_minimum_msat: 0,
4572 htlc_maximum_msat: 15_000,
4574 fee_proportional_millionths: 0,
4575 excess_data: Vec::new()
4579 // Attempt to route more than available results in a failure.
4580 let route_params = RouteParameters::from_payment_params_and_value(
4581 payment_params.clone(), 15_001);
4582 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4583 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4584 &scorer, &Default::default(), &random_seed_bytes) {
4585 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4586 } else { panic!(); }
4590 // Now, attempt to route an exact amount we have should be fine.
4591 let route_params = RouteParameters::from_payment_params_and_value(
4592 payment_params.clone(), 15_000);
4593 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4594 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4595 assert_eq!(route.paths.len(), 1);
4596 let path = route.paths.last().unwrap();
4597 assert_eq!(path.hops.len(), 2);
4598 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4599 assert_eq!(path.final_value_msat(), 15_000);
4602 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4603 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4604 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4605 short_channel_id: 333,
4608 cltv_expiry_delta: 0,
4609 htlc_minimum_msat: 0,
4610 htlc_maximum_msat: 10_000,
4612 fee_proportional_millionths: 0,
4613 excess_data: Vec::new()
4617 // Attempt to route more than available results in a failure.
4618 let route_params = RouteParameters::from_payment_params_and_value(
4619 payment_params.clone(), 10_001);
4620 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4621 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4622 &scorer, &Default::default(), &random_seed_bytes) {
4623 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4624 } else { panic!(); }
4628 // Now, attempt to route an exact amount we have should be fine.
4629 let route_params = RouteParameters::from_payment_params_and_value(
4630 payment_params.clone(), 10_000);
4631 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4632 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4633 assert_eq!(route.paths.len(), 1);
4634 let path = route.paths.last().unwrap();
4635 assert_eq!(path.hops.len(), 2);
4636 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4637 assert_eq!(path.final_value_msat(), 10_000);
4642 fn available_liquidity_last_hop_test() {
4643 // Check that available liquidity properly limits the path even when only
4644 // one of the latter hops is limited.
4645 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4646 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4647 let scorer = ln_test_utils::TestScorer::new();
4648 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4649 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4650 let config = UserConfig::default();
4651 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4652 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4655 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4656 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4657 // Total capacity: 50 sats.
4659 // Disable other potential paths.
4660 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4661 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4662 short_channel_id: 2,
4665 cltv_expiry_delta: 0,
4666 htlc_minimum_msat: 0,
4667 htlc_maximum_msat: 100_000,
4669 fee_proportional_millionths: 0,
4670 excess_data: Vec::new()
4672 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4673 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4674 short_channel_id: 7,
4677 cltv_expiry_delta: 0,
4678 htlc_minimum_msat: 0,
4679 htlc_maximum_msat: 100_000,
4681 fee_proportional_millionths: 0,
4682 excess_data: Vec::new()
4687 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4688 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4689 short_channel_id: 12,
4692 cltv_expiry_delta: 0,
4693 htlc_minimum_msat: 0,
4694 htlc_maximum_msat: 100_000,
4696 fee_proportional_millionths: 0,
4697 excess_data: Vec::new()
4699 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4700 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4701 short_channel_id: 13,
4704 cltv_expiry_delta: 0,
4705 htlc_minimum_msat: 0,
4706 htlc_maximum_msat: 100_000,
4708 fee_proportional_millionths: 0,
4709 excess_data: Vec::new()
4712 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4713 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4714 short_channel_id: 6,
4717 cltv_expiry_delta: 0,
4718 htlc_minimum_msat: 0,
4719 htlc_maximum_msat: 50_000,
4721 fee_proportional_millionths: 0,
4722 excess_data: Vec::new()
4724 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4725 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4726 short_channel_id: 11,
4729 cltv_expiry_delta: 0,
4730 htlc_minimum_msat: 0,
4731 htlc_maximum_msat: 100_000,
4733 fee_proportional_millionths: 0,
4734 excess_data: Vec::new()
4737 // Attempt to route more than available results in a failure.
4738 let route_params = RouteParameters::from_payment_params_and_value(
4739 payment_params.clone(), 60_000);
4740 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4741 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4742 &scorer, &Default::default(), &random_seed_bytes) {
4743 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4744 } else { panic!(); }
4748 // Now, attempt to route 49 sats (just a bit below the capacity).
4749 let route_params = RouteParameters::from_payment_params_and_value(
4750 payment_params.clone(), 49_000);
4751 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4752 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4753 assert_eq!(route.paths.len(), 1);
4754 let mut total_amount_paid_msat = 0;
4755 for path in &route.paths {
4756 assert_eq!(path.hops.len(), 4);
4757 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4758 total_amount_paid_msat += path.final_value_msat();
4760 assert_eq!(total_amount_paid_msat, 49_000);
4764 // Attempt to route an exact amount is also fine
4765 let route_params = RouteParameters::from_payment_params_and_value(
4766 payment_params, 50_000);
4767 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4768 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4769 assert_eq!(route.paths.len(), 1);
4770 let mut total_amount_paid_msat = 0;
4771 for path in &route.paths {
4772 assert_eq!(path.hops.len(), 4);
4773 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4774 total_amount_paid_msat += path.final_value_msat();
4776 assert_eq!(total_amount_paid_msat, 50_000);
4781 fn ignore_fee_first_hop_test() {
4782 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4783 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4784 let scorer = ln_test_utils::TestScorer::new();
4785 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4786 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4787 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4789 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4790 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4791 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4792 short_channel_id: 1,
4795 cltv_expiry_delta: 0,
4796 htlc_minimum_msat: 0,
4797 htlc_maximum_msat: 100_000,
4798 fee_base_msat: 1_000_000,
4799 fee_proportional_millionths: 0,
4800 excess_data: Vec::new()
4802 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4803 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4804 short_channel_id: 3,
4807 cltv_expiry_delta: 0,
4808 htlc_minimum_msat: 0,
4809 htlc_maximum_msat: 50_000,
4811 fee_proportional_millionths: 0,
4812 excess_data: Vec::new()
4816 let route_params = RouteParameters::from_payment_params_and_value(
4817 payment_params, 50_000);
4818 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4819 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4820 assert_eq!(route.paths.len(), 1);
4821 let mut total_amount_paid_msat = 0;
4822 for path in &route.paths {
4823 assert_eq!(path.hops.len(), 2);
4824 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4825 total_amount_paid_msat += path.final_value_msat();
4827 assert_eq!(total_amount_paid_msat, 50_000);
4832 fn simple_mpp_route_test() {
4833 let (secp_ctx, _, _, _, _) = build_graph();
4834 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4835 let config = UserConfig::default();
4836 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4837 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4839 do_simple_mpp_route_test(clear_payment_params);
4841 // MPP to a 1-hop blinded path for nodes[2]
4842 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
4843 let blinded_path = BlindedPath {
4844 introduction_node_id: nodes[2],
4845 blinding_point: ln_test_utils::pubkey(42),
4846 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4848 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4850 fee_proportional_millionths: 0,
4851 htlc_minimum_msat: 0,
4852 htlc_maximum_msat: 0,
4853 cltv_expiry_delta: 0,
4854 features: BlindedHopFeatures::empty(),
4856 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4857 .with_bolt12_features(bolt12_features.clone()).unwrap();
4858 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4860 // MPP to 3 2-hop blinded paths
4861 let mut blinded_path_node_0 = blinded_path.clone();
4862 blinded_path_node_0.introduction_node_id = nodes[0];
4863 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4864 let mut node_0_payinfo = blinded_payinfo.clone();
4865 node_0_payinfo.htlc_maximum_msat = 50_000;
4867 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4868 blinded_path_node_7.introduction_node_id = nodes[7];
4869 let mut node_7_payinfo = blinded_payinfo.clone();
4870 node_7_payinfo.htlc_maximum_msat = 60_000;
4872 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4873 blinded_path_node_1.introduction_node_id = nodes[1];
4874 let mut node_1_payinfo = blinded_payinfo.clone();
4875 node_1_payinfo.htlc_maximum_msat = 180_000;
4877 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4879 (node_0_payinfo, blinded_path_node_0),
4880 (node_7_payinfo, blinded_path_node_7),
4881 (node_1_payinfo, blinded_path_node_1)
4883 .with_bolt12_features(bolt12_features).unwrap();
4884 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4888 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4889 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4890 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4891 let scorer = ln_test_utils::TestScorer::new();
4892 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4893 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4895 // We need a route consisting of 3 paths:
4896 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4897 // To achieve this, the amount being transferred should be around
4898 // the total capacity of these 3 paths.
4900 // First, we set limits on these (previously unlimited) channels.
4901 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4903 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4904 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4905 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4906 short_channel_id: 1,
4909 cltv_expiry_delta: 0,
4910 htlc_minimum_msat: 0,
4911 htlc_maximum_msat: 100_000,
4913 fee_proportional_millionths: 0,
4914 excess_data: Vec::new()
4916 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4917 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4918 short_channel_id: 3,
4921 cltv_expiry_delta: 0,
4922 htlc_minimum_msat: 0,
4923 htlc_maximum_msat: 50_000,
4925 fee_proportional_millionths: 0,
4926 excess_data: Vec::new()
4929 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4930 // (total limit 60).
4931 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4932 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4933 short_channel_id: 12,
4936 cltv_expiry_delta: 0,
4937 htlc_minimum_msat: 0,
4938 htlc_maximum_msat: 60_000,
4940 fee_proportional_millionths: 0,
4941 excess_data: Vec::new()
4943 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4944 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4945 short_channel_id: 13,
4948 cltv_expiry_delta: 0,
4949 htlc_minimum_msat: 0,
4950 htlc_maximum_msat: 60_000,
4952 fee_proportional_millionths: 0,
4953 excess_data: Vec::new()
4956 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4957 // (total capacity 180 sats).
4958 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4959 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4960 short_channel_id: 2,
4963 cltv_expiry_delta: 0,
4964 htlc_minimum_msat: 0,
4965 htlc_maximum_msat: 200_000,
4967 fee_proportional_millionths: 0,
4968 excess_data: Vec::new()
4970 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4971 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4972 short_channel_id: 4,
4975 cltv_expiry_delta: 0,
4976 htlc_minimum_msat: 0,
4977 htlc_maximum_msat: 180_000,
4979 fee_proportional_millionths: 0,
4980 excess_data: Vec::new()
4984 // Attempt to route more than available results in a failure.
4985 let route_params = RouteParameters::from_payment_params_and_value(
4986 payment_params.clone(), 300_000);
4987 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4988 &our_id, &route_params, &network_graph.read_only(), None,
4989 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4990 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4991 } else { panic!(); }
4995 // Attempt to route while setting max_path_count to 0 results in a failure.
4996 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4997 let route_params = RouteParameters::from_payment_params_and_value(
4998 zero_payment_params, 100);
4999 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5000 &our_id, &route_params, &network_graph.read_only(), None,
5001 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5002 assert_eq!(err, "Can't find a route with no paths allowed.");
5003 } else { panic!(); }
5007 // Attempt to route while setting max_path_count to 3 results in a failure.
5008 // This is the case because the minimal_value_contribution_msat would require each path
5009 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5010 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5011 let route_params = RouteParameters::from_payment_params_and_value(
5012 fail_payment_params, 250_000);
5013 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5014 &our_id, &route_params, &network_graph.read_only(), None,
5015 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5016 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5017 } else { panic!(); }
5021 // Now, attempt to route 250 sats (just a bit below the capacity).
5022 // Our algorithm should provide us with these 3 paths.
5023 let route_params = RouteParameters::from_payment_params_and_value(
5024 payment_params.clone(), 250_000);
5025 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5026 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5027 assert_eq!(route.paths.len(), 3);
5028 let mut total_amount_paid_msat = 0;
5029 for path in &route.paths {
5030 if let Some(bt) = &path.blinded_tail {
5031 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5033 assert_eq!(path.hops.len(), 2);
5034 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5036 total_amount_paid_msat += path.final_value_msat();
5038 assert_eq!(total_amount_paid_msat, 250_000);
5042 // Attempt to route an exact amount is also fine
5043 let route_params = RouteParameters::from_payment_params_and_value(
5044 payment_params.clone(), 290_000);
5045 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5046 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5047 assert_eq!(route.paths.len(), 3);
5048 let mut total_amount_paid_msat = 0;
5049 for path in &route.paths {
5050 if payment_params.payee.blinded_route_hints().len() != 0 {
5051 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5052 if let Some(bt) = &path.blinded_tail {
5053 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5054 if bt.hops.len() > 1 {
5055 assert_eq!(path.hops.last().unwrap().pubkey,
5056 payment_params.payee.blinded_route_hints().iter()
5057 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5058 .map(|(_, p)| p.introduction_node_id).unwrap());
5060 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5063 assert_eq!(path.hops.len(), 2);
5064 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5066 total_amount_paid_msat += path.final_value_msat();
5068 assert_eq!(total_amount_paid_msat, 290_000);
5073 fn long_mpp_route_test() {
5074 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5075 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5076 let scorer = ln_test_utils::TestScorer::new();
5077 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5078 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5079 let config = UserConfig::default();
5080 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5081 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5084 // We need a route consisting of 3 paths:
5085 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5086 // Note that these paths overlap (channels 5, 12, 13).
5087 // We will route 300 sats.
5088 // Each path will have 100 sats capacity, those channels which
5089 // are used twice will have 200 sats capacity.
5091 // Disable other potential paths.
5092 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5093 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5094 short_channel_id: 2,
5097 cltv_expiry_delta: 0,
5098 htlc_minimum_msat: 0,
5099 htlc_maximum_msat: 100_000,
5101 fee_proportional_millionths: 0,
5102 excess_data: Vec::new()
5104 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5105 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5106 short_channel_id: 7,
5109 cltv_expiry_delta: 0,
5110 htlc_minimum_msat: 0,
5111 htlc_maximum_msat: 100_000,
5113 fee_proportional_millionths: 0,
5114 excess_data: Vec::new()
5117 // Path via {node0, node2} is channels {1, 3, 5}.
5118 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5119 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5120 short_channel_id: 1,
5123 cltv_expiry_delta: 0,
5124 htlc_minimum_msat: 0,
5125 htlc_maximum_msat: 100_000,
5127 fee_proportional_millionths: 0,
5128 excess_data: Vec::new()
5130 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5131 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5132 short_channel_id: 3,
5135 cltv_expiry_delta: 0,
5136 htlc_minimum_msat: 0,
5137 htlc_maximum_msat: 100_000,
5139 fee_proportional_millionths: 0,
5140 excess_data: Vec::new()
5143 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5144 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5145 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5146 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5147 short_channel_id: 5,
5150 cltv_expiry_delta: 0,
5151 htlc_minimum_msat: 0,
5152 htlc_maximum_msat: 200_000,
5154 fee_proportional_millionths: 0,
5155 excess_data: Vec::new()
5158 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5159 // Add 100 sats to the capacities of {12, 13}, because these channels
5160 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5161 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5162 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5163 short_channel_id: 12,
5166 cltv_expiry_delta: 0,
5167 htlc_minimum_msat: 0,
5168 htlc_maximum_msat: 200_000,
5170 fee_proportional_millionths: 0,
5171 excess_data: Vec::new()
5173 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5174 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5175 short_channel_id: 13,
5178 cltv_expiry_delta: 0,
5179 htlc_minimum_msat: 0,
5180 htlc_maximum_msat: 200_000,
5182 fee_proportional_millionths: 0,
5183 excess_data: Vec::new()
5186 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5187 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5188 short_channel_id: 6,
5191 cltv_expiry_delta: 0,
5192 htlc_minimum_msat: 0,
5193 htlc_maximum_msat: 100_000,
5195 fee_proportional_millionths: 0,
5196 excess_data: Vec::new()
5198 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5199 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5200 short_channel_id: 11,
5203 cltv_expiry_delta: 0,
5204 htlc_minimum_msat: 0,
5205 htlc_maximum_msat: 100_000,
5207 fee_proportional_millionths: 0,
5208 excess_data: Vec::new()
5211 // Path via {node7, node2} is channels {12, 13, 5}.
5212 // We already limited them to 200 sats (they are used twice for 100 sats).
5213 // Nothing to do here.
5216 // Attempt to route more than available results in a failure.
5217 let route_params = RouteParameters::from_payment_params_and_value(
5218 payment_params.clone(), 350_000);
5219 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5220 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5221 &scorer, &Default::default(), &random_seed_bytes) {
5222 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5223 } else { panic!(); }
5227 // Now, attempt to route 300 sats (exact amount we can route).
5228 // Our algorithm should provide us with these 3 paths, 100 sats each.
5229 let route_params = RouteParameters::from_payment_params_and_value(
5230 payment_params, 300_000);
5231 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5232 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5233 assert_eq!(route.paths.len(), 3);
5235 let mut total_amount_paid_msat = 0;
5236 for path in &route.paths {
5237 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5238 total_amount_paid_msat += path.final_value_msat();
5240 assert_eq!(total_amount_paid_msat, 300_000);
5246 fn mpp_cheaper_route_test() {
5247 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5248 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5249 let scorer = ln_test_utils::TestScorer::new();
5250 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5251 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5252 let config = UserConfig::default();
5253 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5254 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5257 // This test checks that if we have two cheaper paths and one more expensive path,
5258 // so that liquidity-wise any 2 of 3 combination is sufficient,
5259 // two cheaper paths will be taken.
5260 // These paths have equal available liquidity.
5262 // We need a combination of 3 paths:
5263 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5264 // Note that these paths overlap (channels 5, 12, 13).
5265 // Each path will have 100 sats capacity, those channels which
5266 // are used twice will have 200 sats capacity.
5268 // Disable other potential paths.
5269 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5270 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5271 short_channel_id: 2,
5274 cltv_expiry_delta: 0,
5275 htlc_minimum_msat: 0,
5276 htlc_maximum_msat: 100_000,
5278 fee_proportional_millionths: 0,
5279 excess_data: Vec::new()
5281 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5282 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5283 short_channel_id: 7,
5286 cltv_expiry_delta: 0,
5287 htlc_minimum_msat: 0,
5288 htlc_maximum_msat: 100_000,
5290 fee_proportional_millionths: 0,
5291 excess_data: Vec::new()
5294 // Path via {node0, node2} is channels {1, 3, 5}.
5295 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5296 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5297 short_channel_id: 1,
5300 cltv_expiry_delta: 0,
5301 htlc_minimum_msat: 0,
5302 htlc_maximum_msat: 100_000,
5304 fee_proportional_millionths: 0,
5305 excess_data: Vec::new()
5307 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5308 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5309 short_channel_id: 3,
5312 cltv_expiry_delta: 0,
5313 htlc_minimum_msat: 0,
5314 htlc_maximum_msat: 100_000,
5316 fee_proportional_millionths: 0,
5317 excess_data: Vec::new()
5320 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5321 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5322 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5323 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5324 short_channel_id: 5,
5327 cltv_expiry_delta: 0,
5328 htlc_minimum_msat: 0,
5329 htlc_maximum_msat: 200_000,
5331 fee_proportional_millionths: 0,
5332 excess_data: Vec::new()
5335 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5336 // Add 100 sats to the capacities of {12, 13}, because these channels
5337 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5338 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5339 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5340 short_channel_id: 12,
5343 cltv_expiry_delta: 0,
5344 htlc_minimum_msat: 0,
5345 htlc_maximum_msat: 200_000,
5347 fee_proportional_millionths: 0,
5348 excess_data: Vec::new()
5350 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5351 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5352 short_channel_id: 13,
5355 cltv_expiry_delta: 0,
5356 htlc_minimum_msat: 0,
5357 htlc_maximum_msat: 200_000,
5359 fee_proportional_millionths: 0,
5360 excess_data: Vec::new()
5363 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5364 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5365 short_channel_id: 6,
5368 cltv_expiry_delta: 0,
5369 htlc_minimum_msat: 0,
5370 htlc_maximum_msat: 100_000,
5371 fee_base_msat: 1_000,
5372 fee_proportional_millionths: 0,
5373 excess_data: Vec::new()
5375 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5376 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5377 short_channel_id: 11,
5380 cltv_expiry_delta: 0,
5381 htlc_minimum_msat: 0,
5382 htlc_maximum_msat: 100_000,
5384 fee_proportional_millionths: 0,
5385 excess_data: Vec::new()
5388 // Path via {node7, node2} is channels {12, 13, 5}.
5389 // We already limited them to 200 sats (they are used twice for 100 sats).
5390 // Nothing to do here.
5393 // Now, attempt to route 180 sats.
5394 // Our algorithm should provide us with these 2 paths.
5395 let route_params = RouteParameters::from_payment_params_and_value(
5396 payment_params, 180_000);
5397 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5398 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5399 assert_eq!(route.paths.len(), 2);
5401 let mut total_value_transferred_msat = 0;
5402 let mut total_paid_msat = 0;
5403 for path in &route.paths {
5404 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5405 total_value_transferred_msat += path.final_value_msat();
5406 for hop in &path.hops {
5407 total_paid_msat += hop.fee_msat;
5410 // If we paid fee, this would be higher.
5411 assert_eq!(total_value_transferred_msat, 180_000);
5412 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5413 assert_eq!(total_fees_paid, 0);
5418 fn fees_on_mpp_route_test() {
5419 // This test makes sure that MPP algorithm properly takes into account
5420 // fees charged on the channels, by making the fees impactful:
5421 // if the fee is not properly accounted for, the behavior is different.
5422 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5423 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5424 let scorer = ln_test_utils::TestScorer::new();
5425 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5426 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5427 let config = UserConfig::default();
5428 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5429 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5432 // We need a route consisting of 2 paths:
5433 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5434 // We will route 200 sats, Each path will have 100 sats capacity.
5436 // This test is not particularly stable: e.g.,
5437 // there's a way to route via {node0, node2, node4}.
5438 // It works while pathfinding is deterministic, but can be broken otherwise.
5439 // It's fine to ignore this concern for now.
5441 // Disable other potential paths.
5442 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5443 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5444 short_channel_id: 2,
5447 cltv_expiry_delta: 0,
5448 htlc_minimum_msat: 0,
5449 htlc_maximum_msat: 100_000,
5451 fee_proportional_millionths: 0,
5452 excess_data: Vec::new()
5455 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5456 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5457 short_channel_id: 7,
5460 cltv_expiry_delta: 0,
5461 htlc_minimum_msat: 0,
5462 htlc_maximum_msat: 100_000,
5464 fee_proportional_millionths: 0,
5465 excess_data: Vec::new()
5468 // Path via {node0, node2} is channels {1, 3, 5}.
5469 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5470 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5471 short_channel_id: 1,
5474 cltv_expiry_delta: 0,
5475 htlc_minimum_msat: 0,
5476 htlc_maximum_msat: 100_000,
5478 fee_proportional_millionths: 0,
5479 excess_data: Vec::new()
5481 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5482 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5483 short_channel_id: 3,
5486 cltv_expiry_delta: 0,
5487 htlc_minimum_msat: 0,
5488 htlc_maximum_msat: 100_000,
5490 fee_proportional_millionths: 0,
5491 excess_data: Vec::new()
5494 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5495 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5496 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5497 short_channel_id: 5,
5500 cltv_expiry_delta: 0,
5501 htlc_minimum_msat: 0,
5502 htlc_maximum_msat: 100_000,
5504 fee_proportional_millionths: 0,
5505 excess_data: Vec::new()
5508 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5509 // All channels should be 100 sats capacity. But for the fee experiment,
5510 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5511 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5512 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5513 // so no matter how large are other channels,
5514 // the whole path will be limited by 100 sats with just these 2 conditions:
5515 // - channel 12 capacity is 250 sats
5516 // - fee for channel 6 is 150 sats
5517 // Let's test this by enforcing these 2 conditions and removing other limits.
5518 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5519 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5520 short_channel_id: 12,
5523 cltv_expiry_delta: 0,
5524 htlc_minimum_msat: 0,
5525 htlc_maximum_msat: 250_000,
5527 fee_proportional_millionths: 0,
5528 excess_data: Vec::new()
5530 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5531 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5532 short_channel_id: 13,
5535 cltv_expiry_delta: 0,
5536 htlc_minimum_msat: 0,
5537 htlc_maximum_msat: MAX_VALUE_MSAT,
5539 fee_proportional_millionths: 0,
5540 excess_data: Vec::new()
5543 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5544 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5545 short_channel_id: 6,
5548 cltv_expiry_delta: 0,
5549 htlc_minimum_msat: 0,
5550 htlc_maximum_msat: MAX_VALUE_MSAT,
5551 fee_base_msat: 150_000,
5552 fee_proportional_millionths: 0,
5553 excess_data: Vec::new()
5555 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5556 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5557 short_channel_id: 11,
5560 cltv_expiry_delta: 0,
5561 htlc_minimum_msat: 0,
5562 htlc_maximum_msat: MAX_VALUE_MSAT,
5564 fee_proportional_millionths: 0,
5565 excess_data: Vec::new()
5569 // Attempt to route more than available results in a failure.
5570 let route_params = RouteParameters::from_payment_params_and_value(
5571 payment_params.clone(), 210_000);
5572 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5573 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5574 &scorer, &Default::default(), &random_seed_bytes) {
5575 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5576 } else { panic!(); }
5580 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5581 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5582 max_total_routing_fee_msat: Some(149_999) };
5583 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5584 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5585 &scorer, &Default::default(), &random_seed_bytes) {
5586 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5587 } else { panic!(); }
5591 // Now, attempt to route 200 sats (exact amount we can route).
5592 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5593 max_total_routing_fee_msat: Some(150_000) };
5594 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5595 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5596 assert_eq!(route.paths.len(), 2);
5598 let mut total_amount_paid_msat = 0;
5599 for path in &route.paths {
5600 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5601 total_amount_paid_msat += path.final_value_msat();
5603 assert_eq!(total_amount_paid_msat, 200_000);
5604 assert_eq!(route.get_total_fees(), 150_000);
5609 fn mpp_with_last_hops() {
5610 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5611 // via a single last-hop route hint, we'd fail to route if we first collected routes
5612 // totaling close but not quite enough to fund the full payment.
5614 // This was because we considered last-hop hints to have exactly the sought payment amount
5615 // instead of the amount we were trying to collect, needlessly limiting our path searching
5616 // at the very first hop.
5618 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5619 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5620 // to only have the remaining to-collect amount in available liquidity.
5622 // This bug appeared in production in some specific channel configurations.
5623 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5624 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5625 let scorer = ln_test_utils::TestScorer::new();
5626 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5627 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5628 let config = UserConfig::default();
5629 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5630 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5631 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5632 src_node_id: nodes[2],
5633 short_channel_id: 42,
5634 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5635 cltv_expiry_delta: 42,
5636 htlc_minimum_msat: None,
5637 htlc_maximum_msat: None,
5638 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5640 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5641 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5642 // would first use the no-fee route and then fail to find a path along the second route as
5643 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5644 // under 5% of our payment amount.
5645 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5646 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5647 short_channel_id: 1,
5650 cltv_expiry_delta: (5 << 4) | 5,
5651 htlc_minimum_msat: 0,
5652 htlc_maximum_msat: 99_000,
5653 fee_base_msat: u32::max_value(),
5654 fee_proportional_millionths: u32::max_value(),
5655 excess_data: Vec::new()
5657 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5658 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5659 short_channel_id: 2,
5662 cltv_expiry_delta: (5 << 4) | 3,
5663 htlc_minimum_msat: 0,
5664 htlc_maximum_msat: 99_000,
5665 fee_base_msat: u32::max_value(),
5666 fee_proportional_millionths: u32::max_value(),
5667 excess_data: Vec::new()
5669 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5670 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5671 short_channel_id: 4,
5674 cltv_expiry_delta: (4 << 4) | 1,
5675 htlc_minimum_msat: 0,
5676 htlc_maximum_msat: MAX_VALUE_MSAT,
5678 fee_proportional_millionths: 0,
5679 excess_data: Vec::new()
5681 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5682 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5683 short_channel_id: 13,
5685 flags: 0|2, // Channel disabled
5686 cltv_expiry_delta: (13 << 4) | 1,
5687 htlc_minimum_msat: 0,
5688 htlc_maximum_msat: MAX_VALUE_MSAT,
5690 fee_proportional_millionths: 2000000,
5691 excess_data: Vec::new()
5694 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5696 let route_params = RouteParameters::from_payment_params_and_value(
5697 payment_params, 100_000);
5698 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5699 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5700 assert_eq!(route.paths.len(), 2);
5701 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5702 // Paths are manually ordered ordered by SCID, so:
5703 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5704 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5705 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5706 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5707 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5708 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5709 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5710 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5711 assert_eq!(route.get_total_fees(), 1);
5712 assert_eq!(route.get_total_amount(), 100_000);
5716 fn drop_lowest_channel_mpp_route_test() {
5717 // This test checks that low-capacity channel is dropped when after
5718 // path finding we realize that we found more capacity than we need.
5719 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5720 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5721 let scorer = ln_test_utils::TestScorer::new();
5722 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5723 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5724 let config = UserConfig::default();
5725 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5726 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5728 .with_max_channel_saturation_power_of_half(0);
5730 // We need a route consisting of 3 paths:
5731 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5733 // The first and the second paths should be sufficient, but the third should be
5734 // cheaper, so that we select it but drop later.
5736 // First, we set limits on these (previously unlimited) channels.
5737 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5739 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5740 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5741 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5742 short_channel_id: 1,
5745 cltv_expiry_delta: 0,
5746 htlc_minimum_msat: 0,
5747 htlc_maximum_msat: 100_000,
5749 fee_proportional_millionths: 0,
5750 excess_data: Vec::new()
5752 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5753 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5754 short_channel_id: 3,
5757 cltv_expiry_delta: 0,
5758 htlc_minimum_msat: 0,
5759 htlc_maximum_msat: 50_000,
5761 fee_proportional_millionths: 0,
5762 excess_data: Vec::new()
5765 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5766 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5767 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5768 short_channel_id: 12,
5771 cltv_expiry_delta: 0,
5772 htlc_minimum_msat: 0,
5773 htlc_maximum_msat: 60_000,
5775 fee_proportional_millionths: 0,
5776 excess_data: Vec::new()
5778 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5779 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5780 short_channel_id: 13,
5783 cltv_expiry_delta: 0,
5784 htlc_minimum_msat: 0,
5785 htlc_maximum_msat: 60_000,
5787 fee_proportional_millionths: 0,
5788 excess_data: Vec::new()
5791 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5792 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5793 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5794 short_channel_id: 2,
5797 cltv_expiry_delta: 0,
5798 htlc_minimum_msat: 0,
5799 htlc_maximum_msat: 20_000,
5801 fee_proportional_millionths: 0,
5802 excess_data: Vec::new()
5804 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5805 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5806 short_channel_id: 4,
5809 cltv_expiry_delta: 0,
5810 htlc_minimum_msat: 0,
5811 htlc_maximum_msat: 20_000,
5813 fee_proportional_millionths: 0,
5814 excess_data: Vec::new()
5818 // Attempt to route more than available results in a failure.
5819 let route_params = RouteParameters::from_payment_params_and_value(
5820 payment_params.clone(), 150_000);
5821 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5822 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5823 &scorer, &Default::default(), &random_seed_bytes) {
5824 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5825 } else { panic!(); }
5829 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5830 // Our algorithm should provide us with these 3 paths.
5831 let route_params = RouteParameters::from_payment_params_and_value(
5832 payment_params.clone(), 125_000);
5833 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5834 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5835 assert_eq!(route.paths.len(), 3);
5836 let mut total_amount_paid_msat = 0;
5837 for path in &route.paths {
5838 assert_eq!(path.hops.len(), 2);
5839 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5840 total_amount_paid_msat += path.final_value_msat();
5842 assert_eq!(total_amount_paid_msat, 125_000);
5846 // Attempt to route without the last small cheap channel
5847 let route_params = RouteParameters::from_payment_params_and_value(
5848 payment_params, 90_000);
5849 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5850 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5851 assert_eq!(route.paths.len(), 2);
5852 let mut total_amount_paid_msat = 0;
5853 for path in &route.paths {
5854 assert_eq!(path.hops.len(), 2);
5855 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5856 total_amount_paid_msat += path.final_value_msat();
5858 assert_eq!(total_amount_paid_msat, 90_000);
5863 fn min_criteria_consistency() {
5864 // Test that we don't use an inconsistent metric between updating and walking nodes during
5865 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5866 // was updated with a different criterion from the heap sorting, resulting in loops in
5867 // calculated paths. We test for that specific case here.
5869 // We construct a network that looks like this:
5871 // node2 -1(3)2- node3
5875 // node1 -1(5)2- node4 -1(1)2- node6
5881 // We create a loop on the side of our real path - our destination is node 6, with a
5882 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5883 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5884 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5885 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5886 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5887 // "previous hop" being set to node 3, creating a loop in the path.
5888 let secp_ctx = Secp256k1::new();
5889 let logger = Arc::new(ln_test_utils::TestLogger::new());
5890 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5891 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5892 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5893 let scorer = ln_test_utils::TestScorer::new();
5894 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5895 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5896 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5898 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5899 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5900 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5901 short_channel_id: 6,
5904 cltv_expiry_delta: (6 << 4) | 0,
5905 htlc_minimum_msat: 0,
5906 htlc_maximum_msat: MAX_VALUE_MSAT,
5908 fee_proportional_millionths: 0,
5909 excess_data: Vec::new()
5911 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5913 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5914 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5915 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5916 short_channel_id: 5,
5919 cltv_expiry_delta: (5 << 4) | 0,
5920 htlc_minimum_msat: 0,
5921 htlc_maximum_msat: MAX_VALUE_MSAT,
5923 fee_proportional_millionths: 0,
5924 excess_data: Vec::new()
5926 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5928 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5929 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5930 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5931 short_channel_id: 4,
5934 cltv_expiry_delta: (4 << 4) | 0,
5935 htlc_minimum_msat: 0,
5936 htlc_maximum_msat: MAX_VALUE_MSAT,
5938 fee_proportional_millionths: 0,
5939 excess_data: Vec::new()
5941 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5943 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5944 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5945 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5946 short_channel_id: 3,
5949 cltv_expiry_delta: (3 << 4) | 0,
5950 htlc_minimum_msat: 0,
5951 htlc_maximum_msat: MAX_VALUE_MSAT,
5953 fee_proportional_millionths: 0,
5954 excess_data: Vec::new()
5956 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5958 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5959 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5960 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5961 short_channel_id: 2,
5964 cltv_expiry_delta: (2 << 4) | 0,
5965 htlc_minimum_msat: 0,
5966 htlc_maximum_msat: MAX_VALUE_MSAT,
5968 fee_proportional_millionths: 0,
5969 excess_data: Vec::new()
5972 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5973 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5974 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5975 short_channel_id: 1,
5978 cltv_expiry_delta: (1 << 4) | 0,
5979 htlc_minimum_msat: 100,
5980 htlc_maximum_msat: MAX_VALUE_MSAT,
5982 fee_proportional_millionths: 0,
5983 excess_data: Vec::new()
5985 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5988 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5989 let route_params = RouteParameters::from_payment_params_and_value(
5990 payment_params, 10_000);
5991 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5992 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5993 assert_eq!(route.paths.len(), 1);
5994 assert_eq!(route.paths[0].hops.len(), 3);
5996 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5997 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5998 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5999 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6000 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6001 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6003 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6004 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6005 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6006 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6007 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6008 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6010 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6011 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6012 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6013 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6014 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6015 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6021 fn exact_fee_liquidity_limit() {
6022 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6023 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6024 // we calculated fees on a higher value, resulting in us ignoring such paths.
6025 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6026 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6027 let scorer = ln_test_utils::TestScorer::new();
6028 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6029 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6030 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6032 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6034 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6035 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6036 short_channel_id: 2,
6039 cltv_expiry_delta: 0,
6040 htlc_minimum_msat: 0,
6041 htlc_maximum_msat: 85_000,
6043 fee_proportional_millionths: 0,
6044 excess_data: Vec::new()
6047 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6048 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6049 short_channel_id: 12,
6052 cltv_expiry_delta: (4 << 4) | 1,
6053 htlc_minimum_msat: 0,
6054 htlc_maximum_msat: 270_000,
6056 fee_proportional_millionths: 1000000,
6057 excess_data: Vec::new()
6061 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6062 // 200% fee charged channel 13 in the 1-to-2 direction.
6063 let mut route_params = RouteParameters::from_payment_params_and_value(
6064 payment_params, 90_000);
6065 route_params.max_total_routing_fee_msat = Some(90_000*2);
6066 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6067 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6068 assert_eq!(route.paths.len(), 1);
6069 assert_eq!(route.paths[0].hops.len(), 2);
6071 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6072 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6073 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6074 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6075 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6076 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6078 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6079 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6080 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6081 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6082 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6083 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6088 fn htlc_max_reduction_below_min() {
6089 // Test that if, while walking the graph, we reduce the value being sent to meet an
6090 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6091 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6092 // resulting in us thinking there is no possible path, even if other paths exist.
6093 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6094 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6095 let scorer = ln_test_utils::TestScorer::new();
6096 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6097 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6098 let config = UserConfig::default();
6099 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6100 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6103 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6104 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6105 // then try to send 90_000.
6106 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6107 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6108 short_channel_id: 2,
6111 cltv_expiry_delta: 0,
6112 htlc_minimum_msat: 0,
6113 htlc_maximum_msat: 80_000,
6115 fee_proportional_millionths: 0,
6116 excess_data: Vec::new()
6118 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6119 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6120 short_channel_id: 4,
6123 cltv_expiry_delta: (4 << 4) | 1,
6124 htlc_minimum_msat: 90_000,
6125 htlc_maximum_msat: MAX_VALUE_MSAT,
6127 fee_proportional_millionths: 0,
6128 excess_data: Vec::new()
6132 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6133 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6134 // expensive) channels 12-13 path.
6135 let mut route_params = RouteParameters::from_payment_params_and_value(
6136 payment_params, 90_000);
6137 route_params.max_total_routing_fee_msat = Some(90_000*2);
6138 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6139 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6140 assert_eq!(route.paths.len(), 1);
6141 assert_eq!(route.paths[0].hops.len(), 2);
6143 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6144 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6145 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6146 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6147 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6148 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6150 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6151 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6152 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6153 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6154 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6155 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6160 fn multiple_direct_first_hops() {
6161 // Previously we'd only ever considered one first hop path per counterparty.
6162 // However, as we don't restrict users to one channel per peer, we really need to support
6163 // looking at all first hop paths.
6164 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6165 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6166 // route over multiple channels with the same first hop.
6167 let secp_ctx = Secp256k1::new();
6168 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6169 let logger = Arc::new(ln_test_utils::TestLogger::new());
6170 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6171 let scorer = ln_test_utils::TestScorer::new();
6172 let config = UserConfig::default();
6173 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6174 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6176 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6177 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6180 let route_params = RouteParameters::from_payment_params_and_value(
6181 payment_params.clone(), 100_000);
6182 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6183 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6184 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6185 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6186 assert_eq!(route.paths.len(), 1);
6187 assert_eq!(route.paths[0].hops.len(), 1);
6189 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6190 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6191 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6194 let route_params = RouteParameters::from_payment_params_and_value(
6195 payment_params.clone(), 100_000);
6196 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6197 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6198 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6199 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6200 assert_eq!(route.paths.len(), 2);
6201 assert_eq!(route.paths[0].hops.len(), 1);
6202 assert_eq!(route.paths[1].hops.len(), 1);
6204 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6205 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6207 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6208 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6210 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6211 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6215 // If we have a bunch of outbound channels to the same node, where most are not
6216 // sufficient to pay the full payment, but one is, we should default to just using the
6217 // one single channel that has sufficient balance, avoiding MPP.
6219 // If we have several options above the 3xpayment value threshold, we should pick the
6220 // smallest of them, avoiding further fragmenting our available outbound balance to
6222 let route_params = RouteParameters::from_payment_params_and_value(
6223 payment_params, 100_000);
6224 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6225 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6226 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6227 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6228 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6229 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6230 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6231 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6232 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6233 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6234 assert_eq!(route.paths.len(), 1);
6235 assert_eq!(route.paths[0].hops.len(), 1);
6237 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6238 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6239 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6244 fn prefers_shorter_route_with_higher_fees() {
6245 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6246 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6247 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6249 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6250 let scorer = ln_test_utils::TestScorer::new();
6251 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6252 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6253 let route_params = RouteParameters::from_payment_params_and_value(
6254 payment_params.clone(), 100);
6255 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6256 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6257 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6259 assert_eq!(route.get_total_fees(), 100);
6260 assert_eq!(route.get_total_amount(), 100);
6261 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6263 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6264 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6265 let scorer = FixedPenaltyScorer::with_penalty(100);
6266 let route_params = RouteParameters::from_payment_params_and_value(
6267 payment_params, 100);
6268 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6269 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6270 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6272 assert_eq!(route.get_total_fees(), 300);
6273 assert_eq!(route.get_total_amount(), 100);
6274 assert_eq!(path, vec![2, 4, 7, 10]);
6277 struct BadChannelScorer {
6278 short_channel_id: u64,
6282 impl Writeable for BadChannelScorer {
6283 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6285 impl ScoreLookUp for BadChannelScorer {
6286 type ScoreParams = ();
6287 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6288 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6292 struct BadNodeScorer {
6297 impl Writeable for BadNodeScorer {
6298 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6301 impl ScoreLookUp for BadNodeScorer {
6302 type ScoreParams = ();
6303 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6304 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6309 fn avoids_routing_through_bad_channels_and_nodes() {
6310 let (secp_ctx, network, _, _, logger) = build_graph();
6311 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6312 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6313 let network_graph = network.read_only();
6315 // A path to nodes[6] exists when no penalties are applied to any channel.
6316 let scorer = ln_test_utils::TestScorer::new();
6317 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6318 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6319 let route_params = RouteParameters::from_payment_params_and_value(
6320 payment_params, 100);
6321 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6322 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6323 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6325 assert_eq!(route.get_total_fees(), 100);
6326 assert_eq!(route.get_total_amount(), 100);
6327 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6329 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6330 let scorer = BadChannelScorer { short_channel_id: 6 };
6331 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6332 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6333 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6335 assert_eq!(route.get_total_fees(), 300);
6336 assert_eq!(route.get_total_amount(), 100);
6337 assert_eq!(path, vec![2, 4, 7, 10]);
6339 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6340 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6341 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6342 &scorer, &Default::default(), &random_seed_bytes) {
6343 Err(LightningError { err, .. } ) => {
6344 assert_eq!(err, "Failed to find a path to the given destination");
6346 Ok(_) => panic!("Expected error"),
6351 fn total_fees_single_path() {
6353 paths: vec![Path { hops: vec![
6355 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6356 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6357 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6360 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6361 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6362 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6365 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6366 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6367 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6369 ], blinded_tail: None }],
6373 assert_eq!(route.get_total_fees(), 250);
6374 assert_eq!(route.get_total_amount(), 225);
6378 fn total_fees_multi_path() {
6380 paths: vec![Path { hops: vec![
6382 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6383 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6384 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6387 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6388 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6389 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6391 ], blinded_tail: None }, Path { hops: vec![
6393 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6394 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6395 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6398 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6399 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6400 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6402 ], blinded_tail: None }],
6406 assert_eq!(route.get_total_fees(), 200);
6407 assert_eq!(route.get_total_amount(), 300);
6411 fn total_empty_route_no_panic() {
6412 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6413 // would both panic if the route was completely empty. We test to ensure they return 0
6414 // here, even though its somewhat nonsensical as a route.
6415 let route = Route { paths: Vec::new(), route_params: None };
6417 assert_eq!(route.get_total_fees(), 0);
6418 assert_eq!(route.get_total_amount(), 0);
6422 fn limits_total_cltv_delta() {
6423 let (secp_ctx, network, _, _, logger) = build_graph();
6424 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6425 let network_graph = network.read_only();
6427 let scorer = ln_test_utils::TestScorer::new();
6429 // Make sure that generally there is at least one route available
6430 let feasible_max_total_cltv_delta = 1008;
6431 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6432 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6433 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6434 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6435 let route_params = RouteParameters::from_payment_params_and_value(
6436 feasible_payment_params, 100);
6437 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6438 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6439 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6440 assert_ne!(path.len(), 0);
6442 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6443 let fail_max_total_cltv_delta = 23;
6444 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6445 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6446 let route_params = RouteParameters::from_payment_params_and_value(
6447 fail_payment_params, 100);
6448 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6449 &Default::default(), &random_seed_bytes)
6451 Err(LightningError { err, .. } ) => {
6452 assert_eq!(err, "Failed to find a path to the given destination");
6454 Ok(_) => panic!("Expected error"),
6459 fn avoids_recently_failed_paths() {
6460 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6461 // randomly inserting channels into it until we can't find a route anymore.
6462 let (secp_ctx, network, _, _, logger) = build_graph();
6463 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6464 let network_graph = network.read_only();
6466 let scorer = ln_test_utils::TestScorer::new();
6467 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6468 .with_max_path_count(1);
6469 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6470 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6472 // We should be able to find a route initially, and then after we fail a few random
6473 // channels eventually we won't be able to any longer.
6474 let route_params = RouteParameters::from_payment_params_and_value(
6475 payment_params.clone(), 100);
6476 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6477 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6479 let route_params = RouteParameters::from_payment_params_and_value(
6480 payment_params.clone(), 100);
6481 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6482 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6484 for chan in route.paths[0].hops.iter() {
6485 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6487 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6488 % route.paths[0].hops.len();
6489 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6495 fn limits_path_length() {
6496 let (secp_ctx, network, _, _, logger) = build_line_graph();
6497 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6498 let network_graph = network.read_only();
6500 let scorer = ln_test_utils::TestScorer::new();
6501 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6502 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6504 // First check we can actually create a long route on this graph.
6505 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6506 let route_params = RouteParameters::from_payment_params_and_value(
6507 feasible_payment_params, 100);
6508 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6509 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6510 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6511 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6513 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6514 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6515 let route_params = RouteParameters::from_payment_params_and_value(
6516 fail_payment_params, 100);
6517 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6518 &Default::default(), &random_seed_bytes)
6520 Err(LightningError { err, .. } ) => {
6521 assert_eq!(err, "Failed to find a path to the given destination");
6523 Ok(_) => panic!("Expected error"),
6528 fn adds_and_limits_cltv_offset() {
6529 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6530 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6532 let scorer = ln_test_utils::TestScorer::new();
6534 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6535 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6536 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6537 let route_params = RouteParameters::from_payment_params_and_value(
6538 payment_params.clone(), 100);
6539 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6540 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6541 assert_eq!(route.paths.len(), 1);
6543 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6545 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6546 let mut route_default = route.clone();
6547 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6548 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6549 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6550 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6551 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6553 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6554 let mut route_limited = route.clone();
6555 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6556 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6557 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6558 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6559 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6563 fn adds_plausible_cltv_offset() {
6564 let (secp_ctx, network, _, _, logger) = build_graph();
6565 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6566 let network_graph = network.read_only();
6567 let network_nodes = network_graph.nodes();
6568 let network_channels = network_graph.channels();
6569 let scorer = ln_test_utils::TestScorer::new();
6570 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6571 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6572 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6574 let route_params = RouteParameters::from_payment_params_and_value(
6575 payment_params.clone(), 100);
6576 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6577 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6578 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6580 let mut path_plausibility = vec![];
6582 for p in route.paths {
6583 // 1. Select random observation point
6584 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6585 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6587 prng.process_in_place(&mut random_bytes);
6588 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6589 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6591 // 2. Calculate what CLTV expiry delta we would observe there
6592 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6594 // 3. Starting from the observation point, find candidate paths
6595 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6596 candidates.push_back((observation_point, vec![]));
6598 let mut found_plausible_candidate = false;
6600 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6601 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6602 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6603 found_plausible_candidate = true;
6604 break 'candidate_loop;
6608 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6609 for channel_id in &cur_node.channels {
6610 if let Some(channel_info) = network_channels.get(&channel_id) {
6611 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6612 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6613 if cur_path_cltv_deltas.iter().sum::<u32>()
6614 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6615 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6616 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6617 candidates.push_back((*next_id, new_path_cltv_deltas));
6625 path_plausibility.push(found_plausible_candidate);
6627 assert!(path_plausibility.iter().all(|x| *x));
6631 fn builds_correct_path_from_hops() {
6632 let (secp_ctx, network, _, _, logger) = build_graph();
6633 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6634 let network_graph = network.read_only();
6636 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6637 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6639 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6640 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6641 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6642 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6643 Arc::clone(&logger), &random_seed_bytes).unwrap();
6644 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6645 assert_eq!(hops.len(), route.paths[0].hops.len());
6646 for (idx, hop_pubkey) in hops.iter().enumerate() {
6647 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6652 fn avoids_saturating_channels() {
6653 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6654 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6655 let decay_params = ProbabilisticScoringDecayParameters::default();
6656 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6658 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6659 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6660 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6661 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6662 short_channel_id: 4,
6665 cltv_expiry_delta: (4 << 4) | 1,
6666 htlc_minimum_msat: 0,
6667 htlc_maximum_msat: 250_000_000,
6669 fee_proportional_millionths: 0,
6670 excess_data: Vec::new()
6672 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6673 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6674 short_channel_id: 13,
6677 cltv_expiry_delta: (13 << 4) | 1,
6678 htlc_minimum_msat: 0,
6679 htlc_maximum_msat: 250_000_000,
6681 fee_proportional_millionths: 0,
6682 excess_data: Vec::new()
6685 let config = UserConfig::default();
6686 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6687 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6689 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6690 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6691 // 100,000 sats is less than the available liquidity on each channel, set above.
6692 let route_params = RouteParameters::from_payment_params_and_value(
6693 payment_params, 100_000_000);
6694 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6695 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6696 assert_eq!(route.paths.len(), 2);
6697 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6698 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6701 #[cfg(not(feature = "no-std"))]
6702 pub(super) fn random_init_seed() -> u64 {
6703 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6704 use core::hash::{BuildHasher, Hasher};
6705 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6706 println!("Using seed of {}", seed);
6711 #[cfg(not(feature = "no-std"))]
6712 fn generate_routes() {
6713 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6715 let logger = ln_test_utils::TestLogger::new();
6716 let graph = match super::bench_utils::read_network_graph(&logger) {
6724 let params = ProbabilisticScoringFeeParameters::default();
6725 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6726 let features = super::Bolt11InvoiceFeatures::empty();
6728 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6732 #[cfg(not(feature = "no-std"))]
6733 fn generate_routes_mpp() {
6734 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6736 let logger = ln_test_utils::TestLogger::new();
6737 let graph = match super::bench_utils::read_network_graph(&logger) {
6745 let params = ProbabilisticScoringFeeParameters::default();
6746 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6747 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6749 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6753 #[cfg(not(feature = "no-std"))]
6754 fn generate_large_mpp_routes() {
6755 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6757 let logger = ln_test_utils::TestLogger::new();
6758 let graph = match super::bench_utils::read_network_graph(&logger) {
6766 let params = ProbabilisticScoringFeeParameters::default();
6767 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6768 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6770 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6774 fn honors_manual_penalties() {
6775 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6776 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6778 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6779 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6781 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6782 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6784 // First check set manual penalties are returned by the scorer.
6785 let usage = ChannelUsage {
6787 inflight_htlc_msat: 0,
6788 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6790 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6791 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6792 let network_graph = network_graph.read_only();
6793 let channels = network_graph.channels();
6794 let channel = channels.get(&5).unwrap();
6795 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
6796 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop {
6798 short_channel_id: 5,
6800 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
6802 // Then check we can get a normal route
6803 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6804 let route_params = RouteParameters::from_payment_params_and_value(
6805 payment_params, 100);
6806 let route = get_route(&our_id, &route_params, &network_graph, None,
6807 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6808 assert!(route.is_ok());
6810 // Then check that we can't get a route if we ban an intermediate node.
6811 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6812 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6813 assert!(route.is_err());
6815 // Finally make sure we can route again, when we remove the ban.
6816 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6817 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6818 assert!(route.is_ok());
6822 fn abide_by_route_hint_max_htlc() {
6823 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6824 // params in the final route.
6825 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6826 let netgraph = network_graph.read_only();
6827 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6828 let scorer = ln_test_utils::TestScorer::new();
6829 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6830 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6831 let config = UserConfig::default();
6833 let max_htlc_msat = 50_000;
6834 let route_hint_1 = RouteHint(vec![RouteHintHop {
6835 src_node_id: nodes[2],
6836 short_channel_id: 42,
6839 proportional_millionths: 0,
6841 cltv_expiry_delta: 10,
6842 htlc_minimum_msat: None,
6843 htlc_maximum_msat: Some(max_htlc_msat),
6845 let dest_node_id = ln_test_utils::pubkey(42);
6846 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6847 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6848 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6851 // Make sure we'll error if our route hints don't have enough liquidity according to their
6852 // htlc_maximum_msat.
6853 let mut route_params = RouteParameters::from_payment_params_and_value(
6854 payment_params, max_htlc_msat + 1);
6855 route_params.max_total_routing_fee_msat = None;
6856 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6857 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6860 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6861 } else { panic!(); }
6863 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6864 let mut route_hint_2 = route_hint_1.clone();
6865 route_hint_2.0[0].short_channel_id = 43;
6866 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6867 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6868 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6870 let mut route_params = RouteParameters::from_payment_params_and_value(
6871 payment_params, max_htlc_msat + 1);
6872 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
6873 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6874 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6875 assert_eq!(route.paths.len(), 2);
6876 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6877 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6881 fn direct_channel_to_hints_with_max_htlc() {
6882 // Check that if we have a first hop channel peer that's connected to multiple provided route
6883 // hints, that we properly split the payment between the route hints if needed.
6884 let logger = Arc::new(ln_test_utils::TestLogger::new());
6885 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6886 let scorer = ln_test_utils::TestScorer::new();
6887 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6888 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6889 let config = UserConfig::default();
6891 let our_node_id = ln_test_utils::pubkey(42);
6892 let intermed_node_id = ln_test_utils::pubkey(43);
6893 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6895 let amt_msat = 900_000;
6896 let max_htlc_msat = 500_000;
6897 let route_hint_1 = RouteHint(vec![RouteHintHop {
6898 src_node_id: intermed_node_id,
6899 short_channel_id: 44,
6902 proportional_millionths: 0,
6904 cltv_expiry_delta: 10,
6905 htlc_minimum_msat: None,
6906 htlc_maximum_msat: Some(max_htlc_msat),
6908 src_node_id: intermed_node_id,
6909 short_channel_id: 45,
6912 proportional_millionths: 0,
6914 cltv_expiry_delta: 10,
6915 htlc_minimum_msat: None,
6916 // Check that later route hint max htlcs don't override earlier ones
6917 htlc_maximum_msat: Some(max_htlc_msat - 50),
6919 let mut route_hint_2 = route_hint_1.clone();
6920 route_hint_2.0[0].short_channel_id = 46;
6921 route_hint_2.0[1].short_channel_id = 47;
6922 let dest_node_id = ln_test_utils::pubkey(44);
6923 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6924 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6925 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6928 let route_params = RouteParameters::from_payment_params_and_value(
6929 payment_params, amt_msat);
6930 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6931 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6932 &Default::default(), &random_seed_bytes).unwrap();
6933 assert_eq!(route.paths.len(), 2);
6934 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6935 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6936 assert_eq!(route.get_total_amount(), amt_msat);
6938 // Re-run but with two first hop channels connected to the same route hint peers that must be
6940 let first_hops = vec![
6941 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6942 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6944 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6945 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6946 &Default::default(), &random_seed_bytes).unwrap();
6947 assert_eq!(route.paths.len(), 2);
6948 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6949 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6950 assert_eq!(route.get_total_amount(), amt_msat);
6952 // Make sure this works for blinded route hints.
6953 let blinded_path = BlindedPath {
6954 introduction_node_id: intermed_node_id,
6955 blinding_point: ln_test_utils::pubkey(42),
6957 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6958 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6961 let blinded_payinfo = BlindedPayInfo {
6963 fee_proportional_millionths: 0,
6964 htlc_minimum_msat: 1,
6965 htlc_maximum_msat: max_htlc_msat,
6966 cltv_expiry_delta: 10,
6967 features: BlindedHopFeatures::empty(),
6969 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
6970 let payment_params = PaymentParameters::blinded(vec![
6971 (blinded_payinfo.clone(), blinded_path.clone()),
6972 (blinded_payinfo.clone(), blinded_path.clone())])
6973 .with_bolt12_features(bolt12_features).unwrap();
6974 let route_params = RouteParameters::from_payment_params_and_value(
6975 payment_params, amt_msat);
6976 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6977 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6978 &Default::default(), &random_seed_bytes).unwrap();
6979 assert_eq!(route.paths.len(), 2);
6980 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6981 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6982 assert_eq!(route.get_total_amount(), amt_msat);
6986 fn blinded_route_ser() {
6987 let blinded_path_1 = BlindedPath {
6988 introduction_node_id: ln_test_utils::pubkey(42),
6989 blinding_point: ln_test_utils::pubkey(43),
6991 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6992 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6995 let blinded_path_2 = BlindedPath {
6996 introduction_node_id: ln_test_utils::pubkey(46),
6997 blinding_point: ln_test_utils::pubkey(47),
6999 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7000 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7003 // (De)serialize a Route with 1 blinded path out of two total paths.
7004 let mut route = Route { paths: vec![Path {
7005 hops: vec![RouteHop {
7006 pubkey: ln_test_utils::pubkey(50),
7007 node_features: NodeFeatures::empty(),
7008 short_channel_id: 42,
7009 channel_features: ChannelFeatures::empty(),
7011 cltv_expiry_delta: 0,
7012 maybe_announced_channel: true,
7014 blinded_tail: Some(BlindedTail {
7015 hops: blinded_path_1.blinded_hops,
7016 blinding_point: blinded_path_1.blinding_point,
7017 excess_final_cltv_expiry_delta: 40,
7018 final_value_msat: 100,
7020 hops: vec![RouteHop {
7021 pubkey: ln_test_utils::pubkey(51),
7022 node_features: NodeFeatures::empty(),
7023 short_channel_id: 43,
7024 channel_features: ChannelFeatures::empty(),
7026 cltv_expiry_delta: 0,
7027 maybe_announced_channel: true,
7028 }], blinded_tail: None }],
7031 let encoded_route = route.encode();
7032 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7033 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7034 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7036 // (De)serialize a Route with two paths, each containing a blinded tail.
7037 route.paths[1].blinded_tail = Some(BlindedTail {
7038 hops: blinded_path_2.blinded_hops,
7039 blinding_point: blinded_path_2.blinding_point,
7040 excess_final_cltv_expiry_delta: 41,
7041 final_value_msat: 101,
7043 let encoded_route = route.encode();
7044 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7045 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7046 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7050 fn blinded_path_inflight_processing() {
7051 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7052 // account for the blinded tail's final amount_msat.
7053 let mut inflight_htlcs = InFlightHtlcs::new();
7054 let blinded_path = BlindedPath {
7055 introduction_node_id: ln_test_utils::pubkey(43),
7056 blinding_point: ln_test_utils::pubkey(48),
7057 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7060 hops: vec![RouteHop {
7061 pubkey: ln_test_utils::pubkey(42),
7062 node_features: NodeFeatures::empty(),
7063 short_channel_id: 42,
7064 channel_features: ChannelFeatures::empty(),
7066 cltv_expiry_delta: 0,
7067 maybe_announced_channel: false,
7070 pubkey: blinded_path.introduction_node_id,
7071 node_features: NodeFeatures::empty(),
7072 short_channel_id: 43,
7073 channel_features: ChannelFeatures::empty(),
7075 cltv_expiry_delta: 0,
7076 maybe_announced_channel: false,
7078 blinded_tail: Some(BlindedTail {
7079 hops: blinded_path.blinded_hops,
7080 blinding_point: blinded_path.blinding_point,
7081 excess_final_cltv_expiry_delta: 0,
7082 final_value_msat: 200,
7085 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7086 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7087 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7091 fn blinded_path_cltv_shadow_offset() {
7092 // Make sure we add a shadow offset when sending to blinded paths.
7093 let blinded_path = BlindedPath {
7094 introduction_node_id: ln_test_utils::pubkey(43),
7095 blinding_point: ln_test_utils::pubkey(44),
7097 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7098 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7101 let mut route = Route { paths: vec![Path {
7102 hops: vec![RouteHop {
7103 pubkey: ln_test_utils::pubkey(42),
7104 node_features: NodeFeatures::empty(),
7105 short_channel_id: 42,
7106 channel_features: ChannelFeatures::empty(),
7108 cltv_expiry_delta: 0,
7109 maybe_announced_channel: false,
7112 pubkey: blinded_path.introduction_node_id,
7113 node_features: NodeFeatures::empty(),
7114 short_channel_id: 43,
7115 channel_features: ChannelFeatures::empty(),
7117 cltv_expiry_delta: 0,
7118 maybe_announced_channel: false,
7121 blinded_tail: Some(BlindedTail {
7122 hops: blinded_path.blinded_hops,
7123 blinding_point: blinded_path.blinding_point,
7124 excess_final_cltv_expiry_delta: 0,
7125 final_value_msat: 200,
7127 }], route_params: None};
7129 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7130 let (_, network_graph, _, _, _) = build_line_graph();
7131 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7132 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7133 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7137 fn simple_blinded_route_hints() {
7138 do_simple_blinded_route_hints(1);
7139 do_simple_blinded_route_hints(2);
7140 do_simple_blinded_route_hints(3);
7143 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7144 // Check that we can generate a route to a blinded path with the expected hops.
7145 let (secp_ctx, network, _, _, logger) = build_graph();
7146 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7147 let network_graph = network.read_only();
7149 let scorer = ln_test_utils::TestScorer::new();
7150 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7151 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7153 let mut blinded_path = BlindedPath {
7154 introduction_node_id: nodes[2],
7155 blinding_point: ln_test_utils::pubkey(42),
7156 blinded_hops: Vec::with_capacity(num_blinded_hops),
7158 for i in 0..num_blinded_hops {
7159 blinded_path.blinded_hops.push(
7160 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7163 let blinded_payinfo = BlindedPayInfo {
7165 fee_proportional_millionths: 500,
7166 htlc_minimum_msat: 1000,
7167 htlc_maximum_msat: 100_000_000,
7168 cltv_expiry_delta: 15,
7169 features: BlindedHopFeatures::empty(),
7172 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7173 let route_params = RouteParameters::from_payment_params_and_value(
7174 payment_params, 1001);
7175 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7176 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7177 assert_eq!(route.paths.len(), 1);
7178 assert_eq!(route.paths[0].hops.len(), 2);
7180 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7181 assert_eq!(tail.hops, blinded_path.blinded_hops);
7182 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7183 assert_eq!(tail.final_value_msat, 1001);
7185 let final_hop = route.paths[0].hops.last().unwrap();
7186 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7187 if tail.hops.len() > 1 {
7188 assert_eq!(final_hop.fee_msat,
7189 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7190 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7192 assert_eq!(final_hop.fee_msat, 0);
7193 assert_eq!(final_hop.cltv_expiry_delta, 0);
7198 fn blinded_path_routing_errors() {
7199 // Check that we can generate a route to a blinded path with the expected hops.
7200 let (secp_ctx, network, _, _, logger) = build_graph();
7201 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7202 let network_graph = network.read_only();
7204 let scorer = ln_test_utils::TestScorer::new();
7205 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7206 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7208 let mut invalid_blinded_path = BlindedPath {
7209 introduction_node_id: nodes[2],
7210 blinding_point: ln_test_utils::pubkey(42),
7212 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7215 let blinded_payinfo = BlindedPayInfo {
7217 fee_proportional_millionths: 500,
7218 htlc_minimum_msat: 1000,
7219 htlc_maximum_msat: 100_000_000,
7220 cltv_expiry_delta: 15,
7221 features: BlindedHopFeatures::empty(),
7224 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7225 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7226 let payment_params = PaymentParameters::blinded(vec![
7227 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7228 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7229 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7230 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7231 &scorer, &Default::default(), &random_seed_bytes)
7233 Err(LightningError { err, .. }) => {
7234 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7236 _ => panic!("Expected error")
7239 invalid_blinded_path.introduction_node_id = our_id;
7240 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7241 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7242 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7243 &Default::default(), &random_seed_bytes)
7245 Err(LightningError { err, .. }) => {
7246 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7248 _ => panic!("Expected error")
7251 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7252 invalid_blinded_path.blinded_hops.clear();
7253 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7254 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7255 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7256 &Default::default(), &random_seed_bytes)
7258 Err(LightningError { err, .. }) => {
7259 assert_eq!(err, "0-hop blinded path provided");
7261 _ => panic!("Expected error")
7266 fn matching_intro_node_paths_provided() {
7267 // Check that if multiple blinded paths with the same intro node are provided in payment
7268 // parameters, we'll return the correct paths in the resulting MPP route.
7269 let (secp_ctx, network, _, _, logger) = build_graph();
7270 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7271 let network_graph = network.read_only();
7273 let scorer = ln_test_utils::TestScorer::new();
7274 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7275 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7276 let config = UserConfig::default();
7278 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7279 let blinded_path_1 = BlindedPath {
7280 introduction_node_id: nodes[2],
7281 blinding_point: ln_test_utils::pubkey(42),
7283 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7284 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7287 let blinded_payinfo_1 = BlindedPayInfo {
7289 fee_proportional_millionths: 0,
7290 htlc_minimum_msat: 0,
7291 htlc_maximum_msat: 30_000,
7292 cltv_expiry_delta: 0,
7293 features: BlindedHopFeatures::empty(),
7296 let mut blinded_path_2 = blinded_path_1.clone();
7297 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7298 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7299 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7301 let blinded_hints = vec![
7302 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7303 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7305 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7306 .with_bolt12_features(bolt12_features).unwrap();
7308 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7309 route_params.max_total_routing_fee_msat = Some(100_000);
7310 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7311 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7312 assert_eq!(route.paths.len(), 2);
7313 let mut total_amount_paid_msat = 0;
7314 for path in route.paths.into_iter() {
7315 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7316 if let Some(bt) = &path.blinded_tail {
7317 assert_eq!(bt.blinding_point,
7318 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7319 .map(|(_, bp)| bp.blinding_point).unwrap());
7320 } else { panic!(); }
7321 total_amount_paid_msat += path.final_value_msat();
7323 assert_eq!(total_amount_paid_msat, 100_000);
7327 fn direct_to_intro_node() {
7328 // This previously caused a debug panic in the router when asserting
7329 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7330 // direct channels we failed to account for the fee charged for use of the blinded path.
7333 // node0 -1(1)2 - node1
7334 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7335 // doesn't account for the blinded path fee.
7337 let secp_ctx = Secp256k1::new();
7338 let logger = Arc::new(ln_test_utils::TestLogger::new());
7339 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7340 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7341 let scorer = ln_test_utils::TestScorer::new();
7342 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7343 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7345 let amt_msat = 10_000_000;
7346 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7347 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7348 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7349 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7350 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7351 short_channel_id: 1,
7354 cltv_expiry_delta: 42,
7355 htlc_minimum_msat: 1_000,
7356 htlc_maximum_msat: 10_000_000,
7358 fee_proportional_millionths: 0,
7359 excess_data: Vec::new()
7361 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7362 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7363 short_channel_id: 1,
7366 cltv_expiry_delta: 42,
7367 htlc_minimum_msat: 1_000,
7368 htlc_maximum_msat: 10_000_000,
7370 fee_proportional_millionths: 0,
7371 excess_data: Vec::new()
7373 let first_hops = vec![
7374 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7376 let blinded_path = BlindedPath {
7377 introduction_node_id: nodes[1],
7378 blinding_point: ln_test_utils::pubkey(42),
7380 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7381 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7384 let blinded_payinfo = BlindedPayInfo {
7385 fee_base_msat: 1000,
7386 fee_proportional_millionths: 0,
7387 htlc_minimum_msat: 1000,
7388 htlc_maximum_msat: MAX_VALUE_MSAT,
7389 cltv_expiry_delta: 0,
7390 features: BlindedHopFeatures::empty(),
7392 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7394 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7396 let netgraph = network_graph.read_only();
7397 let route_params = RouteParameters::from_payment_params_and_value(
7398 payment_params.clone(), amt_msat);
7399 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7400 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7401 &Default::default(), &random_seed_bytes) {
7402 assert_eq!(err, "Failed to find a path to the given destination");
7403 } else { panic!("Expected error") }
7405 // Sending an exact amount accounting for the blinded path fee works.
7406 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7407 let route_params = RouteParameters::from_payment_params_and_value(
7408 payment_params, amt_minus_blinded_path_fee);
7409 let route = get_route(&nodes[0], &route_params, &netgraph,
7410 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7411 &Default::default(), &random_seed_bytes).unwrap();
7412 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7413 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7417 fn direct_to_matching_intro_nodes() {
7418 // This previously caused us to enter `unreachable` code in the following situation:
7419 // 1. We add a route candidate for intro_node contributing a high amount
7420 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7421 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7422 // amount, and update our route candidate for intro_node for the lower amount
7423 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7424 // lower contribution amount, but fail (this was previously caused by failure to account for
7425 // blinded path fees when adding first_hop<>intro_node candidates)
7426 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7427 // candidate still thinks its path is contributing the original higher amount. This caused us
7428 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7430 let secp_ctx = Secp256k1::new();
7431 let logger = Arc::new(ln_test_utils::TestLogger::new());
7432 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7433 let scorer = ln_test_utils::TestScorer::new();
7434 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7435 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7436 let config = UserConfig::default();
7438 // Values are taken from the fuzz input that uncovered this panic.
7439 let amt_msat = 21_7020_5185_1403_2640;
7440 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7441 let first_hops = vec![
7442 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7443 18446744073709551615)];
7445 let blinded_path = BlindedPath {
7446 introduction_node_id: nodes[1],
7447 blinding_point: ln_test_utils::pubkey(42),
7449 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7450 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7453 let blinded_payinfo = BlindedPayInfo {
7454 fee_base_msat: 5046_2720,
7455 fee_proportional_millionths: 0,
7456 htlc_minimum_msat: 4503_5996_2737_0496,
7457 htlc_maximum_msat: 45_0359_9627_3704_9600,
7458 cltv_expiry_delta: 0,
7459 features: BlindedHopFeatures::empty(),
7461 let mut blinded_hints = vec![
7462 (blinded_payinfo.clone(), blinded_path.clone()),
7463 (blinded_payinfo.clone(), blinded_path.clone()),
7465 blinded_hints[1].0.fee_base_msat = 419_4304;
7466 blinded_hints[1].0.fee_proportional_millionths = 257;
7467 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7468 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7469 blinded_hints[1].0.cltv_expiry_delta = 0;
7471 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7472 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7473 .with_bolt12_features(bolt12_features).unwrap();
7475 let netgraph = network_graph.read_only();
7476 let route_params = RouteParameters::from_payment_params_and_value(
7477 payment_params, amt_msat);
7478 let route = get_route(&nodes[0], &route_params, &netgraph,
7479 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7480 &Default::default(), &random_seed_bytes).unwrap();
7481 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7482 assert_eq!(route.get_total_amount(), amt_msat);
7486 fn we_are_intro_node_candidate_hops() {
7487 // This previously led to a panic in the router because we'd generate a Path with only a
7488 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7489 // where the origin node is the intro node. We now fully disallow considering candidate hops
7490 // where the origin node is the intro node.
7491 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7492 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7493 let scorer = ln_test_utils::TestScorer::new();
7494 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7495 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7496 let config = UserConfig::default();
7498 // Values are taken from the fuzz input that uncovered this panic.
7499 let amt_msat = 21_7020_5185_1423_0019;
7501 let blinded_path = BlindedPath {
7502 introduction_node_id: our_id,
7503 blinding_point: ln_test_utils::pubkey(42),
7505 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7506 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7509 let blinded_payinfo = BlindedPayInfo {
7510 fee_base_msat: 5052_9027,
7511 fee_proportional_millionths: 0,
7512 htlc_minimum_msat: 21_7020_5185_1423_0019,
7513 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7514 cltv_expiry_delta: 0,
7515 features: BlindedHopFeatures::empty(),
7517 let mut blinded_hints = vec![
7518 (blinded_payinfo.clone(), blinded_path.clone()),
7519 (blinded_payinfo.clone(), blinded_path.clone()),
7521 blinded_hints[1].1.introduction_node_id = nodes[6];
7523 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7524 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7525 .with_bolt12_features(bolt12_features.clone()).unwrap();
7527 let netgraph = network_graph.read_only();
7528 let route_params = RouteParameters::from_payment_params_and_value(
7529 payment_params, amt_msat);
7530 if let Err(LightningError { err, .. }) = get_route(
7531 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7533 assert_eq!(err, "Failed to find a path to the given destination");
7538 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7539 // This previously led to a debug panic in the router because we'd find an invalid Path with
7540 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7541 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7542 // the payment, when it was intended to only include the final value of the payment.
7543 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7544 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7545 let scorer = ln_test_utils::TestScorer::new();
7546 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7547 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7548 let config = UserConfig::default();
7550 // Values are taken from the fuzz input that uncovered this panic.
7551 let amt_msat = 21_7020_5185_1423_0019;
7553 let blinded_path = BlindedPath {
7554 introduction_node_id: our_id,
7555 blinding_point: ln_test_utils::pubkey(42),
7557 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7558 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7561 let blinded_payinfo = BlindedPayInfo {
7562 fee_base_msat: 10_4425_1395,
7563 fee_proportional_millionths: 0,
7564 htlc_minimum_msat: 21_7301_9934_9094_0931,
7565 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7566 cltv_expiry_delta: 0,
7567 features: BlindedHopFeatures::empty(),
7569 let mut blinded_hints = vec![
7570 (blinded_payinfo.clone(), blinded_path.clone()),
7571 (blinded_payinfo.clone(), blinded_path.clone()),
7572 (blinded_payinfo.clone(), blinded_path.clone()),
7574 blinded_hints[1].0.fee_base_msat = 5052_9027;
7575 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7576 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7578 blinded_hints[2].1.introduction_node_id = nodes[6];
7580 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7581 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7582 .with_bolt12_features(bolt12_features.clone()).unwrap();
7584 let netgraph = network_graph.read_only();
7585 let route_params = RouteParameters::from_payment_params_and_value(
7586 payment_params, amt_msat);
7587 if let Err(LightningError { err, .. }) = get_route(
7588 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7590 assert_eq!(err, "Failed to find a path to the given destination");
7595 fn min_htlc_overpay_violates_max_htlc() {
7596 do_min_htlc_overpay_violates_max_htlc(true);
7597 do_min_htlc_overpay_violates_max_htlc(false);
7599 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7600 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7601 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7602 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7603 // that the used liquidity for a hop was less than its available liquidity limit.
7604 let secp_ctx = Secp256k1::new();
7605 let logger = Arc::new(ln_test_utils::TestLogger::new());
7606 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7607 let scorer = ln_test_utils::TestScorer::new();
7608 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7609 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7610 let config = UserConfig::default();
7612 // Values are taken from the fuzz input that uncovered this panic.
7613 let amt_msat = 7_4009_8048;
7614 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7615 let first_hop_outbound_capacity = 2_7345_2000;
7616 let first_hops = vec![get_channel_details(
7617 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7618 first_hop_outbound_capacity
7621 let base_fee = 1_6778_3453;
7622 let htlc_min = 2_5165_8240;
7623 let payment_params = if blinded_payee {
7624 let blinded_path = BlindedPath {
7625 introduction_node_id: nodes[0],
7626 blinding_point: ln_test_utils::pubkey(42),
7628 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7629 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7632 let blinded_payinfo = BlindedPayInfo {
7633 fee_base_msat: base_fee,
7634 fee_proportional_millionths: 0,
7635 htlc_minimum_msat: htlc_min,
7636 htlc_maximum_msat: htlc_min * 1000,
7637 cltv_expiry_delta: 0,
7638 features: BlindedHopFeatures::empty(),
7640 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7641 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7642 .with_bolt12_features(bolt12_features.clone()).unwrap()
7644 let route_hint = RouteHint(vec![RouteHintHop {
7645 src_node_id: nodes[0],
7646 short_channel_id: 42,
7648 base_msat: base_fee,
7649 proportional_millionths: 0,
7651 cltv_expiry_delta: 10,
7652 htlc_minimum_msat: Some(htlc_min),
7653 htlc_maximum_msat: None,
7656 PaymentParameters::from_node_id(nodes[1], 42)
7657 .with_route_hints(vec![route_hint]).unwrap()
7658 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7661 let netgraph = network_graph.read_only();
7662 let route_params = RouteParameters::from_payment_params_and_value(
7663 payment_params, amt_msat);
7664 if let Err(LightningError { err, .. }) = get_route(
7665 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7666 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7668 assert_eq!(err, "Failed to find a path to the given destination");
7673 fn previously_used_liquidity_violates_max_htlc() {
7674 do_previously_used_liquidity_violates_max_htlc(true);
7675 do_previously_used_liquidity_violates_max_htlc(false);
7678 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7679 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7680 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7681 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7682 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7683 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7684 let secp_ctx = Secp256k1::new();
7685 let logger = Arc::new(ln_test_utils::TestLogger::new());
7686 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7687 let scorer = ln_test_utils::TestScorer::new();
7688 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7689 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7690 let config = UserConfig::default();
7692 // Values are taken from the fuzz input that uncovered this panic.
7693 let amt_msat = 52_4288;
7694 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7695 let first_hops = vec![get_channel_details(
7696 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7697 ), get_channel_details(
7698 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7701 let base_fees = [0, 425_9840, 0, 0];
7702 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7703 let payment_params = if blinded_payee {
7704 let blinded_path = BlindedPath {
7705 introduction_node_id: nodes[0],
7706 blinding_point: ln_test_utils::pubkey(42),
7708 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7709 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7712 let mut blinded_hints = Vec::new();
7713 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7714 blinded_hints.push((BlindedPayInfo {
7715 fee_base_msat: *base_fee,
7716 fee_proportional_millionths: 0,
7717 htlc_minimum_msat: *htlc_min,
7718 htlc_maximum_msat: htlc_min * 100,
7719 cltv_expiry_delta: 10,
7720 features: BlindedHopFeatures::empty(),
7721 }, blinded_path.clone()));
7723 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7724 PaymentParameters::blinded(blinded_hints.clone())
7725 .with_bolt12_features(bolt12_features.clone()).unwrap()
7727 let mut route_hints = Vec::new();
7728 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7729 route_hints.push(RouteHint(vec![RouteHintHop {
7730 src_node_id: nodes[0],
7731 short_channel_id: 42 + idx as u64,
7733 base_msat: *base_fee,
7734 proportional_millionths: 0,
7736 cltv_expiry_delta: 10,
7737 htlc_minimum_msat: Some(*htlc_min),
7738 htlc_maximum_msat: Some(htlc_min * 100),
7741 PaymentParameters::from_node_id(nodes[1], 42)
7742 .with_route_hints(route_hints).unwrap()
7743 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7746 let netgraph = network_graph.read_only();
7747 let route_params = RouteParameters::from_payment_params_and_value(
7748 payment_params, amt_msat);
7750 let route = get_route(
7751 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7752 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7754 assert_eq!(route.paths.len(), 1);
7755 assert_eq!(route.get_total_amount(), amt_msat);
7759 fn candidate_path_min() {
7760 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7761 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7762 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7763 // would add a connecting first_hop node that did not have enough contribution amount, leading
7764 // to a debug panic upon invalid path construction.
7765 let secp_ctx = Secp256k1::new();
7766 let logger = Arc::new(ln_test_utils::TestLogger::new());
7767 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7768 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7769 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7770 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7771 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7772 let config = UserConfig::default();
7774 // Values are taken from the fuzz input that uncovered this panic.
7775 let amt_msat = 7_4009_8048;
7776 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7777 let first_hops = vec![get_channel_details(
7778 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7781 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7782 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7783 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7784 short_channel_id: 6,
7787 cltv_expiry_delta: (6 << 4) | 0,
7788 htlc_minimum_msat: 0,
7789 htlc_maximum_msat: MAX_VALUE_MSAT,
7791 fee_proportional_millionths: 0,
7792 excess_data: Vec::new()
7794 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
7796 let htlc_min = 2_5165_8240;
7797 let blinded_hints = vec![
7799 fee_base_msat: 1_6778_3453,
7800 fee_proportional_millionths: 0,
7801 htlc_minimum_msat: htlc_min,
7802 htlc_maximum_msat: htlc_min * 100,
7803 cltv_expiry_delta: 10,
7804 features: BlindedHopFeatures::empty(),
7806 introduction_node_id: nodes[0],
7807 blinding_point: ln_test_utils::pubkey(42),
7809 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7810 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7814 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7815 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7816 .with_bolt12_features(bolt12_features.clone()).unwrap();
7817 let route_params = RouteParameters::from_payment_params_and_value(
7818 payment_params, amt_msat);
7819 let netgraph = network_graph.read_only();
7821 if let Err(LightningError { err, .. }) = get_route(
7822 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7823 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7826 assert_eq!(err, "Failed to find a path to the given destination");
7831 fn path_contribution_includes_min_htlc_overpay() {
7832 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
7833 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
7834 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
7835 // selection, both tested here.
7836 let secp_ctx = Secp256k1::new();
7837 let logger = Arc::new(ln_test_utils::TestLogger::new());
7838 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7839 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7840 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7841 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7842 let config = UserConfig::default();
7844 // Values are taken from the fuzz input that uncovered this panic.
7845 let amt_msat = 562_0000;
7846 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7847 let first_hops = vec![
7848 get_channel_details(
7849 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
7853 let htlc_mins = [49_0000, 1125_0000];
7854 let payment_params = {
7855 let blinded_path = BlindedPath {
7856 introduction_node_id: nodes[0],
7857 blinding_point: ln_test_utils::pubkey(42),
7859 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7860 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7863 let mut blinded_hints = Vec::new();
7864 for htlc_min in htlc_mins.iter() {
7865 blinded_hints.push((BlindedPayInfo {
7867 fee_proportional_millionths: 0,
7868 htlc_minimum_msat: *htlc_min,
7869 htlc_maximum_msat: *htlc_min * 100,
7870 cltv_expiry_delta: 10,
7871 features: BlindedHopFeatures::empty(),
7872 }, blinded_path.clone()));
7874 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7875 PaymentParameters::blinded(blinded_hints.clone())
7876 .with_bolt12_features(bolt12_features.clone()).unwrap()
7879 let netgraph = network_graph.read_only();
7880 let route_params = RouteParameters::from_payment_params_and_value(
7881 payment_params, amt_msat);
7882 let route = get_route(
7883 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7884 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7887 assert_eq!(route.paths.len(), 1);
7888 assert_eq!(route.get_total_amount(), amt_msat);
7892 fn first_hop_preferred_over_hint() {
7893 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
7894 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
7895 let secp_ctx = Secp256k1::new();
7896 let logger = Arc::new(ln_test_utils::TestLogger::new());
7897 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7898 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7899 let scorer = ln_test_utils::TestScorer::new();
7900 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7901 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7902 let config = UserConfig::default();
7904 let amt_msat = 1_000_000;
7905 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
7907 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
7908 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7909 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
7910 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7911 short_channel_id: 1,
7914 cltv_expiry_delta: 42,
7915 htlc_minimum_msat: 1_000,
7916 htlc_maximum_msat: 10_000_000,
7918 fee_proportional_millionths: 0,
7919 excess_data: Vec::new()
7921 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7922 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7923 short_channel_id: 1,
7926 cltv_expiry_delta: 42,
7927 htlc_minimum_msat: 1_000,
7928 htlc_maximum_msat: 10_000_000,
7930 fee_proportional_millionths: 0,
7931 excess_data: Vec::new()
7934 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7935 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
7936 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7937 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7938 short_channel_id: 2,
7941 cltv_expiry_delta: 42,
7942 htlc_minimum_msat: 1_000,
7943 htlc_maximum_msat: 10_000_000,
7945 fee_proportional_millionths: 0,
7946 excess_data: Vec::new()
7948 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7949 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7950 short_channel_id: 2,
7953 cltv_expiry_delta: 42,
7954 htlc_minimum_msat: 1_000,
7955 htlc_maximum_msat: 10_000_000,
7957 fee_proportional_millionths: 0,
7958 excess_data: Vec::new()
7961 let dest_node_id = nodes[2];
7963 let route_hint = RouteHint(vec![RouteHintHop {
7964 src_node_id: our_node_id,
7965 short_channel_id: 44,
7968 proportional_millionths: 0,
7970 cltv_expiry_delta: 10,
7971 htlc_minimum_msat: None,
7972 htlc_maximum_msat: Some(5_000_000),
7975 src_node_id: nodes[0],
7976 short_channel_id: 45,
7979 proportional_millionths: 0,
7981 cltv_expiry_delta: 10,
7982 htlc_minimum_msat: None,
7983 htlc_maximum_msat: None,
7986 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7987 .with_route_hints(vec![route_hint]).unwrap()
7988 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
7989 let route_params = RouteParameters::from_payment_params_and_value(
7990 payment_params, amt_msat);
7992 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
7994 let first_hop = get_channel_details(Some(1), nodes[0],
7995 channelmanager::provided_init_features(&config), 999_999);
7996 let first_hops = vec![first_hop];
7998 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
7999 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8000 &Default::default(), &random_seed_bytes).unwrap();
8001 assert_eq!(route.paths.len(), 1);
8002 assert_eq!(route.get_total_amount(), amt_msat);
8003 assert_eq!(route.paths[0].hops.len(), 2);
8004 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8005 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8006 assert_eq!(route.get_total_fees(), 123);
8008 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8009 // for a first hop channel.
8010 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8011 first_hop.outbound_scid_alias = Some(44);
8012 let first_hops = vec![first_hop];
8014 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8015 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8016 &Default::default(), &random_seed_bytes);
8017 assert!(route_res.is_err());
8019 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8020 // use the cheaper second hop of the route hint.
8021 let mut first_hop = get_channel_details(Some(1), nodes[0],
8022 channelmanager::provided_init_features(&config), 10_000_000);
8023 first_hop.outbound_scid_alias = Some(44);
8024 let first_hops = vec![first_hop];
8026 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8027 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8028 &Default::default(), &random_seed_bytes).unwrap();
8029 assert_eq!(route.paths.len(), 1);
8030 assert_eq!(route.get_total_amount(), amt_msat);
8031 assert_eq!(route.paths[0].hops.len(), 2);
8032 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8033 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8034 assert_eq!(route.get_total_fees(), 123);
8038 fn allow_us_being_first_hint() {
8039 // Check that we consider a route hint even if we are the src of the first hop.
8040 let secp_ctx = Secp256k1::new();
8041 let logger = Arc::new(ln_test_utils::TestLogger::new());
8042 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8043 let scorer = ln_test_utils::TestScorer::new();
8044 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8045 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8046 let config = UserConfig::default();
8048 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8050 let amt_msat = 1_000_000;
8051 let dest_node_id = nodes[1];
8053 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8054 let first_hops = vec![first_hop];
8056 let route_hint = RouteHint(vec![RouteHintHop {
8057 src_node_id: our_node_id,
8058 short_channel_id: 44,
8061 proportional_millionths: 0,
8063 cltv_expiry_delta: 10,
8064 htlc_minimum_msat: None,
8065 htlc_maximum_msat: None,
8068 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8069 .with_route_hints(vec![route_hint]).unwrap()
8070 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8072 let route_params = RouteParameters::from_payment_params_and_value(
8073 payment_params, amt_msat);
8076 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8077 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8078 &Default::default(), &random_seed_bytes).unwrap();
8080 assert_eq!(route.paths.len(), 1);
8081 assert_eq!(route.get_total_amount(), amt_msat);
8082 assert_eq!(route.get_total_fees(), 0);
8083 assert_eq!(route.paths[0].hops.len(), 1);
8085 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8089 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8090 pub(crate) mod bench_utils {
8094 use bitcoin::hashes::Hash;
8095 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8097 use crate::chain::transaction::OutPoint;
8098 use crate::routing::scoring::ScoreUpdate;
8099 use crate::sign::{EntropySource, KeysManager};
8100 use crate::ln::ChannelId;
8101 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8102 use crate::ln::features::Bolt11InvoiceFeatures;
8103 use crate::routing::gossip::NetworkGraph;
8104 use crate::util::config::UserConfig;
8105 use crate::util::ser::ReadableArgs;
8106 use crate::util::test_utils::TestLogger;
8108 /// Tries to open a network graph file, or panics with a URL to fetch it.
8109 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8110 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8111 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8112 .or_else(|_| { // Fall back to guessing based on the binary location
8113 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8114 let mut path = std::env::current_exe().unwrap();
8115 path.pop(); // lightning-...
8117 path.pop(); // debug
8118 path.pop(); // target
8119 path.push("lightning");
8120 path.push("net_graph-2023-01-18.bin");
8123 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8124 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8125 let mut path = std::env::current_exe().unwrap();
8126 path.pop(); // bench...
8128 path.pop(); // debug
8129 path.pop(); // target
8130 path.pop(); // bench
8131 path.push("lightning");
8132 path.push("net_graph-2023-01-18.bin");
8135 .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");
8136 #[cfg(require_route_graph_test)]
8137 return Ok(res.unwrap());
8138 #[cfg(not(require_route_graph_test))]
8142 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8143 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8146 pub(crate) fn payer_pubkey() -> PublicKey {
8147 let secp_ctx = Secp256k1::new();
8148 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8152 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8154 channel_id: ChannelId::new_zero(),
8155 counterparty: ChannelCounterparty {
8156 features: channelmanager::provided_init_features(&UserConfig::default()),
8158 unspendable_punishment_reserve: 0,
8159 forwarding_info: None,
8160 outbound_htlc_minimum_msat: None,
8161 outbound_htlc_maximum_msat: None,
8163 funding_txo: Some(OutPoint {
8164 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8167 short_channel_id: Some(1),
8168 inbound_scid_alias: None,
8169 outbound_scid_alias: None,
8170 channel_value_satoshis: 10_000_000_000,
8172 balance_msat: 10_000_000_000,
8173 outbound_capacity_msat: 10_000_000_000,
8174 next_outbound_htlc_minimum_msat: 0,
8175 next_outbound_htlc_limit_msat: 10_000_000_000,
8176 inbound_capacity_msat: 0,
8177 unspendable_punishment_reserve: None,
8178 confirmations_required: None,
8179 confirmations: None,
8180 force_close_spend_delay: None,
8182 is_channel_ready: true,
8185 inbound_htlc_minimum_msat: None,
8186 inbound_htlc_maximum_msat: None,
8188 feerate_sat_per_1000_weight: None,
8189 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8193 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8194 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8195 starting_amount: u64, route_count: usize,
8196 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8197 let payer = payer_pubkey();
8198 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8199 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8201 let nodes = graph.read_only().nodes().clone();
8202 let mut route_endpoints = Vec::new();
8203 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8204 // with some routes we picked being un-routable.
8205 for _ in 0..route_count * 3 / 2 {
8207 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8208 let src = PublicKey::from_slice(nodes.unordered_keys()
8209 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8210 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8211 let dst = PublicKey::from_slice(nodes.unordered_keys()
8212 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8213 let params = PaymentParameters::from_node_id(dst, 42)
8214 .with_bolt11_features(features.clone()).unwrap();
8215 let first_hop = first_hop(src);
8216 let amt_msat = starting_amount + seed % 1_000_000;
8217 let route_params = RouteParameters::from_payment_params_and_value(
8218 params.clone(), amt_msat);
8220 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8221 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8223 // ...and seed the scorer with success and failure data...
8224 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8225 let mut score_amt = seed % 1_000_000_000;
8227 // Generate fail/success paths for a wider range of potential amounts with
8228 // MPP enabled to give us a chance to apply penalties for more potential
8230 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8231 let params = PaymentParameters::from_node_id(dst, 42)
8232 .with_bolt11_features(mpp_features).unwrap();
8233 let route_params = RouteParameters::from_payment_params_and_value(
8234 params.clone(), score_amt);
8235 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8236 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8237 &random_seed_bytes);
8238 if let Ok(route) = route_res {
8239 for path in route.paths {
8240 if seed & 0x80 == 0 {
8241 scorer.payment_path_successful(&path);
8243 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8244 scorer.payment_path_failed(&path, short_channel_id);
8246 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8250 // If we couldn't find a path with a higer amount, reduce and try again.
8254 route_endpoints.push((first_hop, params, amt_msat));
8260 // Because we've changed channel scores, it's possible we'll take different routes to the
8261 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8262 // requires a too-high CLTV delta.
8263 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8264 let route_params = RouteParameters::from_payment_params_and_value(
8265 params.clone(), *amt_msat);
8266 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8267 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8269 route_endpoints.truncate(route_count);
8270 assert_eq!(route_endpoints.len(), route_count);
8278 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8279 use crate::sign::{EntropySource, KeysManager};
8280 use crate::ln::channelmanager;
8281 use crate::ln::features::Bolt11InvoiceFeatures;
8282 use crate::routing::gossip::NetworkGraph;
8283 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8284 use crate::util::config::UserConfig;
8285 use crate::util::logger::{Logger, Record};
8286 use crate::util::test_utils::TestLogger;
8288 use criterion::Criterion;
8290 struct DummyLogger {}
8291 impl Logger for DummyLogger {
8292 fn log(&self, _record: Record) {}
8295 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8296 let logger = TestLogger::new();
8297 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8298 let scorer = FixedPenaltyScorer::with_penalty(0);
8299 generate_routes(bench, &network_graph, scorer, &Default::default(),
8300 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8303 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8304 let logger = TestLogger::new();
8305 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8306 let scorer = FixedPenaltyScorer::with_penalty(0);
8307 generate_routes(bench, &network_graph, scorer, &Default::default(),
8308 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8309 "generate_mpp_routes_with_zero_penalty_scorer");
8312 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8313 let logger = TestLogger::new();
8314 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8315 let params = ProbabilisticScoringFeeParameters::default();
8316 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8317 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8318 "generate_routes_with_probabilistic_scorer");
8321 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8322 let logger = TestLogger::new();
8323 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8324 let params = ProbabilisticScoringFeeParameters::default();
8325 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8326 generate_routes(bench, &network_graph, scorer, ¶ms,
8327 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8328 "generate_mpp_routes_with_probabilistic_scorer");
8331 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8332 let logger = TestLogger::new();
8333 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8334 let params = ProbabilisticScoringFeeParameters::default();
8335 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8336 generate_routes(bench, &network_graph, scorer, ¶ms,
8337 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8338 "generate_large_mpp_routes_with_probabilistic_scorer");
8341 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8342 let logger = TestLogger::new();
8343 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8344 let mut params = ProbabilisticScoringFeeParameters::default();
8345 params.linear_success_probability = false;
8346 let scorer = ProbabilisticScorer::new(
8347 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8348 generate_routes(bench, &network_graph, scorer, ¶ms,
8349 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8350 "generate_routes_with_nonlinear_probabilistic_scorer");
8353 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8354 let logger = TestLogger::new();
8355 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8356 let mut params = ProbabilisticScoringFeeParameters::default();
8357 params.linear_success_probability = false;
8358 let scorer = ProbabilisticScorer::new(
8359 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8360 generate_routes(bench, &network_graph, scorer, ¶ms,
8361 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8362 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8365 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8366 let logger = TestLogger::new();
8367 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8368 let mut params = ProbabilisticScoringFeeParameters::default();
8369 params.linear_success_probability = false;
8370 let scorer = ProbabilisticScorer::new(
8371 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8372 generate_routes(bench, &network_graph, scorer, ¶ms,
8373 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8374 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8377 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8378 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8379 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8380 bench_name: &'static str,
8382 let payer = bench_utils::payer_pubkey();
8383 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8384 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8386 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8387 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8389 // ...then benchmark finding paths between the nodes we learned.
8391 bench.bench_function(bench_name, |b| b.iter(|| {
8392 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8393 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8394 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8395 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());