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.
1023 payer_node_id: &'a NodeId,
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: &'a 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.
1104 fn short_channel_id(&self) -> Option<u64> {
1106 CandidateRouteHop::FirstHop { details, .. } => details.get_outbound_payment_scid(),
1107 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1108 CandidateRouteHop::PrivateHop { hint, .. } => Some(hint.short_channel_id),
1109 CandidateRouteHop::Blinded { .. } => None,
1110 CandidateRouteHop::OneHopBlinded { .. } => None,
1114 /// Returns the globally unique short channel ID for this hop, if one is known.
1116 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1117 /// from the public network graph), and thus the short channel ID we have for this channel is
1118 /// globally unique and identifies this channel in a global namespace.
1120 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1122 CandidateRouteHop::FirstHop { details, .. } => if details.is_public { details.short_channel_id } else { None },
1123 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1124 CandidateRouteHop::PrivateHop { .. } => None,
1125 CandidateRouteHop::Blinded { .. } => None,
1126 CandidateRouteHop::OneHopBlinded { .. } => None,
1130 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1131 fn features(&self) -> ChannelFeatures {
1133 CandidateRouteHop::FirstHop { details, .. } => details.counterparty.features.to_context(),
1134 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1135 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1136 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1137 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1141 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1142 /// next-hop for an HTLC taking this hop.
1144 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1145 /// next-hop goes on chain with a payment preimage.
1147 pub fn cltv_expiry_delta(&self) -> u32 {
1149 CandidateRouteHop::FirstHop { .. } => 0,
1150 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1151 CandidateRouteHop::PrivateHop { hint, .. } => hint.cltv_expiry_delta as u32,
1152 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1153 CandidateRouteHop::OneHopBlinded { .. } => 0,
1157 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1159 pub fn htlc_minimum_msat(&self) -> u64 {
1161 CandidateRouteHop::FirstHop { details, .. } => details.next_outbound_htlc_minimum_msat,
1162 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1163 CandidateRouteHop::PrivateHop { hint, .. } => hint.htlc_minimum_msat.unwrap_or(0),
1164 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1165 CandidateRouteHop::OneHopBlinded { .. } => 0,
1169 /// Returns the fees that must be paid to route an HTLC over this channel.
1171 pub fn fees(&self) -> RoutingFees {
1173 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1174 base_msat: 0, proportional_millionths: 0,
1176 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1177 CandidateRouteHop::PrivateHop { hint, .. } => hint.fees,
1178 CandidateRouteHop::Blinded { hint, .. } => {
1180 base_msat: hint.0.fee_base_msat,
1181 proportional_millionths: hint.0.fee_proportional_millionths
1184 CandidateRouteHop::OneHopBlinded { .. } =>
1185 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1189 /// Fetch the effective capacity of this hop.
1191 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1193 fn effective_capacity(&self) -> EffectiveCapacity {
1195 CandidateRouteHop::FirstHop { details, .. } => EffectiveCapacity::ExactLiquidity {
1196 liquidity_msat: details.next_outbound_htlc_limit_msat,
1198 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1199 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. } =>
1200 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1201 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. } =>
1202 EffectiveCapacity::Infinite,
1203 CandidateRouteHop::Blinded { hint, .. } =>
1204 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1205 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1209 /// Returns an ID describing the given hop.
1211 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1213 fn id(&self) -> CandidateHopId {
1215 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1216 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1217 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1220 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1222 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1228 /// Returns the source node id of current hop.
1230 /// Source node id refers to the node forwarding the HTLC through this hop.
1232 /// For [`Self::FirstHop`] we return payer's node id.
1234 pub fn source(&self) -> NodeId {
1236 CandidateRouteHop::FirstHop { payer_node_id, .. } => **payer_node_id,
1237 CandidateRouteHop::PublicHop { info, .. } => *info.source(),
1238 CandidateRouteHop::PrivateHop { hint, .. } => hint.src_node_id.into(),
1239 CandidateRouteHop::Blinded { hint, .. } => hint.1.introduction_node_id.into(),
1240 CandidateRouteHop::OneHopBlinded { hint, .. } => hint.1.introduction_node_id.into(),
1243 /// Returns the target node id of this hop, if known.
1245 /// Target node id refers to the node receiving the HTLC after this hop.
1247 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1248 /// path is unknown.
1250 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1251 /// and such a return value would be somewhat nonsensical.
1253 pub fn target(&self) -> Option<NodeId> {
1255 CandidateRouteHop::FirstHop { details, .. } => Some(details.counterparty.node_id.into()),
1256 CandidateRouteHop::PublicHop { info, .. } => Some(*info.target()),
1257 CandidateRouteHop::PrivateHop { target_node_id, .. } => Some(**target_node_id),
1258 CandidateRouteHop::Blinded { .. } => None,
1259 CandidateRouteHop::OneHopBlinded { .. } => None,
1264 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1266 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1268 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1269 /// isn't guaranteed to be unique at all.
1271 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1272 /// difficult-to-use API.
1273 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1274 enum CandidateHopId {
1275 /// Contains (scid, src_node_id < target_node_id)
1277 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1282 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1283 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1285 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1286 EffectiveCapacity::Infinite => u64::max_value(),
1287 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1288 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1289 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1290 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1291 // expected to have been generated from up-to-date capacity information.
1292 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1293 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1294 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1298 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1299 -> bool where I1::Item: PartialEq<I2::Item> {
1301 let a = iter_a.next();
1302 let b = iter_b.next();
1303 if a.is_none() && b.is_none() { return true; }
1304 if a.is_none() || b.is_none() { return false; }
1305 if a.unwrap().ne(&b.unwrap()) { return false; }
1309 /// It's useful to keep track of the hops associated with the fees required to use them,
1310 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1311 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1312 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1314 #[repr(C)] // Force fields to appear in the order we define them.
1315 struct PathBuildingHop<'a> {
1316 candidate: CandidateRouteHop<'a>,
1317 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1318 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1319 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1320 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1321 /// avoid processing them again.
1322 was_processed: bool,
1323 /// Used to compare channels when choosing the for routing.
1324 /// Includes paying for the use of a hop and the following hops, as well as
1325 /// an estimated cost of reaching this hop.
1326 /// Might get stale when fees are recomputed. Primarily for internal use.
1327 total_fee_msat: u64,
1328 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1329 /// walk and may be invalid thereafter.
1330 path_htlc_minimum_msat: u64,
1331 /// All penalties incurred from this channel on the way to the destination, as calculated using
1332 /// channel scoring.
1333 path_penalty_msat: u64,
1335 // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1336 // only place fields which are not hot there. Luckily, the next three fields are only read if
1337 // we end up on the selected path, and only in the final path layout phase, so we don't care
1338 // too much if reading them is slow.
1342 /// All the fees paid *after* this channel on the way to the destination
1343 next_hops_fee_msat: u64,
1344 /// Fee paid for the use of the current channel (see candidate.fees()).
1345 /// The value will be actually deducted from the counterparty balance on the previous link.
1346 hop_use_fee_msat: u64,
1348 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1349 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1350 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1351 // value_contribution_msat, which requires tracking it here. See comments below where it is
1352 // used for more info.
1353 value_contribution_msat: u64,
1356 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1357 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1358 // generally won't, because at least glibc's malloc will align to a nice, big, round
1359 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1361 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1364 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1366 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1368 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1369 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1370 let mut debug_struct = f.debug_struct("PathBuildingHop");
1372 .field("node_id", &self.candidate.target())
1373 .field("short_channel_id", &self.candidate.short_channel_id())
1374 .field("total_fee_msat", &self.total_fee_msat)
1375 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1376 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1377 .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)))
1378 .field("path_penalty_msat", &self.path_penalty_msat)
1379 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1380 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1381 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1382 let debug_struct = debug_struct
1383 .field("value_contribution_msat", &self.value_contribution_msat);
1384 debug_struct.finish()
1388 // Instantiated with a list of hops with correct data in them collected during path finding,
1389 // an instance of this struct should be further modified only via given methods.
1391 struct PaymentPath<'a> {
1392 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1395 impl<'a> PaymentPath<'a> {
1396 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1397 fn get_value_msat(&self) -> u64 {
1398 self.hops.last().unwrap().0.fee_msat
1401 fn get_path_penalty_msat(&self) -> u64 {
1402 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1405 fn get_total_fee_paid_msat(&self) -> u64 {
1406 if self.hops.len() < 1 {
1410 // Can't use next_hops_fee_msat because it gets outdated.
1411 for (i, (hop, _)) in self.hops.iter().enumerate() {
1412 if i != self.hops.len() - 1 {
1413 result += hop.fee_msat;
1419 fn get_cost_msat(&self) -> u64 {
1420 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1423 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1424 // to change fees may result in an inconsistency.
1426 // Sometimes we call this function right after constructing a path which is inconsistent in
1427 // that it the value being transferred has decreased while we were doing path finding, leading
1428 // to the fees being paid not lining up with the actual limits.
1430 // Note that this function is not aware of the available_liquidity limit, and thus does not
1431 // support increasing the value being transferred beyond what was selected during the initial
1434 // Returns the amount that this path contributes to the total payment value, which may be greater
1435 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1436 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1437 let mut extra_contribution_msat = 0;
1438 let mut total_fee_paid_msat = 0 as u64;
1439 for i in (0..self.hops.len()).rev() {
1440 let last_hop = i == self.hops.len() - 1;
1442 // For non-last-hop, this value will represent the fees paid on the current hop. It
1443 // will consist of the fees for the use of the next hop, and extra fees to match
1444 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1445 let mut cur_hop_fees_msat = 0;
1447 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1450 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1451 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1452 cur_hop.path_penalty_msat += extra_contribution_msat;
1453 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1454 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1455 // set it too high just to maliciously take more fees by exploiting this
1456 // match htlc_minimum_msat logic.
1457 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1458 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1459 // Note that there is a risk that *previous hops* (those closer to us, as we go
1460 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1462 // This might make us end up with a broken route, although this should be super-rare
1463 // in practice, both because of how healthy channels look like, and how we pick
1464 // channels in add_entry.
1465 // Also, this can't be exploited more heavily than *announce a free path and fail
1467 cur_hop_transferred_amount_msat += extra_fees_msat;
1469 // We remember and return the extra fees on the final hop to allow accounting for
1470 // them in the path's value contribution.
1472 extra_contribution_msat = extra_fees_msat;
1474 total_fee_paid_msat += extra_fees_msat;
1475 cur_hop_fees_msat += extra_fees_msat;
1480 // Final hop is a special case: it usually has just value_msat (by design), but also
1481 // it still could overpay for the htlc_minimum_msat.
1482 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1484 // Propagate updated fees for the use of the channels to one hop back, where they
1485 // will be actually paid (fee_msat). The last hop is handled above separately.
1486 cur_hop.fee_msat = cur_hop_fees_msat;
1489 // Fee for the use of the current hop which will be deducted on the previous hop.
1490 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1491 // this channel is free for us.
1493 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1494 cur_hop.hop_use_fee_msat = new_fee;
1495 total_fee_paid_msat += new_fee;
1497 // It should not be possible because this function is called only to reduce the
1498 // value. In that case, compute_fee was already called with the same fees for
1499 // larger amount and there was no overflow.
1504 value_msat + extra_contribution_msat
1509 /// Calculate the fees required to route the given amount over a channel with the given fees.
1510 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1511 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1512 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1516 /// Calculate the fees required to route the given amount over a channel with the given fees,
1517 /// saturating to [`u64::max_value`].
1518 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1519 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1520 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1521 .saturating_add(channel_fees.base_msat as u64)
1524 /// The default `features` we assume for a node in a route, when no `features` are known about that
1527 /// Default features are:
1528 /// * variable_length_onion_optional
1529 fn default_node_features() -> NodeFeatures {
1530 let mut features = NodeFeatures::empty();
1531 features.set_variable_length_onion_optional();
1535 struct LoggedPayeePubkey(Option<PublicKey>);
1536 impl fmt::Display for LoggedPayeePubkey {
1537 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1540 "payee node id ".fmt(f)?;
1544 "blinded payee".fmt(f)
1550 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1551 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1554 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1555 "blinded route hint with introduction node id ".fmt(f)?;
1556 hint.1.introduction_node_id.fmt(f)?;
1557 " and blinding point ".fmt(f)?;
1558 hint.1.blinding_point.fmt(f)
1560 CandidateRouteHop::FirstHop { .. } => {
1561 "first hop with SCID ".fmt(f)?;
1562 self.0.short_channel_id().unwrap().fmt(f)
1564 CandidateRouteHop::PrivateHop { .. } => {
1565 "route hint with SCID ".fmt(f)?;
1566 self.0.short_channel_id().unwrap().fmt(f)
1570 self.0.short_channel_id().unwrap().fmt(f)
1577 fn sort_first_hop_channels(
1578 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1579 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1581 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1582 // most like to use.
1584 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1585 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1588 // Second, because simply always sorting in descending order would always use our largest
1589 // available outbound capacity, needlessly fragmenting our available channel capacities,
1590 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1591 // which have enough, but not too much, capacity for the payment.
1593 // Available outbound balances factor in liquidity already reserved for previously found paths.
1594 channels.sort_unstable_by(|chan_a, chan_b| {
1595 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1596 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1597 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1598 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1599 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1600 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1601 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1602 // Sort in descending order
1603 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1605 // Sort in ascending order
1606 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1611 /// Finds a route from us (payer) to the given target node (payee).
1613 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1614 /// in the given [`RouteParameters::payment_params`].
1615 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1617 /// Private routing paths between a public node and the target may be included in the `payee` field
1618 /// of [`RouteParameters::payment_params`].
1620 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1621 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1622 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1624 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1625 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1626 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1630 /// Panics if first_hops contains channels without `short_channel_id`s;
1631 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1633 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1634 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1635 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1636 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1637 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1638 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1639 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1640 ) -> Result<Route, LightningError>
1641 where L::Target: Logger, GL::Target: Logger {
1642 let graph_lock = network_graph.read_only();
1643 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1644 scorer, score_params, random_seed_bytes)?;
1645 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1649 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1650 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1651 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1652 _random_seed_bytes: &[u8; 32]
1653 ) -> Result<Route, LightningError>
1654 where L::Target: Logger {
1656 let payment_params = &route_params.payment_params;
1657 let final_value_msat = route_params.final_value_msat;
1658 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1659 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1660 // so use a dummy id for this in the blinded case.
1661 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1662 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1663 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1664 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1665 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1667 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1668 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1670 if our_node_id == maybe_dummy_payee_node_id {
1671 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1674 if final_value_msat > MAX_VALUE_MSAT {
1675 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1678 if final_value_msat == 0 {
1679 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1682 match &payment_params.payee {
1683 Payee::Clear { route_hints, node_id, .. } => {
1684 for route in route_hints.iter() {
1685 for hop in &route.0 {
1686 if hop.src_node_id == *node_id {
1687 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1692 Payee::Blinded { route_hints, .. } => {
1693 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1694 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});
1696 for (_, blinded_path) in route_hints.iter() {
1697 if blinded_path.blinded_hops.len() == 0 {
1698 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1699 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1700 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1701 } else if blinded_path.blinded_hops.len() == 1 &&
1702 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1703 && p.introduction_node_id != blinded_path.introduction_node_id)
1705 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1710 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1711 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1712 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});
1715 // The general routing idea is the following:
1716 // 1. Fill first/last hops communicated by the caller.
1717 // 2. Attempt to construct a path from payer to payee for transferring
1718 // any ~sufficient (described later) value.
1719 // If succeed, remember which channels were used and how much liquidity they have available,
1720 // so that future paths don't rely on the same liquidity.
1721 // 3. Proceed to the next step if:
1722 // - we hit the recommended target value;
1723 // - OR if we could not construct a new path. Any next attempt will fail too.
1724 // Otherwise, repeat step 2.
1725 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1726 // (not recommended value).
1727 // 5. If yes, proceed. If not, fail routing.
1728 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1729 // transferred up to the transfer target value.
1730 // 7. Reduce the value of the last path until we are sending only the target value.
1731 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1732 // them so that we're not sending two HTLCs along the same path.
1734 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1735 // distance from the payee
1737 // We are not a faithful Dijkstra's implementation because we can change values which impact
1738 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1739 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1740 // the value we are currently attempting to send over a path, we simply reduce the value being
1741 // sent along the path for any hops after that channel. This may imply that later fees (which
1742 // we've already tabulated) are lower because a smaller value is passing through the channels
1743 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1744 // channels which were selected earlier (and which may still be used for other paths without a
1745 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1748 // One potentially problematic case for this algorithm would be if there are many
1749 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1750 // graph walking), we may never find a path which is not liquidity-limited and has lower
1751 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1752 // Because we only consider paths with at least 5% of the total value being sent, the damage
1753 // from such a case should be limited, however this could be further reduced in the future by
1754 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1755 // limits for the purposes of fee calculation.
1757 // Alternatively, we could store more detailed path information in the heap (targets, below)
1758 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1759 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1760 // and practically (as we would need to store dynamically-allocated path information in heap
1761 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1762 // results of such an algorithm would likely be biased towards lower-value paths.
1764 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1765 // outside of our current search value, running a path search more times to gather candidate
1766 // paths at different values. While this may be acceptable, further path searches may increase
1767 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1768 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1769 // the same time, remaining generic across different payment values.
1771 let network_channels = network_graph.channels();
1772 let network_nodes = network_graph.nodes();
1774 if payment_params.max_path_count == 0 {
1775 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1778 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1779 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1781 let allow_mpp = if payment_params.max_path_count == 1 {
1783 } else if payment_params.payee.supports_basic_mpp() {
1785 } else if let Some(payee) = payee_node_id_opt {
1786 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1787 |info| info.features.supports_basic_mpp()))
1790 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1792 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1793 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1794 if allow_mpp { "with" } else { "without" },
1795 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1796 max_total_routing_fee_msat);
1799 // Prepare the data we'll use for payee-to-payer search by
1800 // inserting first hops suggested by the caller as targets.
1801 // Our search will then attempt to reach them while traversing from the payee node.
1802 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1803 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1804 if let Some(hops) = first_hops {
1806 if chan.get_outbound_payment_scid().is_none() {
1807 panic!("first_hops should be filled in with usable channels, not pending ones");
1809 if chan.counterparty.node_id == *our_node_pubkey {
1810 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1813 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1814 .or_insert(Vec::new())
1817 if first_hop_targets.is_empty() {
1818 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1822 let mut private_hop_key_cache = HashMap::with_capacity(
1823 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
1826 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
1827 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
1828 // we'll need here and simply fetch them when routing.
1829 private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
1830 for route in payment_params.payee.unblinded_route_hints().iter() {
1831 for hop in route.0.iter() {
1832 private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
1836 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1837 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1838 // adding duplicate entries when we find a better path to a given node.
1839 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1841 // Map from node_id to information about the best current path to that node, including feerate
1843 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1845 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1846 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1847 // htlc_minimum with extra fees while still finding a cheaper path.
1848 let mut hit_minimum_limit;
1850 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1851 // We start with a path_value of the exact amount we want, and if that generates a route we may
1852 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1853 // amount we want in total across paths, selecting the best subset at the end.
1854 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1855 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1856 let mut path_value_msat = final_value_msat;
1858 // Routing Fragmentation Mitigation heuristic:
1860 // Routing fragmentation across many payment paths increases the overall routing
1861 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1862 // Taking too many smaller paths also increases the chance of payment failure.
1863 // Thus to avoid this effect, we require from our collected links to provide
1864 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1865 // This requirement is currently set to be 1/max_path_count of the payment
1866 // value to ensure we only ever return routes that do not violate this limit.
1867 let minimal_value_contribution_msat: u64 = if allow_mpp {
1868 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1873 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1874 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1875 // drop the requirement by setting this to 0.
1876 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1878 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1879 // determine if the channel can be used by additional MPP paths or to inform path finding
1880 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1881 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1883 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1884 HashMap::with_capacity(network_nodes.len());
1886 // Keeping track of how much value we already collected across other paths. Helps to decide
1887 // when we want to stop looking for new paths.
1888 let mut already_collected_value_msat = 0;
1890 for (_, channels) in first_hop_targets.iter_mut() {
1891 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1895 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1896 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1898 // Remember how many candidates we ignored to allow for some logging afterwards.
1899 let mut num_ignored_value_contribution: u32 = 0;
1900 let mut num_ignored_path_length_limit: u32 = 0;
1901 let mut num_ignored_cltv_delta_limit: u32 = 0;
1902 let mut num_ignored_previously_failed: u32 = 0;
1903 let mut num_ignored_total_fee_limit: u32 = 0;
1904 let mut num_ignored_avoid_overpayment: u32 = 0;
1905 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
1907 macro_rules! add_entry {
1908 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
1909 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1910 // since that value has to be transferred over this channel.
1911 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
1912 ( $candidate: expr, $next_hops_fee_msat: expr,
1913 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1914 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1915 // We "return" whether we updated the path at the end, and how much we can route via
1916 // this channel, via this:
1917 let mut hop_contribution_amt_msat = None;
1918 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1919 // practice these cases should be caught earlier:
1920 // - for regular channels at channel announcement (TODO)
1921 // - for first and last hops early in get_route
1922 let src_node_id = $candidate.source();
1923 if Some(src_node_id) != $candidate.target() {
1924 let scid_opt = $candidate.short_channel_id();
1925 let effective_capacity = $candidate.effective_capacity();
1926 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1928 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1929 // It may be misleading because we might later choose to reduce the value transferred
1930 // over these channels, and the channel which was insufficient might become sufficient.
1931 // Worst case: we drop a good channel here because it can't cover the high following
1932 // fees caused by one expensive channel, but then this channel could have been used
1933 // if the amount being transferred over this path is lower.
1934 // We do this for now, but this is a subject for removal.
1935 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1936 let used_liquidity_msat = used_liquidities
1937 .get(&$candidate.id())
1938 .map_or(0, |used_liquidity_msat| {
1939 available_value_contribution_msat = available_value_contribution_msat
1940 .saturating_sub(*used_liquidity_msat);
1941 *used_liquidity_msat
1944 // Verify the liquidity offered by this channel complies to the minimal contribution.
1945 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1946 // Do not consider candidate hops that would exceed the maximum path length.
1947 let path_length_to_node = $next_hops_path_length + 1;
1948 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1950 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1951 // In order to already account for some of the privacy enhancing random CLTV
1952 // expiry delta offset we add on top later, we subtract a rough estimate
1953 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1954 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1955 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1956 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1957 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1958 .saturating_add($candidate.cltv_expiry_delta());
1959 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1961 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1962 // Includes paying fees for the use of the following channels.
1963 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1964 Some(result) => result,
1965 // Can't overflow due to how the values were computed right above.
1966 None => unreachable!(),
1968 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1969 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1970 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1972 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1973 let may_overpay_to_meet_path_minimum_msat =
1974 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1975 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
1976 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1977 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
1979 let payment_failed_on_this_channel = scid_opt.map_or(false,
1980 |scid| payment_params.previously_failed_channels.contains(&scid));
1982 let (should_log_candidate, first_hop_details) = match $candidate {
1983 CandidateRouteHop::FirstHop { details, .. } => (true, Some(details)),
1984 CandidateRouteHop::PrivateHop { .. } => (true, None),
1985 CandidateRouteHop::Blinded { .. } => (true, None),
1986 CandidateRouteHop::OneHopBlinded { .. } => (true, None),
1990 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1991 // bother considering this channel. If retrying with recommended_value_msat may
1992 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1993 // around again with a higher amount.
1994 if !contributes_sufficient_value {
1995 if should_log_candidate {
1996 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1998 if let Some(details) = first_hop_details {
2000 "First hop candidate next_outbound_htlc_limit_msat: {}",
2001 details.next_outbound_htlc_limit_msat,
2005 num_ignored_value_contribution += 1;
2006 } else if exceeds_max_path_length {
2007 if should_log_candidate {
2008 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2010 num_ignored_path_length_limit += 1;
2011 } else if exceeds_cltv_delta_limit {
2012 if should_log_candidate {
2013 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2015 if let Some(_) = first_hop_details {
2017 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2018 hop_total_cltv_delta,
2019 max_total_cltv_expiry_delta,
2023 num_ignored_cltv_delta_limit += 1;
2024 } else if payment_failed_on_this_channel {
2025 if should_log_candidate {
2026 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2028 num_ignored_previously_failed += 1;
2029 } else if may_overpay_to_meet_path_minimum_msat {
2030 if should_log_candidate {
2032 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2033 LoggedCandidateHop(&$candidate));
2035 if let Some(details) = first_hop_details {
2037 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2038 details.next_outbound_htlc_minimum_msat,
2042 num_ignored_avoid_overpayment += 1;
2043 hit_minimum_limit = true;
2044 } else if over_path_minimum_msat {
2045 // Note that low contribution here (limited by available_liquidity_msat)
2046 // might violate htlc_minimum_msat on the hops which are next along the
2047 // payment path (upstream to the payee). To avoid that, we recompute
2048 // path fees knowing the final path contribution after constructing it.
2049 let curr_min = cmp::max(
2050 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2052 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2053 .saturating_add(curr_min);
2054 let hm_entry = dist.entry(src_node_id);
2055 let old_entry = hm_entry.or_insert_with(|| {
2056 // If there was previously no known way to access the source node
2057 // (recall it goes payee-to-payer) of short_channel_id, first add a
2058 // semi-dummy record just to compute the fees to reach the source node.
2059 // This will affect our decision on selecting short_channel_id
2060 // as a way to reach the $candidate.target() node.
2062 candidate: $candidate.clone(),
2064 next_hops_fee_msat: u64::max_value(),
2065 hop_use_fee_msat: u64::max_value(),
2066 total_fee_msat: u64::max_value(),
2067 path_htlc_minimum_msat,
2068 path_penalty_msat: u64::max_value(),
2069 was_processed: false,
2070 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2071 value_contribution_msat,
2075 #[allow(unused_mut)] // We only use the mut in cfg(test)
2076 let mut should_process = !old_entry.was_processed;
2077 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2079 // In test/fuzzing builds, we do extra checks to make sure the skipping
2080 // of already-seen nodes only happens in cases we expect (see below).
2081 if !should_process { should_process = true; }
2085 let mut hop_use_fee_msat = 0;
2086 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2088 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2089 // will have the same effective-fee
2090 if src_node_id != our_node_id {
2091 // Note that `u64::max_value` means we'll always fail the
2092 // `old_entry.total_fee_msat > total_fee_msat` check below
2093 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2094 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2097 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2098 if total_fee_msat > max_total_routing_fee_msat {
2099 if should_log_candidate {
2100 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2102 if let Some(_) = first_hop_details {
2104 "First hop candidate routing fee: {}. Limit: {}",
2106 max_total_routing_fee_msat,
2110 num_ignored_total_fee_limit += 1;
2112 let channel_usage = ChannelUsage {
2113 amount_msat: amount_to_transfer_over_msat,
2114 inflight_htlc_msat: used_liquidity_msat,
2117 let channel_penalty_msat =
2118 scorer.channel_penalty_msat($candidate,
2121 let path_penalty_msat = $next_hops_path_penalty_msat
2122 .saturating_add(channel_penalty_msat);
2123 let new_graph_node = RouteGraphNode {
2124 node_id: src_node_id,
2125 lowest_fee_to_node: total_fee_msat,
2126 total_cltv_delta: hop_total_cltv_delta,
2127 value_contribution_msat,
2128 path_htlc_minimum_msat,
2130 path_length_to_node,
2133 // Update the way of reaching $candidate.source()
2134 // with the given short_channel_id (from $candidate.target()),
2135 // if this way is cheaper than the already known
2136 // (considering the cost to "reach" this channel from the route destination,
2137 // the cost of using this channel,
2138 // and the cost of routing to the source node of this channel).
2139 // Also, consider that htlc_minimum_msat_difference, because we might end up
2140 // paying it. Consider the following exploit:
2141 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2142 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2143 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2144 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2146 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2147 // but it may require additional tracking - we don't want to double-count
2148 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2149 // can't use something that may decrease on future hops.
2150 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2151 .saturating_add(old_entry.path_penalty_msat);
2152 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2153 .saturating_add(path_penalty_msat);
2155 if !old_entry.was_processed && new_cost < old_cost {
2156 targets.push(new_graph_node);
2157 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2158 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2159 old_entry.total_fee_msat = total_fee_msat;
2160 old_entry.candidate = $candidate.clone();
2161 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2162 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2163 old_entry.path_penalty_msat = path_penalty_msat;
2164 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2166 old_entry.value_contribution_msat = value_contribution_msat;
2168 hop_contribution_amt_msat = Some(value_contribution_msat);
2169 } else if old_entry.was_processed && new_cost < old_cost {
2170 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2172 // If we're skipping processing a node which was previously
2173 // processed even though we found another path to it with a
2174 // cheaper fee, check that it was because the second path we
2175 // found (which we are processing now) has a lower value
2176 // contribution due to an HTLC minimum limit.
2178 // e.g. take a graph with two paths from node 1 to node 2, one
2179 // through channel A, and one through channel B. Channel A and
2180 // B are both in the to-process heap, with their scores set by
2181 // a higher htlc_minimum than fee.
2182 // Channel A is processed first, and the channels onwards from
2183 // node 1 are added to the to-process heap. Thereafter, we pop
2184 // Channel B off of the heap, note that it has a much more
2185 // restrictive htlc_maximum_msat, and recalculate the fees for
2186 // all of node 1's channels using the new, reduced, amount.
2188 // This would be bogus - we'd be selecting a higher-fee path
2189 // with a lower htlc_maximum_msat instead of the one we'd
2190 // already decided to use.
2191 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2193 value_contribution_msat + path_penalty_msat <
2194 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2201 if should_log_candidate {
2203 "Ignoring {} due to its htlc_minimum_msat limit.",
2204 LoggedCandidateHop(&$candidate));
2206 if let Some(details) = first_hop_details {
2208 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2209 details.next_outbound_htlc_minimum_msat,
2213 num_ignored_htlc_minimum_msat_limit += 1;
2217 hop_contribution_amt_msat
2221 let default_node_features = default_node_features();
2223 // Find ways (channels with destination) to reach a given node and store them
2224 // in the corresponding data structures (routing graph etc).
2225 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2226 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2227 // This data can later be helpful to optimize routing (pay lower fees).
2228 macro_rules! add_entries_to_cheapest_to_target_node {
2229 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
2230 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
2231 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2232 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2233 let was_processed = elem.was_processed;
2234 elem.was_processed = true;
2237 // Entries are added to dist in add_entry!() when there is a channel from a node.
2238 // Because there are no channels from payee, it will not have a dist entry at this point.
2239 // If we're processing any other node, it is always be the result of a channel from it.
2240 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2245 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2246 for details in first_channels {
2247 let candidate = CandidateRouteHop::FirstHop {
2248 details, payer_node_id: &our_node_id,
2250 add_entry!(&candidate, $fee_to_target_msat,
2251 $next_hops_value_contribution,
2252 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
2253 $next_hops_cltv_delta, $next_hops_path_length);
2257 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2260 &default_node_features
2263 if !features.requires_unknown_bits() {
2264 for chan_id in $node.channels.iter() {
2265 let chan = network_channels.get(chan_id).unwrap();
2266 if !chan.features.requires_unknown_bits() {
2267 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2268 if first_hops.is_none() || *source != our_node_id {
2269 if directed_channel.direction().enabled {
2270 let candidate = CandidateRouteHop::PublicHop {
2271 info: directed_channel,
2272 short_channel_id: *chan_id,
2274 add_entry!(&candidate,
2275 $fee_to_target_msat,
2276 $next_hops_value_contribution,
2277 $next_hops_path_htlc_minimum_msat,
2278 $next_hops_path_penalty_msat,
2279 $next_hops_cltv_delta, $next_hops_path_length);
2290 let mut payment_paths = Vec::<PaymentPath>::new();
2292 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2293 'paths_collection: loop {
2294 // For every new path, start from scratch, except for used_liquidities, which
2295 // helps to avoid reusing previously selected paths in future iterations.
2298 hit_minimum_limit = false;
2300 // If first hop is a private channel and the only way to reach the payee, this is the only
2301 // place where it could be added.
2302 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2303 for details in first_channels {
2304 let candidate = CandidateRouteHop::FirstHop {
2305 details, payer_node_id: &our_node_id,
2307 let added = add_entry!(&candidate, 0, path_value_msat,
2308 0, 0u64, 0, 0).is_some();
2309 log_trace!(logger, "{} direct route to payee via {}",
2310 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2314 // Add the payee as a target, so that the payee-to-payer
2315 // search algorithm knows what to start with.
2316 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2317 // The payee is not in our network graph, so nothing to add here.
2318 // There is still a chance of reaching them via last_hops though,
2319 // so don't yet fail the payment here.
2320 // If not, targets.pop() will not even let us enter the loop in step 2.
2323 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2328 // If a caller provided us with last hops, add them to routing targets. Since this happens
2329 // earlier than general path finding, they will be somewhat prioritized, although currently
2330 // it matters only if the fees are exactly the same.
2331 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2332 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2333 let have_intro_node_in_graph =
2334 // Only add the hops in this route to our candidate set if either
2335 // we have a direct channel to the first hop or the first hop is
2336 // in the regular network graph.
2337 first_hop_targets.get(&intro_node_id).is_some() ||
2338 network_nodes.get(&intro_node_id).is_some();
2339 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2340 let candidate = if hint.1.blinded_hops.len() == 1 {
2341 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2342 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2343 let mut path_contribution_msat = path_value_msat;
2344 if let Some(hop_used_msat) = add_entry!(&candidate,
2345 0, path_contribution_msat, 0, 0_u64, 0, 0)
2347 path_contribution_msat = hop_used_msat;
2349 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2350 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2352 for details in first_channels {
2353 let first_hop_candidate = CandidateRouteHop::FirstHop {
2354 details, payer_node_id: &our_node_id,
2356 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2360 let path_min = candidate.htlc_minimum_msat().saturating_add(
2361 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2362 add_entry!(&first_hop_candidate, blinded_path_fee,
2363 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2364 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2368 for route in payment_params.payee.unblinded_route_hints().iter()
2369 .filter(|route| !route.0.is_empty())
2371 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2372 let first_hop_src_is_reachable =
2373 // Only add the hops in this route to our candidate set if either we are part of
2374 // the first hop, we have a direct channel to the first hop, or the first hop is in
2375 // the regular network graph.
2376 our_node_id == first_hop_src_id ||
2377 first_hop_targets.get(&first_hop_src_id).is_some() ||
2378 network_nodes.get(&first_hop_src_id).is_some();
2379 if first_hop_src_is_reachable {
2380 // We start building the path from reverse, i.e., from payee
2381 // to the first RouteHintHop in the path.
2382 let hop_iter = route.0.iter().rev();
2383 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2384 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2385 let mut hop_used = true;
2386 let mut aggregate_next_hops_fee_msat: u64 = 0;
2387 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2388 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2389 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2390 let mut aggregate_next_hops_path_length: u8 = 0;
2391 let mut aggregate_path_contribution_msat = path_value_msat;
2393 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2394 let target = private_hop_key_cache.get(&prev_hop_id).unwrap();
2396 if let Some(first_channels) = first_hop_targets.get(&target) {
2397 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2398 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2399 hop.short_channel_id);
2404 let candidate = network_channels
2405 .get(&hop.short_channel_id)
2406 .and_then(|channel| channel.as_directed_to(&target))
2407 .map(|(info, _)| CandidateRouteHop::PublicHop {
2409 short_channel_id: hop.short_channel_id,
2411 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop, target_node_id: target });
2413 if let Some(hop_used_msat) = add_entry!(&candidate,
2414 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2415 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2416 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2418 aggregate_path_contribution_msat = hop_used_msat;
2420 // If this hop was not used then there is no use checking the preceding
2421 // hops in the RouteHint. We can break by just searching for a direct
2422 // channel between last checked hop and first_hop_targets.
2426 let used_liquidity_msat = used_liquidities
2427 .get(&candidate.id()).copied()
2429 let channel_usage = ChannelUsage {
2430 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2431 inflight_htlc_msat: used_liquidity_msat,
2432 effective_capacity: candidate.effective_capacity(),
2434 let channel_penalty_msat = scorer.channel_penalty_msat(
2435 &candidate, channel_usage, score_params
2437 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2438 .saturating_add(channel_penalty_msat);
2440 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2441 .saturating_add(hop.cltv_expiry_delta as u32);
2443 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2446 // Searching for a direct channel between last checked hop and first_hop_targets
2447 if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2448 sort_first_hop_channels(first_channels, &used_liquidities,
2449 recommended_value_msat, our_node_pubkey);
2450 for details in first_channels {
2451 let first_hop_candidate = CandidateRouteHop::FirstHop {
2452 details, payer_node_id: &our_node_id,
2454 add_entry!(&first_hop_candidate,
2455 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2456 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2457 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2465 // In the next values of the iterator, the aggregate fees already reflects
2466 // the sum of value sent from payer (final_value_msat) and routing fees
2467 // for the last node in the RouteHint. We need to just add the fees to
2468 // route through the current node so that the preceding node (next iteration)
2470 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2471 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2472 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2474 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2475 // this route hint's source node to forward said min over this channel.
2476 aggregate_next_hops_path_htlc_minimum_msat = {
2477 let curr_htlc_min = cmp::max(
2478 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2480 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2481 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2484 if idx == route.0.len() - 1 {
2485 // The last hop in this iterator is the first hop in
2486 // overall RouteHint.
2487 // If this hop connects to a node with which we have a direct channel,
2488 // ignore the network graph and, if the last hop was added, add our
2489 // direct channel to the candidate set.
2491 // Note that we *must* check if the last hop was added as `add_entry`
2492 // always assumes that the third argument is a node to which we have a
2494 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2495 sort_first_hop_channels(first_channels, &used_liquidities,
2496 recommended_value_msat, our_node_pubkey);
2497 for details in first_channels {
2498 let first_hop_candidate = CandidateRouteHop::FirstHop {
2499 details, payer_node_id: &our_node_id,
2501 add_entry!(&first_hop_candidate,
2502 aggregate_next_hops_fee_msat,
2503 aggregate_path_contribution_msat,
2504 aggregate_next_hops_path_htlc_minimum_msat,
2505 aggregate_next_hops_path_penalty_msat,
2506 aggregate_next_hops_cltv_delta,
2507 aggregate_next_hops_path_length);
2515 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2517 // At this point, targets are filled with the data from first and
2518 // last hops communicated by the caller, and the payment receiver.
2519 let mut found_new_path = false;
2522 // If this loop terminates due the exhaustion of targets, two situations are possible:
2523 // - not enough outgoing liquidity:
2524 // 0 < already_collected_value_msat < final_value_msat
2525 // - enough outgoing liquidity:
2526 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2527 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2528 // paths_collection will be stopped because found_new_path==false.
2529 // This is not necessarily a routing failure.
2530 '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() {
2532 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2533 // traversing the graph and arrange the path out of what we found.
2534 if node_id == our_node_id {
2535 let mut new_entry = dist.remove(&our_node_id).unwrap();
2536 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2539 let mut features_set = false;
2540 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2541 if let Some(first_channels) = first_hop_targets.get(&target) {
2542 for details in first_channels {
2543 if let CandidateRouteHop::FirstHop { details: last_hop_details, .. }
2544 = ordered_hops.last().unwrap().0.candidate
2546 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2547 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2548 features_set = true;
2555 if let Some(node) = network_nodes.get(&target) {
2556 if let Some(node_info) = node.announcement_info.as_ref() {
2557 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2559 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2562 // We can fill in features for everything except hops which were
2563 // provided via the invoice we're paying. We could guess based on the
2564 // recipient's features but for now we simply avoid guessing at all.
2568 // Means we succesfully traversed from the payer to the payee, now
2569 // save this path for the payment route. Also, update the liquidity
2570 // remaining on the used hops, so that we take them into account
2571 // while looking for more paths.
2572 if target == maybe_dummy_payee_node_id {
2576 new_entry = match dist.remove(&target) {
2577 Some(payment_hop) => payment_hop,
2578 // We can't arrive at None because, if we ever add an entry to targets,
2579 // we also fill in the entry in dist (see add_entry!).
2580 None => unreachable!(),
2582 // We "propagate" the fees one hop backward (topologically) here,
2583 // so that fees paid for a HTLC forwarding on the current channel are
2584 // associated with the previous channel (where they will be subtracted).
2585 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2586 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2588 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2589 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2591 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2592 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2594 let mut payment_path = PaymentPath {hops: ordered_hops};
2596 // We could have possibly constructed a slightly inconsistent path: since we reduce
2597 // value being transferred along the way, we could have violated htlc_minimum_msat
2598 // on some channels we already passed (assuming dest->source direction). Here, we
2599 // recompute the fees again, so that if that's the case, we match the currently
2600 // underpaid htlc_minimum_msat with fees.
2601 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2602 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2603 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2605 // Since a path allows to transfer as much value as
2606 // the smallest channel it has ("bottleneck"), we should recompute
2607 // the fees so sender HTLC don't overpay fees when traversing
2608 // larger channels than the bottleneck. This may happen because
2609 // when we were selecting those channels we were not aware how much value
2610 // this path will transfer, and the relative fee for them
2611 // might have been computed considering a larger value.
2612 // Remember that we used these channels so that we don't rely
2613 // on the same liquidity in future paths.
2614 let mut prevented_redundant_path_selection = false;
2615 for (hop, _) in payment_path.hops.iter() {
2616 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2617 let used_liquidity_msat = used_liquidities
2618 .entry(hop.candidate.id())
2619 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2620 .or_insert(spent_on_hop_msat);
2621 let hop_capacity = hop.candidate.effective_capacity();
2622 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2623 if *used_liquidity_msat == hop_max_msat {
2624 // If this path used all of this channel's available liquidity, we know
2625 // this path will not be selected again in the next loop iteration.
2626 prevented_redundant_path_selection = true;
2628 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2630 if !prevented_redundant_path_selection {
2631 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2632 // we'll probably end up picking the same path again on the next iteration.
2633 // Decrease the available liquidity of a hop in the middle of the path.
2634 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2635 let exhausted = u64::max_value();
2637 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2638 LoggedCandidateHop(victim_candidate));
2639 if let Some(scid) = victim_candidate.short_channel_id() {
2640 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2641 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2645 // Track the total amount all our collected paths allow to send so that we know
2646 // when to stop looking for more paths
2647 already_collected_value_msat += value_contribution_msat;
2649 payment_paths.push(payment_path);
2650 found_new_path = true;
2651 break 'path_construction;
2654 // If we found a path back to the payee, we shouldn't try to process it again. This is
2655 // the equivalent of the `elem.was_processed` check in
2656 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2657 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2659 // Otherwise, since the current target node is not us,
2660 // keep "unrolling" the payment graph from payee to payer by
2661 // finding a way to reach the current target from the payer side.
2662 match network_nodes.get(&node_id) {
2665 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2666 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2667 total_cltv_delta, path_length_to_node);
2673 if !found_new_path && channel_saturation_pow_half != 0 {
2674 channel_saturation_pow_half = 0;
2675 continue 'paths_collection;
2677 // If we don't support MPP, no use trying to gather more value ever.
2678 break 'paths_collection;
2682 // Stop either when the recommended value is reached or if no new path was found in this
2684 // In the latter case, making another path finding attempt won't help,
2685 // because we deterministically terminated the search due to low liquidity.
2686 if !found_new_path && channel_saturation_pow_half != 0 {
2687 channel_saturation_pow_half = 0;
2688 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2689 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2690 path_value_msat = recommended_value_msat;
2691 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2692 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2693 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2694 break 'paths_collection;
2695 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2696 // Further, if this was our first walk of the graph, and we weren't limited by an
2697 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2698 // limited by an htlc_minimum_msat value, find another path with a higher value,
2699 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2700 // still keeping a lower total fee than this path.
2701 if !hit_minimum_limit {
2702 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2703 break 'paths_collection;
2705 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.");
2706 path_value_msat = recommended_value_msat;
2710 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2711 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2712 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2713 num_ignored_total_fee_limit;
2714 if num_ignored_total > 0 {
2716 "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.",
2717 num_ignored_value_contribution, num_ignored_path_length_limit,
2718 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2719 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2720 num_ignored_total_fee_limit, num_ignored_total);
2724 if payment_paths.len() == 0 {
2725 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2728 if already_collected_value_msat < final_value_msat {
2729 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2733 let mut selected_route = payment_paths;
2735 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2736 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2738 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2739 // the value they contribute towards the payment amount.
2740 // We sort in descending order as we will remove from the front in `retain`, next.
2741 selected_route.sort_unstable_by(|a, b|
2742 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2743 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2746 // We should make sure that at least 1 path left.
2747 let mut paths_left = selected_route.len();
2748 selected_route.retain(|path| {
2749 if paths_left == 1 {
2752 let path_value_msat = path.get_value_msat();
2753 if path_value_msat <= overpaid_value_msat {
2754 overpaid_value_msat -= path_value_msat;
2760 debug_assert!(selected_route.len() > 0);
2762 if overpaid_value_msat != 0 {
2764 // Now, subtract the remaining overpaid value from the most-expensive path.
2765 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2766 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2767 selected_route.sort_unstable_by(|a, b| {
2768 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2769 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2770 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2772 let expensive_payment_path = selected_route.first_mut().unwrap();
2774 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2775 // can't go negative.
2776 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2777 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2781 // Sort by the path itself and combine redundant paths.
2782 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2783 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2785 selected_route.sort_unstable_by_key(|path| {
2786 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2787 debug_assert!(path.hops.len() <= key.len());
2788 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2793 for idx in 0..(selected_route.len() - 1) {
2794 if idx + 1 >= selected_route.len() { break; }
2795 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2796 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2797 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2798 selected_route[idx].update_value_and_recompute_fees(new_value);
2799 selected_route.remove(idx + 1);
2803 let mut paths = Vec::new();
2804 for payment_path in selected_route {
2805 let mut hops = Vec::with_capacity(payment_path.hops.len());
2806 for (hop, node_features) in payment_path.hops.iter()
2807 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2809 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2810 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2811 // If we sourced the hop from the graph we're sure the target node is announced.
2813 } else if let CandidateRouteHop::FirstHop { details, .. } = hop.candidate {
2814 // If this is a first hop we also know if it's announced.
2817 // If we sourced it any other way, we double-check the network graph to see if
2818 // there are announced channels between the endpoints. If so, the hop might be
2819 // referring to any of the announced channels, as its `short_channel_id` might be
2820 // an alias, in which case we don't take any chances here.
2821 network_graph.node(&target).map_or(false, |hop_node|
2822 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2823 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
2827 hops.push(RouteHop {
2828 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2829 node_features: node_features.clone(),
2830 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2831 channel_features: hop.candidate.features(),
2832 fee_msat: hop.fee_msat,
2833 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2834 maybe_announced_channel,
2837 let mut final_cltv_delta = final_cltv_expiry_delta;
2838 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2839 if let Some(blinded_path) = h.candidate.blinded_path() {
2840 final_cltv_delta = h.candidate.cltv_expiry_delta();
2842 hops: blinded_path.blinded_hops.clone(),
2843 blinding_point: blinded_path.blinding_point,
2844 excess_final_cltv_expiry_delta: 0,
2845 final_value_msat: h.fee_msat,
2849 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2850 // applicable for the previous hop.
2851 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2852 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2855 paths.push(Path { hops, blinded_tail });
2857 // Make sure we would never create a route with more paths than we allow.
2858 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2860 if let Some(node_features) = payment_params.payee.node_features() {
2861 for path in paths.iter_mut() {
2862 path.hops.last_mut().unwrap().node_features = node_features.clone();
2866 let route = Route { paths, route_params: Some(route_params.clone()) };
2868 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2869 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2870 if route.get_total_fees() > max_total_routing_fee_msat {
2871 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2872 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2876 log_info!(logger, "Got route: {}", log_route!(route));
2880 // When an adversarial intermediary node observes a payment, it may be able to infer its
2881 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2882 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2883 // payment path by adding a randomized 'shadow route' offset to the final hop.
2884 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2885 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2887 let network_channels = network_graph.channels();
2888 let network_nodes = network_graph.nodes();
2890 for path in route.paths.iter_mut() {
2891 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2893 // Remember the last three nodes of the random walk and avoid looping back on them.
2894 // Init with the last three nodes from the actual path, if possible.
2895 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2896 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2897 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2899 // Choose the last publicly known node as the starting point for the random walk.
2900 let mut cur_hop: Option<NodeId> = None;
2901 let mut path_nonce = [0u8; 12];
2902 if let Some(starting_hop) = path.hops.iter().rev()
2903 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2904 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2905 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2908 // Init PRNG with the path-dependant nonce, which is static for private paths.
2909 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2910 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2912 // Pick a random path length in [1 .. 3]
2913 prng.process_in_place(&mut random_path_bytes);
2914 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2916 for random_hop in 0..random_walk_length {
2917 // If we don't find a suitable offset in the public network graph, we default to
2918 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2919 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2921 if let Some(cur_node_id) = cur_hop {
2922 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2923 // Randomly choose the next unvisited hop.
2924 prng.process_in_place(&mut random_path_bytes);
2925 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2926 .checked_rem(cur_node.channels.len())
2927 .and_then(|index| cur_node.channels.get(index))
2928 .and_then(|id| network_channels.get(id)) {
2929 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2930 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2931 nodes_to_avoid[random_hop] = *next_id;
2932 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2933 cur_hop = Some(*next_id);
2940 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2941 .checked_add(random_hop_offset)
2942 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2945 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2946 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2947 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2949 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2950 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2951 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2952 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2953 max_path_offset = cmp::max(
2954 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2955 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2956 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2958 // Add 'shadow' CLTV offset to the final hop
2959 if let Some(tail) = path.blinded_tail.as_mut() {
2960 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2961 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2963 if let Some(last_hop) = path.hops.last_mut() {
2964 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2965 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2970 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2971 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2973 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2974 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2975 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2976 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2977 ) -> Result<Route, LightningError>
2978 where L::Target: Logger, GL::Target: Logger {
2979 let graph_lock = network_graph.read_only();
2980 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2981 &graph_lock, logger, random_seed_bytes)?;
2982 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2986 fn build_route_from_hops_internal<L: Deref>(
2987 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2988 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2989 ) -> Result<Route, LightningError> where L::Target: Logger {
2992 our_node_id: NodeId,
2993 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2996 impl ScoreLookUp for HopScorer {
2997 type ScoreParams = ();
2998 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
2999 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3001 let mut cur_id = self.our_node_id;
3002 for i in 0..self.hop_ids.len() {
3003 if let Some(next_id) = self.hop_ids[i] {
3004 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3016 impl<'a> Writeable for HopScorer {
3018 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3023 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3024 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3027 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3028 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3029 for i in 0..hops.len() {
3030 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3033 let scorer = HopScorer { our_node_id, hop_ids };
3035 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3040 use crate::blinded_path::{BlindedHop, BlindedPath};
3041 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3042 use crate::routing::utxo::UtxoResult;
3043 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3044 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3045 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop};
3046 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3047 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3048 use crate::chain::transaction::OutPoint;
3049 use crate::sign::EntropySource;
3050 use crate::ln::ChannelId;
3051 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3052 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3053 use crate::ln::channelmanager;
3054 use crate::offers::invoice::BlindedPayInfo;
3055 use crate::util::config::UserConfig;
3056 use crate::util::test_utils as ln_test_utils;
3057 use crate::util::chacha20::ChaCha20;
3058 use crate::util::ser::{Readable, Writeable};
3060 use crate::util::ser::Writer;
3062 use bitcoin::hashes::Hash;
3063 use bitcoin::network::constants::Network;
3064 use bitcoin::blockdata::constants::ChainHash;
3065 use bitcoin::blockdata::script::Builder;
3066 use bitcoin::blockdata::opcodes;
3067 use bitcoin::blockdata::transaction::TxOut;
3068 use bitcoin::hashes::hex::FromHex;
3069 use bitcoin::secp256k1::{PublicKey,SecretKey};
3070 use bitcoin::secp256k1::Secp256k1;
3072 use crate::io::Cursor;
3073 use crate::prelude::*;
3074 use crate::sync::Arc;
3076 use core::convert::TryInto;
3078 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3079 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3080 channelmanager::ChannelDetails {
3081 channel_id: ChannelId::new_zero(),
3082 counterparty: channelmanager::ChannelCounterparty {
3085 unspendable_punishment_reserve: 0,
3086 forwarding_info: None,
3087 outbound_htlc_minimum_msat: None,
3088 outbound_htlc_maximum_msat: None,
3090 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3093 outbound_scid_alias: None,
3094 inbound_scid_alias: None,
3095 channel_value_satoshis: 0,
3098 outbound_capacity_msat,
3099 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3100 next_outbound_htlc_minimum_msat: 0,
3101 inbound_capacity_msat: 42,
3102 unspendable_punishment_reserve: None,
3103 confirmations_required: None,
3104 confirmations: None,
3105 force_close_spend_delay: None,
3106 is_outbound: true, is_channel_ready: true,
3107 is_usable: true, is_public: true,
3108 inbound_htlc_minimum_msat: None,
3109 inbound_htlc_maximum_msat: None,
3111 feerate_sat_per_1000_weight: None,
3112 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3117 fn simple_route_test() {
3118 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3119 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3120 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3121 let scorer = ln_test_utils::TestScorer::new();
3122 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3123 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3125 // Simple route to 2 via 1
3127 let route_params = RouteParameters::from_payment_params_and_value(
3128 payment_params.clone(), 0);
3129 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3130 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3131 &Default::default(), &random_seed_bytes) {
3132 assert_eq!(err, "Cannot send a payment of 0 msat");
3133 } else { panic!(); }
3135 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3136 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3137 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3138 assert_eq!(route.paths[0].hops.len(), 2);
3140 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3141 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3142 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3143 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3144 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3145 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3147 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3148 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3149 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3150 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3151 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3152 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3156 fn invalid_first_hop_test() {
3157 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3158 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3159 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3160 let scorer = ln_test_utils::TestScorer::new();
3161 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3162 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3164 // Simple route to 2 via 1
3166 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3168 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3169 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3170 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3171 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3172 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3173 } else { panic!(); }
3175 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3176 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3177 assert_eq!(route.paths[0].hops.len(), 2);
3181 fn htlc_minimum_test() {
3182 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3183 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3184 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3185 let scorer = ln_test_utils::TestScorer::new();
3186 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3187 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3189 // Simple route to 2 via 1
3191 // Disable other paths
3192 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3193 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3194 short_channel_id: 12,
3196 flags: 2, // to disable
3197 cltv_expiry_delta: 0,
3198 htlc_minimum_msat: 0,
3199 htlc_maximum_msat: MAX_VALUE_MSAT,
3201 fee_proportional_millionths: 0,
3202 excess_data: Vec::new()
3204 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3205 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3206 short_channel_id: 3,
3208 flags: 2, // to disable
3209 cltv_expiry_delta: 0,
3210 htlc_minimum_msat: 0,
3211 htlc_maximum_msat: MAX_VALUE_MSAT,
3213 fee_proportional_millionths: 0,
3214 excess_data: Vec::new()
3216 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3217 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3218 short_channel_id: 13,
3220 flags: 2, // to disable
3221 cltv_expiry_delta: 0,
3222 htlc_minimum_msat: 0,
3223 htlc_maximum_msat: MAX_VALUE_MSAT,
3225 fee_proportional_millionths: 0,
3226 excess_data: Vec::new()
3228 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3229 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3230 short_channel_id: 6,
3232 flags: 2, // to disable
3233 cltv_expiry_delta: 0,
3234 htlc_minimum_msat: 0,
3235 htlc_maximum_msat: MAX_VALUE_MSAT,
3237 fee_proportional_millionths: 0,
3238 excess_data: Vec::new()
3240 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3241 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3242 short_channel_id: 7,
3244 flags: 2, // to disable
3245 cltv_expiry_delta: 0,
3246 htlc_minimum_msat: 0,
3247 htlc_maximum_msat: MAX_VALUE_MSAT,
3249 fee_proportional_millionths: 0,
3250 excess_data: Vec::new()
3253 // Check against amount_to_transfer_over_msat.
3254 // Set minimal HTLC of 200_000_000 msat.
3255 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3256 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3257 short_channel_id: 2,
3260 cltv_expiry_delta: 0,
3261 htlc_minimum_msat: 200_000_000,
3262 htlc_maximum_msat: MAX_VALUE_MSAT,
3264 fee_proportional_millionths: 0,
3265 excess_data: Vec::new()
3268 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3270 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3271 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3272 short_channel_id: 4,
3275 cltv_expiry_delta: 0,
3276 htlc_minimum_msat: 0,
3277 htlc_maximum_msat: 199_999_999,
3279 fee_proportional_millionths: 0,
3280 excess_data: Vec::new()
3283 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3284 let route_params = RouteParameters::from_payment_params_and_value(
3285 payment_params, 199_999_999);
3286 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3287 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3288 &Default::default(), &random_seed_bytes) {
3289 assert_eq!(err, "Failed to find a path to the given destination");
3290 } else { panic!(); }
3292 // Lift the restriction on the first hop.
3293 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3294 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3295 short_channel_id: 2,
3298 cltv_expiry_delta: 0,
3299 htlc_minimum_msat: 0,
3300 htlc_maximum_msat: MAX_VALUE_MSAT,
3302 fee_proportional_millionths: 0,
3303 excess_data: Vec::new()
3306 // A payment above the minimum should pass
3307 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3308 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3309 assert_eq!(route.paths[0].hops.len(), 2);
3313 fn htlc_minimum_overpay_test() {
3314 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3315 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3316 let config = UserConfig::default();
3317 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3318 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3320 let scorer = ln_test_utils::TestScorer::new();
3321 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3322 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3324 // A route to node#2 via two paths.
3325 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3326 // Thus, they can't send 60 without overpaying.
3327 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3328 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3329 short_channel_id: 2,
3332 cltv_expiry_delta: 0,
3333 htlc_minimum_msat: 35_000,
3334 htlc_maximum_msat: 40_000,
3336 fee_proportional_millionths: 0,
3337 excess_data: Vec::new()
3339 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3340 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3341 short_channel_id: 12,
3344 cltv_expiry_delta: 0,
3345 htlc_minimum_msat: 35_000,
3346 htlc_maximum_msat: 40_000,
3348 fee_proportional_millionths: 0,
3349 excess_data: Vec::new()
3353 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3354 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3355 short_channel_id: 13,
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: 0,
3375 excess_data: Vec::new()
3378 // Disable other paths
3379 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3380 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3381 short_channel_id: 1,
3383 flags: 2, // to disable
3384 cltv_expiry_delta: 0,
3385 htlc_minimum_msat: 0,
3386 htlc_maximum_msat: MAX_VALUE_MSAT,
3388 fee_proportional_millionths: 0,
3389 excess_data: Vec::new()
3392 let mut route_params = RouteParameters::from_payment_params_and_value(
3393 payment_params.clone(), 60_000);
3394 route_params.max_total_routing_fee_msat = Some(15_000);
3395 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3396 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3397 // Overpay fees to hit htlc_minimum_msat.
3398 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3399 // TODO: this could be better balanced to overpay 10k and not 15k.
3400 assert_eq!(overpaid_fees, 15_000);
3402 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3403 // while taking even more fee to match htlc_minimum_msat.
3404 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3405 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3406 short_channel_id: 12,
3409 cltv_expiry_delta: 0,
3410 htlc_minimum_msat: 65_000,
3411 htlc_maximum_msat: 80_000,
3413 fee_proportional_millionths: 0,
3414 excess_data: Vec::new()
3416 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3417 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3418 short_channel_id: 2,
3421 cltv_expiry_delta: 0,
3422 htlc_minimum_msat: 0,
3423 htlc_maximum_msat: MAX_VALUE_MSAT,
3425 fee_proportional_millionths: 0,
3426 excess_data: Vec::new()
3428 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3429 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3430 short_channel_id: 4,
3433 cltv_expiry_delta: 0,
3434 htlc_minimum_msat: 0,
3435 htlc_maximum_msat: MAX_VALUE_MSAT,
3437 fee_proportional_millionths: 100_000,
3438 excess_data: Vec::new()
3441 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3442 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3443 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3444 assert_eq!(route.paths.len(), 1);
3445 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3446 let fees = route.paths[0].hops[0].fee_msat;
3447 assert_eq!(fees, 5_000);
3449 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3450 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3451 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3452 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3453 // the other channel.
3454 assert_eq!(route.paths.len(), 1);
3455 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3456 let fees = route.paths[0].hops[0].fee_msat;
3457 assert_eq!(fees, 5_000);
3461 fn htlc_minimum_recipient_overpay_test() {
3462 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3463 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3464 let config = UserConfig::default();
3465 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3466 let scorer = ln_test_utils::TestScorer::new();
3467 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3468 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3470 // Route to node2 over a single path which requires overpaying the recipient themselves.
3472 // First disable all paths except the us -> node1 -> node2 path
3473 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3474 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3475 short_channel_id: 13,
3478 cltv_expiry_delta: 0,
3479 htlc_minimum_msat: 0,
3480 htlc_maximum_msat: 0,
3482 fee_proportional_millionths: 0,
3483 excess_data: Vec::new()
3486 // Set channel 4 to free but with a high htlc_minimum_msat
3487 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3488 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3489 short_channel_id: 4,
3492 cltv_expiry_delta: 0,
3493 htlc_minimum_msat: 15_000,
3494 htlc_maximum_msat: MAX_VALUE_MSAT,
3496 fee_proportional_millionths: 0,
3497 excess_data: Vec::new()
3500 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3501 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3502 // what we try to find a route for, so this test only just happens to work out to exactly
3504 let mut route_params = RouteParameters::from_payment_params_and_value(
3505 payment_params.clone(), 5_000);
3506 route_params.max_total_routing_fee_msat = Some(9_999);
3507 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3508 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3509 &Default::default(), &random_seed_bytes) {
3510 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3511 } else { panic!(); }
3513 let mut route_params = RouteParameters::from_payment_params_and_value(
3514 payment_params.clone(), 5_000);
3515 route_params.max_total_routing_fee_msat = Some(10_000);
3516 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3517 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3518 assert_eq!(route.get_total_fees(), 10_000);
3522 fn disable_channels_test() {
3523 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3524 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3525 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3526 let scorer = ln_test_utils::TestScorer::new();
3527 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3528 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3530 // // Disable channels 4 and 12 by flags=2
3531 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3532 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3533 short_channel_id: 4,
3535 flags: 2, // to disable
3536 cltv_expiry_delta: 0,
3537 htlc_minimum_msat: 0,
3538 htlc_maximum_msat: MAX_VALUE_MSAT,
3540 fee_proportional_millionths: 0,
3541 excess_data: Vec::new()
3543 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3544 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3545 short_channel_id: 12,
3547 flags: 2, // to disable
3548 cltv_expiry_delta: 0,
3549 htlc_minimum_msat: 0,
3550 htlc_maximum_msat: MAX_VALUE_MSAT,
3552 fee_proportional_millionths: 0,
3553 excess_data: Vec::new()
3556 // If all the channels require some features we don't understand, route should fail
3557 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3558 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3559 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3560 &Default::default(), &random_seed_bytes) {
3561 assert_eq!(err, "Failed to find a path to the given destination");
3562 } else { panic!(); }
3564 // If we specify a channel to node7, that overrides our local channel view and that gets used
3565 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3566 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3567 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3568 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3569 &Default::default(), &random_seed_bytes).unwrap();
3570 assert_eq!(route.paths[0].hops.len(), 2);
3572 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3573 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3574 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3575 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3576 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3577 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3579 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3580 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3581 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3582 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3583 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3584 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3588 fn disable_node_test() {
3589 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3590 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3591 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3592 let scorer = ln_test_utils::TestScorer::new();
3593 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3594 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3596 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3597 let mut unknown_features = NodeFeatures::empty();
3598 unknown_features.set_unknown_feature_required();
3599 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3600 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3601 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3603 // If all nodes require some features we don't understand, route should fail
3604 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3605 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3606 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3607 &Default::default(), &random_seed_bytes) {
3608 assert_eq!(err, "Failed to find a path to the given destination");
3609 } else { panic!(); }
3611 // If we specify a channel to node7, that overrides our local channel view and that gets used
3612 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3613 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3614 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3615 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3616 &Default::default(), &random_seed_bytes).unwrap();
3617 assert_eq!(route.paths[0].hops.len(), 2);
3619 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3620 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3621 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3622 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3623 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3624 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3626 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3627 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3628 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3629 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3630 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3631 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3633 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3634 // naively) assume that the user checked the feature bits on the invoice, which override
3635 // the node_announcement.
3639 fn our_chans_test() {
3640 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3641 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3642 let scorer = ln_test_utils::TestScorer::new();
3643 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3644 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3646 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3647 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3648 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3649 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3650 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3651 assert_eq!(route.paths[0].hops.len(), 3);
3653 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3654 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3655 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3656 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3657 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3658 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3660 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3661 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3662 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3663 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3664 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3665 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3667 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3668 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3669 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3670 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3671 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3672 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3674 // If we specify a channel to node7, that overrides our local channel view and that gets used
3675 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3676 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3677 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3678 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3679 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3680 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3681 &Default::default(), &random_seed_bytes).unwrap();
3682 assert_eq!(route.paths[0].hops.len(), 2);
3684 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3685 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3686 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3687 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3688 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3689 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3691 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3692 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3693 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3694 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3695 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3696 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3699 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3700 let zero_fees = RoutingFees {
3702 proportional_millionths: 0,
3704 vec![RouteHint(vec![RouteHintHop {
3705 src_node_id: nodes[3],
3706 short_channel_id: 8,
3708 cltv_expiry_delta: (8 << 4) | 1,
3709 htlc_minimum_msat: None,
3710 htlc_maximum_msat: None,
3712 ]), RouteHint(vec![RouteHintHop {
3713 src_node_id: nodes[4],
3714 short_channel_id: 9,
3717 proportional_millionths: 0,
3719 cltv_expiry_delta: (9 << 4) | 1,
3720 htlc_minimum_msat: None,
3721 htlc_maximum_msat: None,
3722 }]), RouteHint(vec![RouteHintHop {
3723 src_node_id: nodes[5],
3724 short_channel_id: 10,
3726 cltv_expiry_delta: (10 << 4) | 1,
3727 htlc_minimum_msat: None,
3728 htlc_maximum_msat: None,
3732 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3733 let zero_fees = RoutingFees {
3735 proportional_millionths: 0,
3737 vec![RouteHint(vec![RouteHintHop {
3738 src_node_id: nodes[2],
3739 short_channel_id: 5,
3742 proportional_millionths: 0,
3744 cltv_expiry_delta: (5 << 4) | 1,
3745 htlc_minimum_msat: None,
3746 htlc_maximum_msat: None,
3748 src_node_id: nodes[3],
3749 short_channel_id: 8,
3751 cltv_expiry_delta: (8 << 4) | 1,
3752 htlc_minimum_msat: None,
3753 htlc_maximum_msat: None,
3755 ]), RouteHint(vec![RouteHintHop {
3756 src_node_id: nodes[4],
3757 short_channel_id: 9,
3760 proportional_millionths: 0,
3762 cltv_expiry_delta: (9 << 4) | 1,
3763 htlc_minimum_msat: None,
3764 htlc_maximum_msat: None,
3765 }]), RouteHint(vec![RouteHintHop {
3766 src_node_id: nodes[5],
3767 short_channel_id: 10,
3769 cltv_expiry_delta: (10 << 4) | 1,
3770 htlc_minimum_msat: None,
3771 htlc_maximum_msat: None,
3776 fn partial_route_hint_test() {
3777 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3778 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3779 let scorer = ln_test_utils::TestScorer::new();
3780 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3781 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3783 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3784 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3785 // RouteHint may be partially used by the algo to build the best path.
3787 // First check that last hop can't have its source as the payee.
3788 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3789 src_node_id: nodes[6],
3790 short_channel_id: 8,
3793 proportional_millionths: 0,
3795 cltv_expiry_delta: (8 << 4) | 1,
3796 htlc_minimum_msat: None,
3797 htlc_maximum_msat: None,
3800 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3801 invalid_last_hops.push(invalid_last_hop);
3803 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3804 .with_route_hints(invalid_last_hops).unwrap();
3805 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3806 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3807 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3808 &Default::default(), &random_seed_bytes) {
3809 assert_eq!(err, "Route hint cannot have the payee as the source.");
3810 } else { panic!(); }
3813 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3814 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3815 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3816 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3817 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3818 assert_eq!(route.paths[0].hops.len(), 5);
3820 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3821 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3822 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3823 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3824 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3825 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3827 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3828 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3829 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3830 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3831 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3832 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3834 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3835 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3836 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3837 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3838 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3839 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3841 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3842 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3843 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3844 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3845 // If we have a peer in the node map, we'll use their features here since we don't have
3846 // a way of figuring out their features from the invoice:
3847 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3848 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3850 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3851 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3852 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3853 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3854 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3855 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3858 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3859 let zero_fees = RoutingFees {
3861 proportional_millionths: 0,
3863 vec![RouteHint(vec![RouteHintHop {
3864 src_node_id: nodes[3],
3865 short_channel_id: 8,
3867 cltv_expiry_delta: (8 << 4) | 1,
3868 htlc_minimum_msat: None,
3869 htlc_maximum_msat: None,
3870 }]), RouteHint(vec![
3872 ]), RouteHint(vec![RouteHintHop {
3873 src_node_id: nodes[5],
3874 short_channel_id: 10,
3876 cltv_expiry_delta: (10 << 4) | 1,
3877 htlc_minimum_msat: None,
3878 htlc_maximum_msat: None,
3883 fn ignores_empty_last_hops_test() {
3884 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3885 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3886 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3887 let scorer = ln_test_utils::TestScorer::new();
3888 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3889 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3891 // Test handling of an empty RouteHint passed in Invoice.
3892 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3893 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3894 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3895 assert_eq!(route.paths[0].hops.len(), 5);
3897 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3898 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3899 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3900 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3901 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3902 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3904 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3905 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3906 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3907 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3908 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3909 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3911 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3912 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3913 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3914 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3915 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3916 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3918 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3919 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3920 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3921 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3922 // If we have a peer in the node map, we'll use their features here since we don't have
3923 // a way of figuring out their features from the invoice:
3924 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3925 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3927 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3928 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3929 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3930 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3931 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3932 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3935 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3937 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3938 let zero_fees = RoutingFees {
3940 proportional_millionths: 0,
3942 vec![RouteHint(vec![RouteHintHop {
3943 src_node_id: hint_hops[0],
3944 short_channel_id: 0xff00,
3947 proportional_millionths: 0,
3949 cltv_expiry_delta: (5 << 4) | 1,
3950 htlc_minimum_msat: None,
3951 htlc_maximum_msat: None,
3953 src_node_id: hint_hops[1],
3954 short_channel_id: 0xff01,
3956 cltv_expiry_delta: (8 << 4) | 1,
3957 htlc_minimum_msat: None,
3958 htlc_maximum_msat: None,
3963 fn multi_hint_last_hops_test() {
3964 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3965 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3966 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3967 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3968 let scorer = ln_test_utils::TestScorer::new();
3969 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3970 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3971 // Test through channels 2, 3, 0xff00, 0xff01.
3972 // Test shows that multiple hop hints are considered.
3974 // Disabling channels 6 & 7 by flags=2
3975 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3976 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3977 short_channel_id: 6,
3979 flags: 2, // to disable
3980 cltv_expiry_delta: 0,
3981 htlc_minimum_msat: 0,
3982 htlc_maximum_msat: MAX_VALUE_MSAT,
3984 fee_proportional_millionths: 0,
3985 excess_data: Vec::new()
3987 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3988 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3989 short_channel_id: 7,
3991 flags: 2, // to disable
3992 cltv_expiry_delta: 0,
3993 htlc_minimum_msat: 0,
3994 htlc_maximum_msat: MAX_VALUE_MSAT,
3996 fee_proportional_millionths: 0,
3997 excess_data: Vec::new()
4000 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4001 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4002 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4003 assert_eq!(route.paths[0].hops.len(), 4);
4005 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4006 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4007 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4008 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4009 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4010 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4012 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4013 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4014 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4015 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4016 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4017 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4019 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4020 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4021 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4022 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4023 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4024 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4026 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4027 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4028 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4029 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4030 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4031 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4035 fn private_multi_hint_last_hops_test() {
4036 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4037 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4039 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4040 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4042 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4043 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4044 let scorer = ln_test_utils::TestScorer::new();
4045 // Test through channels 2, 3, 0xff00, 0xff01.
4046 // Test shows that multiple hop hints are considered.
4048 // Disabling channels 6 & 7 by flags=2
4049 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4050 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4051 short_channel_id: 6,
4053 flags: 2, // to disable
4054 cltv_expiry_delta: 0,
4055 htlc_minimum_msat: 0,
4056 htlc_maximum_msat: MAX_VALUE_MSAT,
4058 fee_proportional_millionths: 0,
4059 excess_data: Vec::new()
4061 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4062 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4063 short_channel_id: 7,
4065 flags: 2, // to disable
4066 cltv_expiry_delta: 0,
4067 htlc_minimum_msat: 0,
4068 htlc_maximum_msat: MAX_VALUE_MSAT,
4070 fee_proportional_millionths: 0,
4071 excess_data: Vec::new()
4074 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4075 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4076 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4077 assert_eq!(route.paths[0].hops.len(), 4);
4079 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4080 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4081 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4082 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4083 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4084 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4086 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4087 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4088 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4089 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4090 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4091 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4093 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4094 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4095 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4096 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4097 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4098 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4100 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4101 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4102 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4103 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4104 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4105 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4108 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4109 let zero_fees = RoutingFees {
4111 proportional_millionths: 0,
4113 vec![RouteHint(vec![RouteHintHop {
4114 src_node_id: nodes[4],
4115 short_channel_id: 11,
4117 cltv_expiry_delta: (11 << 4) | 1,
4118 htlc_minimum_msat: None,
4119 htlc_maximum_msat: None,
4121 src_node_id: nodes[3],
4122 short_channel_id: 8,
4124 cltv_expiry_delta: (8 << 4) | 1,
4125 htlc_minimum_msat: None,
4126 htlc_maximum_msat: None,
4127 }]), RouteHint(vec![RouteHintHop {
4128 src_node_id: nodes[4],
4129 short_channel_id: 9,
4132 proportional_millionths: 0,
4134 cltv_expiry_delta: (9 << 4) | 1,
4135 htlc_minimum_msat: None,
4136 htlc_maximum_msat: None,
4137 }]), RouteHint(vec![RouteHintHop {
4138 src_node_id: nodes[5],
4139 short_channel_id: 10,
4141 cltv_expiry_delta: (10 << 4) | 1,
4142 htlc_minimum_msat: None,
4143 htlc_maximum_msat: None,
4148 fn last_hops_with_public_channel_test() {
4149 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4150 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4151 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4152 let scorer = ln_test_utils::TestScorer::new();
4153 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4154 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4155 // This test shows that public routes can be present in the invoice
4156 // which would be handled in the same manner.
4158 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4159 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4160 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4161 assert_eq!(route.paths[0].hops.len(), 5);
4163 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4164 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4165 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4166 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4167 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4168 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4170 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4171 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4172 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4173 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4174 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4175 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4177 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4178 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4179 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4180 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4181 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4182 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4184 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4185 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4186 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4187 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4188 // If we have a peer in the node map, we'll use their features here since we don't have
4189 // a way of figuring out their features from the invoice:
4190 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4191 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4193 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4194 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4195 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4196 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4197 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4198 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4202 fn our_chans_last_hop_connect_test() {
4203 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4204 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4205 let scorer = ln_test_utils::TestScorer::new();
4206 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4207 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4209 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4210 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4211 let mut last_hops = last_hops(&nodes);
4212 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4213 .with_route_hints(last_hops.clone()).unwrap();
4214 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4215 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4216 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4217 &Default::default(), &random_seed_bytes).unwrap();
4218 assert_eq!(route.paths[0].hops.len(), 2);
4220 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4221 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4222 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4223 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4224 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4225 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4227 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4228 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4229 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4230 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4231 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4232 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4234 last_hops[0].0[0].fees.base_msat = 1000;
4236 // Revert to via 6 as the fee on 8 goes up
4237 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4238 .with_route_hints(last_hops).unwrap();
4239 let route_params = RouteParameters::from_payment_params_and_value(
4240 payment_params.clone(), 100);
4241 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4242 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4243 assert_eq!(route.paths[0].hops.len(), 4);
4245 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4246 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4247 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4248 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4249 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4250 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4252 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4253 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4254 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4255 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4256 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4257 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4259 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4260 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4261 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4262 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4263 // If we have a peer in the node map, we'll use their features here since we don't have
4264 // a way of figuring out their features from the invoice:
4265 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4266 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4268 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4269 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4270 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4271 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4272 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4273 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4275 // ...but still use 8 for larger payments as 6 has a variable feerate
4276 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4277 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4278 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4279 assert_eq!(route.paths[0].hops.len(), 5);
4281 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4282 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4283 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4284 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4285 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4286 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4288 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4289 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4290 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4291 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4292 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4293 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4295 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4296 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4297 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4298 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4299 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4300 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4302 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4303 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4304 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4305 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4306 // If we have a peer in the node map, we'll use their features here since we don't have
4307 // a way of figuring out their features from the invoice:
4308 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4309 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4311 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4312 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4313 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4314 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4315 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4316 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4319 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> {
4320 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4321 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4322 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4324 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4325 let last_hops = RouteHint(vec![RouteHintHop {
4326 src_node_id: middle_node_id,
4327 short_channel_id: 8,
4330 proportional_millionths: last_hop_fee_prop,
4332 cltv_expiry_delta: (8 << 4) | 1,
4333 htlc_minimum_msat: None,
4334 htlc_maximum_msat: last_hop_htlc_max,
4336 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4337 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4338 let scorer = ln_test_utils::TestScorer::new();
4339 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4340 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4341 let logger = ln_test_utils::TestLogger::new();
4342 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4343 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4344 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4345 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4346 &random_seed_bytes);
4351 fn unannounced_path_test() {
4352 // We should be able to send a payment to a destination without any help of a routing graph
4353 // if we have a channel with a common counterparty that appears in the first and last hop
4355 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4357 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4358 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4359 assert_eq!(route.paths[0].hops.len(), 2);
4361 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4362 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4363 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4364 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4365 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4366 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4368 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4369 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4370 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4371 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4372 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4373 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4377 fn overflow_unannounced_path_test_liquidity_underflow() {
4378 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4379 // the last-hop had a fee which overflowed a u64, we'd panic.
4380 // This was due to us adding the first-hop from us unconditionally, causing us to think
4381 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4382 // In this test, we previously hit a subtraction underflow due to having less available
4383 // liquidity at the last hop than 0.
4384 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());
4388 fn overflow_unannounced_path_test_feerate_overflow() {
4389 // This tests for the same case as above, except instead of hitting a subtraction
4390 // underflow, we hit a case where the fee charged at a hop overflowed.
4391 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());
4395 fn available_amount_while_routing_test() {
4396 // Tests whether we choose the correct available channel amount while routing.
4398 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4399 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4400 let scorer = ln_test_utils::TestScorer::new();
4401 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4402 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4403 let config = UserConfig::default();
4404 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4405 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4408 // We will use a simple single-path route from
4409 // our node to node2 via node0: channels {1, 3}.
4411 // First disable all other paths.
4412 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4413 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4414 short_channel_id: 2,
4417 cltv_expiry_delta: 0,
4418 htlc_minimum_msat: 0,
4419 htlc_maximum_msat: 100_000,
4421 fee_proportional_millionths: 0,
4422 excess_data: Vec::new()
4424 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4425 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4426 short_channel_id: 12,
4429 cltv_expiry_delta: 0,
4430 htlc_minimum_msat: 0,
4431 htlc_maximum_msat: 100_000,
4433 fee_proportional_millionths: 0,
4434 excess_data: Vec::new()
4437 // Make the first channel (#1) very permissive,
4438 // and we will be testing all limits on the second channel.
4439 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4440 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4441 short_channel_id: 1,
4444 cltv_expiry_delta: 0,
4445 htlc_minimum_msat: 0,
4446 htlc_maximum_msat: 1_000_000_000,
4448 fee_proportional_millionths: 0,
4449 excess_data: Vec::new()
4452 // First, let's see if routing works if we have absolutely no idea about the available amount.
4453 // In this case, it should be set to 250_000 sats.
4454 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4455 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4456 short_channel_id: 3,
4459 cltv_expiry_delta: 0,
4460 htlc_minimum_msat: 0,
4461 htlc_maximum_msat: 250_000_000,
4463 fee_proportional_millionths: 0,
4464 excess_data: Vec::new()
4468 // Attempt to route more than available results in a failure.
4469 let route_params = RouteParameters::from_payment_params_and_value(
4470 payment_params.clone(), 250_000_001);
4471 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4472 &our_id, &route_params, &network_graph.read_only(), None,
4473 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4474 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4475 } else { panic!(); }
4479 // Now, attempt to route an exact amount we have should be fine.
4480 let route_params = RouteParameters::from_payment_params_and_value(
4481 payment_params.clone(), 250_000_000);
4482 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4483 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4484 assert_eq!(route.paths.len(), 1);
4485 let path = route.paths.last().unwrap();
4486 assert_eq!(path.hops.len(), 2);
4487 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4488 assert_eq!(path.final_value_msat(), 250_000_000);
4491 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4492 // Disable channel #1 and use another first hop.
4493 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4494 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4495 short_channel_id: 1,
4498 cltv_expiry_delta: 0,
4499 htlc_minimum_msat: 0,
4500 htlc_maximum_msat: 1_000_000_000,
4502 fee_proportional_millionths: 0,
4503 excess_data: Vec::new()
4506 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4507 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4510 // Attempt to route more than available results in a failure.
4511 let route_params = RouteParameters::from_payment_params_and_value(
4512 payment_params.clone(), 200_000_001);
4513 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4514 &our_id, &route_params, &network_graph.read_only(),
4515 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4516 &Default::default(), &random_seed_bytes) {
4517 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4518 } else { panic!(); }
4522 // Now, attempt to route an exact amount we have should be fine.
4523 let route_params = RouteParameters::from_payment_params_and_value(
4524 payment_params.clone(), 200_000_000);
4525 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4526 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4527 &Default::default(), &random_seed_bytes).unwrap();
4528 assert_eq!(route.paths.len(), 1);
4529 let path = route.paths.last().unwrap();
4530 assert_eq!(path.hops.len(), 2);
4531 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4532 assert_eq!(path.final_value_msat(), 200_000_000);
4535 // Enable channel #1 back.
4536 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4537 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4538 short_channel_id: 1,
4541 cltv_expiry_delta: 0,
4542 htlc_minimum_msat: 0,
4543 htlc_maximum_msat: 1_000_000_000,
4545 fee_proportional_millionths: 0,
4546 excess_data: Vec::new()
4550 // Now let's see if routing works if we know only htlc_maximum_msat.
4551 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4552 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4553 short_channel_id: 3,
4556 cltv_expiry_delta: 0,
4557 htlc_minimum_msat: 0,
4558 htlc_maximum_msat: 15_000,
4560 fee_proportional_millionths: 0,
4561 excess_data: Vec::new()
4565 // Attempt to route more than available results in a failure.
4566 let route_params = RouteParameters::from_payment_params_and_value(
4567 payment_params.clone(), 15_001);
4568 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4569 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4570 &scorer, &Default::default(), &random_seed_bytes) {
4571 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4572 } else { panic!(); }
4576 // Now, attempt to route an exact amount we have should be fine.
4577 let route_params = RouteParameters::from_payment_params_and_value(
4578 payment_params.clone(), 15_000);
4579 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4580 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4581 assert_eq!(route.paths.len(), 1);
4582 let path = route.paths.last().unwrap();
4583 assert_eq!(path.hops.len(), 2);
4584 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4585 assert_eq!(path.final_value_msat(), 15_000);
4588 // Now let's see if routing works if we know only capacity from the UTXO.
4590 // We can't change UTXO capacity on the fly, so we'll disable
4591 // the existing channel and add another one with the capacity we need.
4592 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4593 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4594 short_channel_id: 3,
4597 cltv_expiry_delta: 0,
4598 htlc_minimum_msat: 0,
4599 htlc_maximum_msat: MAX_VALUE_MSAT,
4601 fee_proportional_millionths: 0,
4602 excess_data: Vec::new()
4605 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4606 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4607 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4608 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4609 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4611 *chain_monitor.utxo_ret.lock().unwrap() =
4612 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4613 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4615 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4616 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4617 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4618 short_channel_id: 333,
4621 cltv_expiry_delta: (3 << 4) | 1,
4622 htlc_minimum_msat: 0,
4623 htlc_maximum_msat: 15_000,
4625 fee_proportional_millionths: 0,
4626 excess_data: Vec::new()
4628 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4629 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4630 short_channel_id: 333,
4633 cltv_expiry_delta: (3 << 4) | 2,
4634 htlc_minimum_msat: 0,
4635 htlc_maximum_msat: 15_000,
4637 fee_proportional_millionths: 0,
4638 excess_data: Vec::new()
4642 // Attempt to route more than available results in a failure.
4643 let route_params = RouteParameters::from_payment_params_and_value(
4644 payment_params.clone(), 15_001);
4645 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4646 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4647 &scorer, &Default::default(), &random_seed_bytes) {
4648 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4649 } else { panic!(); }
4653 // Now, attempt to route an exact amount we have should be fine.
4654 let route_params = RouteParameters::from_payment_params_and_value(
4655 payment_params.clone(), 15_000);
4656 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4657 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4658 assert_eq!(route.paths.len(), 1);
4659 let path = route.paths.last().unwrap();
4660 assert_eq!(path.hops.len(), 2);
4661 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4662 assert_eq!(path.final_value_msat(), 15_000);
4665 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4666 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4667 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4668 short_channel_id: 333,
4671 cltv_expiry_delta: 0,
4672 htlc_minimum_msat: 0,
4673 htlc_maximum_msat: 10_000,
4675 fee_proportional_millionths: 0,
4676 excess_data: Vec::new()
4680 // Attempt to route more than available results in a failure.
4681 let route_params = RouteParameters::from_payment_params_and_value(
4682 payment_params.clone(), 10_001);
4683 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4684 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4685 &scorer, &Default::default(), &random_seed_bytes) {
4686 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4687 } else { panic!(); }
4691 // Now, attempt to route an exact amount we have should be fine.
4692 let route_params = RouteParameters::from_payment_params_and_value(
4693 payment_params.clone(), 10_000);
4694 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4695 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4696 assert_eq!(route.paths.len(), 1);
4697 let path = route.paths.last().unwrap();
4698 assert_eq!(path.hops.len(), 2);
4699 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4700 assert_eq!(path.final_value_msat(), 10_000);
4705 fn available_liquidity_last_hop_test() {
4706 // Check that available liquidity properly limits the path even when only
4707 // one of the latter hops is limited.
4708 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4709 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4710 let scorer = ln_test_utils::TestScorer::new();
4711 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4712 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4713 let config = UserConfig::default();
4714 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4715 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4718 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4719 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4720 // Total capacity: 50 sats.
4722 // Disable other potential paths.
4723 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4724 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4725 short_channel_id: 2,
4728 cltv_expiry_delta: 0,
4729 htlc_minimum_msat: 0,
4730 htlc_maximum_msat: 100_000,
4732 fee_proportional_millionths: 0,
4733 excess_data: Vec::new()
4735 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4736 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4737 short_channel_id: 7,
4740 cltv_expiry_delta: 0,
4741 htlc_minimum_msat: 0,
4742 htlc_maximum_msat: 100_000,
4744 fee_proportional_millionths: 0,
4745 excess_data: Vec::new()
4750 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4751 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4752 short_channel_id: 12,
4755 cltv_expiry_delta: 0,
4756 htlc_minimum_msat: 0,
4757 htlc_maximum_msat: 100_000,
4759 fee_proportional_millionths: 0,
4760 excess_data: Vec::new()
4762 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4763 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4764 short_channel_id: 13,
4767 cltv_expiry_delta: 0,
4768 htlc_minimum_msat: 0,
4769 htlc_maximum_msat: 100_000,
4771 fee_proportional_millionths: 0,
4772 excess_data: Vec::new()
4775 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4776 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4777 short_channel_id: 6,
4780 cltv_expiry_delta: 0,
4781 htlc_minimum_msat: 0,
4782 htlc_maximum_msat: 50_000,
4784 fee_proportional_millionths: 0,
4785 excess_data: Vec::new()
4787 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4788 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4789 short_channel_id: 11,
4792 cltv_expiry_delta: 0,
4793 htlc_minimum_msat: 0,
4794 htlc_maximum_msat: 100_000,
4796 fee_proportional_millionths: 0,
4797 excess_data: Vec::new()
4800 // Attempt to route more than available results in a failure.
4801 let route_params = RouteParameters::from_payment_params_and_value(
4802 payment_params.clone(), 60_000);
4803 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4804 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4805 &scorer, &Default::default(), &random_seed_bytes) {
4806 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4807 } else { panic!(); }
4811 // Now, attempt to route 49 sats (just a bit below the capacity).
4812 let route_params = RouteParameters::from_payment_params_and_value(
4813 payment_params.clone(), 49_000);
4814 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4815 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4816 assert_eq!(route.paths.len(), 1);
4817 let mut total_amount_paid_msat = 0;
4818 for path in &route.paths {
4819 assert_eq!(path.hops.len(), 4);
4820 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4821 total_amount_paid_msat += path.final_value_msat();
4823 assert_eq!(total_amount_paid_msat, 49_000);
4827 // Attempt to route an exact amount is also fine
4828 let route_params = RouteParameters::from_payment_params_and_value(
4829 payment_params, 50_000);
4830 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4831 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4832 assert_eq!(route.paths.len(), 1);
4833 let mut total_amount_paid_msat = 0;
4834 for path in &route.paths {
4835 assert_eq!(path.hops.len(), 4);
4836 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4837 total_amount_paid_msat += path.final_value_msat();
4839 assert_eq!(total_amount_paid_msat, 50_000);
4844 fn ignore_fee_first_hop_test() {
4845 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4846 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4847 let scorer = ln_test_utils::TestScorer::new();
4848 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4849 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4850 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4852 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4853 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4854 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4855 short_channel_id: 1,
4858 cltv_expiry_delta: 0,
4859 htlc_minimum_msat: 0,
4860 htlc_maximum_msat: 100_000,
4861 fee_base_msat: 1_000_000,
4862 fee_proportional_millionths: 0,
4863 excess_data: Vec::new()
4865 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4866 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4867 short_channel_id: 3,
4870 cltv_expiry_delta: 0,
4871 htlc_minimum_msat: 0,
4872 htlc_maximum_msat: 50_000,
4874 fee_proportional_millionths: 0,
4875 excess_data: Vec::new()
4879 let route_params = RouteParameters::from_payment_params_and_value(
4880 payment_params, 50_000);
4881 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4882 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4883 assert_eq!(route.paths.len(), 1);
4884 let mut total_amount_paid_msat = 0;
4885 for path in &route.paths {
4886 assert_eq!(path.hops.len(), 2);
4887 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4888 total_amount_paid_msat += path.final_value_msat();
4890 assert_eq!(total_amount_paid_msat, 50_000);
4895 fn simple_mpp_route_test() {
4896 let (secp_ctx, _, _, _, _) = build_graph();
4897 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4898 let config = UserConfig::default();
4899 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4900 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4902 do_simple_mpp_route_test(clear_payment_params);
4904 // MPP to a 1-hop blinded path for nodes[2]
4905 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
4906 let blinded_path = BlindedPath {
4907 introduction_node_id: nodes[2],
4908 blinding_point: ln_test_utils::pubkey(42),
4909 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4911 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4913 fee_proportional_millionths: 0,
4914 htlc_minimum_msat: 0,
4915 htlc_maximum_msat: 0,
4916 cltv_expiry_delta: 0,
4917 features: BlindedHopFeatures::empty(),
4919 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4920 .with_bolt12_features(bolt12_features.clone()).unwrap();
4921 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4923 // MPP to 3 2-hop blinded paths
4924 let mut blinded_path_node_0 = blinded_path.clone();
4925 blinded_path_node_0.introduction_node_id = nodes[0];
4926 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4927 let mut node_0_payinfo = blinded_payinfo.clone();
4928 node_0_payinfo.htlc_maximum_msat = 50_000;
4930 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4931 blinded_path_node_7.introduction_node_id = nodes[7];
4932 let mut node_7_payinfo = blinded_payinfo.clone();
4933 node_7_payinfo.htlc_maximum_msat = 60_000;
4935 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4936 blinded_path_node_1.introduction_node_id = nodes[1];
4937 let mut node_1_payinfo = blinded_payinfo.clone();
4938 node_1_payinfo.htlc_maximum_msat = 180_000;
4940 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4942 (node_0_payinfo, blinded_path_node_0),
4943 (node_7_payinfo, blinded_path_node_7),
4944 (node_1_payinfo, blinded_path_node_1)
4946 .with_bolt12_features(bolt12_features).unwrap();
4947 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4951 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4952 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4953 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4954 let scorer = ln_test_utils::TestScorer::new();
4955 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4956 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4958 // We need a route consisting of 3 paths:
4959 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4960 // To achieve this, the amount being transferred should be around
4961 // the total capacity of these 3 paths.
4963 // First, we set limits on these (previously unlimited) channels.
4964 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4966 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4967 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4968 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4969 short_channel_id: 1,
4972 cltv_expiry_delta: 0,
4973 htlc_minimum_msat: 0,
4974 htlc_maximum_msat: 100_000,
4976 fee_proportional_millionths: 0,
4977 excess_data: Vec::new()
4979 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4980 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4981 short_channel_id: 3,
4984 cltv_expiry_delta: 0,
4985 htlc_minimum_msat: 0,
4986 htlc_maximum_msat: 50_000,
4988 fee_proportional_millionths: 0,
4989 excess_data: Vec::new()
4992 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4993 // (total limit 60).
4994 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4995 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4996 short_channel_id: 12,
4999 cltv_expiry_delta: 0,
5000 htlc_minimum_msat: 0,
5001 htlc_maximum_msat: 60_000,
5003 fee_proportional_millionths: 0,
5004 excess_data: Vec::new()
5006 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5007 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5008 short_channel_id: 13,
5011 cltv_expiry_delta: 0,
5012 htlc_minimum_msat: 0,
5013 htlc_maximum_msat: 60_000,
5015 fee_proportional_millionths: 0,
5016 excess_data: Vec::new()
5019 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5020 // (total capacity 180 sats).
5021 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5022 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5023 short_channel_id: 2,
5026 cltv_expiry_delta: 0,
5027 htlc_minimum_msat: 0,
5028 htlc_maximum_msat: 200_000,
5030 fee_proportional_millionths: 0,
5031 excess_data: Vec::new()
5033 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5034 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5035 short_channel_id: 4,
5038 cltv_expiry_delta: 0,
5039 htlc_minimum_msat: 0,
5040 htlc_maximum_msat: 180_000,
5042 fee_proportional_millionths: 0,
5043 excess_data: Vec::new()
5047 // Attempt to route more than available results in a failure.
5048 let route_params = RouteParameters::from_payment_params_and_value(
5049 payment_params.clone(), 300_000);
5050 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5051 &our_id, &route_params, &network_graph.read_only(), None,
5052 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5053 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5054 } else { panic!(); }
5058 // Attempt to route while setting max_path_count to 0 results in a failure.
5059 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5060 let route_params = RouteParameters::from_payment_params_and_value(
5061 zero_payment_params, 100);
5062 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5063 &our_id, &route_params, &network_graph.read_only(), None,
5064 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5065 assert_eq!(err, "Can't find a route with no paths allowed.");
5066 } else { panic!(); }
5070 // Attempt to route while setting max_path_count to 3 results in a failure.
5071 // This is the case because the minimal_value_contribution_msat would require each path
5072 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5073 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5074 let route_params = RouteParameters::from_payment_params_and_value(
5075 fail_payment_params, 250_000);
5076 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5077 &our_id, &route_params, &network_graph.read_only(), None,
5078 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5079 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5080 } else { panic!(); }
5084 // Now, attempt to route 250 sats (just a bit below the capacity).
5085 // Our algorithm should provide us with these 3 paths.
5086 let route_params = RouteParameters::from_payment_params_and_value(
5087 payment_params.clone(), 250_000);
5088 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5089 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5090 assert_eq!(route.paths.len(), 3);
5091 let mut total_amount_paid_msat = 0;
5092 for path in &route.paths {
5093 if let Some(bt) = &path.blinded_tail {
5094 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5096 assert_eq!(path.hops.len(), 2);
5097 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5099 total_amount_paid_msat += path.final_value_msat();
5101 assert_eq!(total_amount_paid_msat, 250_000);
5105 // Attempt to route an exact amount is also fine
5106 let route_params = RouteParameters::from_payment_params_and_value(
5107 payment_params.clone(), 290_000);
5108 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5109 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5110 assert_eq!(route.paths.len(), 3);
5111 let mut total_amount_paid_msat = 0;
5112 for path in &route.paths {
5113 if payment_params.payee.blinded_route_hints().len() != 0 {
5114 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5115 if let Some(bt) = &path.blinded_tail {
5116 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5117 if bt.hops.len() > 1 {
5118 assert_eq!(path.hops.last().unwrap().pubkey,
5119 payment_params.payee.blinded_route_hints().iter()
5120 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5121 .map(|(_, p)| p.introduction_node_id).unwrap());
5123 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5126 assert_eq!(path.hops.len(), 2);
5127 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5129 total_amount_paid_msat += path.final_value_msat();
5131 assert_eq!(total_amount_paid_msat, 290_000);
5136 fn long_mpp_route_test() {
5137 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5138 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5139 let scorer = ln_test_utils::TestScorer::new();
5140 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5141 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5142 let config = UserConfig::default();
5143 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5144 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5147 // We need a route consisting of 3 paths:
5148 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5149 // Note that these paths overlap (channels 5, 12, 13).
5150 // We will route 300 sats.
5151 // Each path will have 100 sats capacity, those channels which
5152 // are used twice will have 200 sats capacity.
5154 // Disable other potential paths.
5155 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5156 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5157 short_channel_id: 2,
5160 cltv_expiry_delta: 0,
5161 htlc_minimum_msat: 0,
5162 htlc_maximum_msat: 100_000,
5164 fee_proportional_millionths: 0,
5165 excess_data: Vec::new()
5167 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5168 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5169 short_channel_id: 7,
5172 cltv_expiry_delta: 0,
5173 htlc_minimum_msat: 0,
5174 htlc_maximum_msat: 100_000,
5176 fee_proportional_millionths: 0,
5177 excess_data: Vec::new()
5180 // Path via {node0, node2} is channels {1, 3, 5}.
5181 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5182 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5183 short_channel_id: 1,
5186 cltv_expiry_delta: 0,
5187 htlc_minimum_msat: 0,
5188 htlc_maximum_msat: 100_000,
5190 fee_proportional_millionths: 0,
5191 excess_data: Vec::new()
5193 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5194 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5195 short_channel_id: 3,
5198 cltv_expiry_delta: 0,
5199 htlc_minimum_msat: 0,
5200 htlc_maximum_msat: 100_000,
5202 fee_proportional_millionths: 0,
5203 excess_data: Vec::new()
5206 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5207 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5208 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5209 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5210 short_channel_id: 5,
5213 cltv_expiry_delta: 0,
5214 htlc_minimum_msat: 0,
5215 htlc_maximum_msat: 200_000,
5217 fee_proportional_millionths: 0,
5218 excess_data: Vec::new()
5221 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5222 // Add 100 sats to the capacities of {12, 13}, because these channels
5223 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5224 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5225 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5226 short_channel_id: 12,
5229 cltv_expiry_delta: 0,
5230 htlc_minimum_msat: 0,
5231 htlc_maximum_msat: 200_000,
5233 fee_proportional_millionths: 0,
5234 excess_data: Vec::new()
5236 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5237 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5238 short_channel_id: 13,
5241 cltv_expiry_delta: 0,
5242 htlc_minimum_msat: 0,
5243 htlc_maximum_msat: 200_000,
5245 fee_proportional_millionths: 0,
5246 excess_data: Vec::new()
5249 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5250 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5251 short_channel_id: 6,
5254 cltv_expiry_delta: 0,
5255 htlc_minimum_msat: 0,
5256 htlc_maximum_msat: 100_000,
5258 fee_proportional_millionths: 0,
5259 excess_data: Vec::new()
5261 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5262 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5263 short_channel_id: 11,
5266 cltv_expiry_delta: 0,
5267 htlc_minimum_msat: 0,
5268 htlc_maximum_msat: 100_000,
5270 fee_proportional_millionths: 0,
5271 excess_data: Vec::new()
5274 // Path via {node7, node2} is channels {12, 13, 5}.
5275 // We already limited them to 200 sats (they are used twice for 100 sats).
5276 // Nothing to do here.
5279 // Attempt to route more than available results in a failure.
5280 let route_params = RouteParameters::from_payment_params_and_value(
5281 payment_params.clone(), 350_000);
5282 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5283 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5284 &scorer, &Default::default(), &random_seed_bytes) {
5285 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5286 } else { panic!(); }
5290 // Now, attempt to route 300 sats (exact amount we can route).
5291 // Our algorithm should provide us with these 3 paths, 100 sats each.
5292 let route_params = RouteParameters::from_payment_params_and_value(
5293 payment_params, 300_000);
5294 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5295 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5296 assert_eq!(route.paths.len(), 3);
5298 let mut total_amount_paid_msat = 0;
5299 for path in &route.paths {
5300 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5301 total_amount_paid_msat += path.final_value_msat();
5303 assert_eq!(total_amount_paid_msat, 300_000);
5309 fn mpp_cheaper_route_test() {
5310 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5311 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5312 let scorer = ln_test_utils::TestScorer::new();
5313 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5314 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5315 let config = UserConfig::default();
5316 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5317 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5320 // This test checks that if we have two cheaper paths and one more expensive path,
5321 // so that liquidity-wise any 2 of 3 combination is sufficient,
5322 // two cheaper paths will be taken.
5323 // These paths have equal available liquidity.
5325 // We need a combination of 3 paths:
5326 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5327 // Note that these paths overlap (channels 5, 12, 13).
5328 // Each path will have 100 sats capacity, those channels which
5329 // are used twice will have 200 sats capacity.
5331 // Disable other potential paths.
5332 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5333 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5334 short_channel_id: 2,
5337 cltv_expiry_delta: 0,
5338 htlc_minimum_msat: 0,
5339 htlc_maximum_msat: 100_000,
5341 fee_proportional_millionths: 0,
5342 excess_data: Vec::new()
5344 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5345 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5346 short_channel_id: 7,
5349 cltv_expiry_delta: 0,
5350 htlc_minimum_msat: 0,
5351 htlc_maximum_msat: 100_000,
5353 fee_proportional_millionths: 0,
5354 excess_data: Vec::new()
5357 // Path via {node0, node2} is channels {1, 3, 5}.
5358 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5359 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5360 short_channel_id: 1,
5363 cltv_expiry_delta: 0,
5364 htlc_minimum_msat: 0,
5365 htlc_maximum_msat: 100_000,
5367 fee_proportional_millionths: 0,
5368 excess_data: Vec::new()
5370 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5371 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5372 short_channel_id: 3,
5375 cltv_expiry_delta: 0,
5376 htlc_minimum_msat: 0,
5377 htlc_maximum_msat: 100_000,
5379 fee_proportional_millionths: 0,
5380 excess_data: Vec::new()
5383 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5384 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5385 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5386 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5387 short_channel_id: 5,
5390 cltv_expiry_delta: 0,
5391 htlc_minimum_msat: 0,
5392 htlc_maximum_msat: 200_000,
5394 fee_proportional_millionths: 0,
5395 excess_data: Vec::new()
5398 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5399 // Add 100 sats to the capacities of {12, 13}, because these channels
5400 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5401 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5402 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5403 short_channel_id: 12,
5406 cltv_expiry_delta: 0,
5407 htlc_minimum_msat: 0,
5408 htlc_maximum_msat: 200_000,
5410 fee_proportional_millionths: 0,
5411 excess_data: Vec::new()
5413 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5414 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5415 short_channel_id: 13,
5418 cltv_expiry_delta: 0,
5419 htlc_minimum_msat: 0,
5420 htlc_maximum_msat: 200_000,
5422 fee_proportional_millionths: 0,
5423 excess_data: Vec::new()
5426 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5427 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5428 short_channel_id: 6,
5431 cltv_expiry_delta: 0,
5432 htlc_minimum_msat: 0,
5433 htlc_maximum_msat: 100_000,
5434 fee_base_msat: 1_000,
5435 fee_proportional_millionths: 0,
5436 excess_data: Vec::new()
5438 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5439 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5440 short_channel_id: 11,
5443 cltv_expiry_delta: 0,
5444 htlc_minimum_msat: 0,
5445 htlc_maximum_msat: 100_000,
5447 fee_proportional_millionths: 0,
5448 excess_data: Vec::new()
5451 // Path via {node7, node2} is channels {12, 13, 5}.
5452 // We already limited them to 200 sats (they are used twice for 100 sats).
5453 // Nothing to do here.
5456 // Now, attempt to route 180 sats.
5457 // Our algorithm should provide us with these 2 paths.
5458 let route_params = RouteParameters::from_payment_params_and_value(
5459 payment_params, 180_000);
5460 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5461 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5462 assert_eq!(route.paths.len(), 2);
5464 let mut total_value_transferred_msat = 0;
5465 let mut total_paid_msat = 0;
5466 for path in &route.paths {
5467 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5468 total_value_transferred_msat += path.final_value_msat();
5469 for hop in &path.hops {
5470 total_paid_msat += hop.fee_msat;
5473 // If we paid fee, this would be higher.
5474 assert_eq!(total_value_transferred_msat, 180_000);
5475 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5476 assert_eq!(total_fees_paid, 0);
5481 fn fees_on_mpp_route_test() {
5482 // This test makes sure that MPP algorithm properly takes into account
5483 // fees charged on the channels, by making the fees impactful:
5484 // if the fee is not properly accounted for, the behavior is different.
5485 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5486 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5487 let scorer = ln_test_utils::TestScorer::new();
5488 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5489 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5490 let config = UserConfig::default();
5491 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5492 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5495 // We need a route consisting of 2 paths:
5496 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5497 // We will route 200 sats, Each path will have 100 sats capacity.
5499 // This test is not particularly stable: e.g.,
5500 // there's a way to route via {node0, node2, node4}.
5501 // It works while pathfinding is deterministic, but can be broken otherwise.
5502 // It's fine to ignore this concern for now.
5504 // Disable other potential paths.
5505 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5506 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5507 short_channel_id: 2,
5510 cltv_expiry_delta: 0,
5511 htlc_minimum_msat: 0,
5512 htlc_maximum_msat: 100_000,
5514 fee_proportional_millionths: 0,
5515 excess_data: Vec::new()
5518 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5519 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5520 short_channel_id: 7,
5523 cltv_expiry_delta: 0,
5524 htlc_minimum_msat: 0,
5525 htlc_maximum_msat: 100_000,
5527 fee_proportional_millionths: 0,
5528 excess_data: Vec::new()
5531 // Path via {node0, node2} is channels {1, 3, 5}.
5532 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5533 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5534 short_channel_id: 1,
5537 cltv_expiry_delta: 0,
5538 htlc_minimum_msat: 0,
5539 htlc_maximum_msat: 100_000,
5541 fee_proportional_millionths: 0,
5542 excess_data: Vec::new()
5544 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5545 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5546 short_channel_id: 3,
5549 cltv_expiry_delta: 0,
5550 htlc_minimum_msat: 0,
5551 htlc_maximum_msat: 100_000,
5553 fee_proportional_millionths: 0,
5554 excess_data: Vec::new()
5557 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5558 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5559 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5560 short_channel_id: 5,
5563 cltv_expiry_delta: 0,
5564 htlc_minimum_msat: 0,
5565 htlc_maximum_msat: 100_000,
5567 fee_proportional_millionths: 0,
5568 excess_data: Vec::new()
5571 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5572 // All channels should be 100 sats capacity. But for the fee experiment,
5573 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5574 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5575 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5576 // so no matter how large are other channels,
5577 // the whole path will be limited by 100 sats with just these 2 conditions:
5578 // - channel 12 capacity is 250 sats
5579 // - fee for channel 6 is 150 sats
5580 // Let's test this by enforcing these 2 conditions and removing other limits.
5581 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5582 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5583 short_channel_id: 12,
5586 cltv_expiry_delta: 0,
5587 htlc_minimum_msat: 0,
5588 htlc_maximum_msat: 250_000,
5590 fee_proportional_millionths: 0,
5591 excess_data: Vec::new()
5593 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5594 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5595 short_channel_id: 13,
5598 cltv_expiry_delta: 0,
5599 htlc_minimum_msat: 0,
5600 htlc_maximum_msat: MAX_VALUE_MSAT,
5602 fee_proportional_millionths: 0,
5603 excess_data: Vec::new()
5606 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5607 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5608 short_channel_id: 6,
5611 cltv_expiry_delta: 0,
5612 htlc_minimum_msat: 0,
5613 htlc_maximum_msat: MAX_VALUE_MSAT,
5614 fee_base_msat: 150_000,
5615 fee_proportional_millionths: 0,
5616 excess_data: Vec::new()
5618 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5619 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5620 short_channel_id: 11,
5623 cltv_expiry_delta: 0,
5624 htlc_minimum_msat: 0,
5625 htlc_maximum_msat: MAX_VALUE_MSAT,
5627 fee_proportional_millionths: 0,
5628 excess_data: Vec::new()
5632 // Attempt to route more than available results in a failure.
5633 let route_params = RouteParameters::from_payment_params_and_value(
5634 payment_params.clone(), 210_000);
5635 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5636 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5637 &scorer, &Default::default(), &random_seed_bytes) {
5638 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5639 } else { panic!(); }
5643 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5644 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5645 max_total_routing_fee_msat: Some(149_999) };
5646 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5647 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5648 &scorer, &Default::default(), &random_seed_bytes) {
5649 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5650 } else { panic!(); }
5654 // Now, attempt to route 200 sats (exact amount we can route).
5655 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5656 max_total_routing_fee_msat: Some(150_000) };
5657 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5658 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5659 assert_eq!(route.paths.len(), 2);
5661 let mut total_amount_paid_msat = 0;
5662 for path in &route.paths {
5663 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5664 total_amount_paid_msat += path.final_value_msat();
5666 assert_eq!(total_amount_paid_msat, 200_000);
5667 assert_eq!(route.get_total_fees(), 150_000);
5672 fn mpp_with_last_hops() {
5673 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5674 // via a single last-hop route hint, we'd fail to route if we first collected routes
5675 // totaling close but not quite enough to fund the full payment.
5677 // This was because we considered last-hop hints to have exactly the sought payment amount
5678 // instead of the amount we were trying to collect, needlessly limiting our path searching
5679 // at the very first hop.
5681 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5682 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5683 // to only have the remaining to-collect amount in available liquidity.
5685 // This bug appeared in production in some specific channel configurations.
5686 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5687 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5688 let scorer = ln_test_utils::TestScorer::new();
5689 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5690 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5691 let config = UserConfig::default();
5692 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5693 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5694 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5695 src_node_id: nodes[2],
5696 short_channel_id: 42,
5697 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5698 cltv_expiry_delta: 42,
5699 htlc_minimum_msat: None,
5700 htlc_maximum_msat: None,
5701 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5703 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5704 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5705 // would first use the no-fee route and then fail to find a path along the second route as
5706 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5707 // under 5% of our payment amount.
5708 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5709 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5710 short_channel_id: 1,
5713 cltv_expiry_delta: (5 << 4) | 5,
5714 htlc_minimum_msat: 0,
5715 htlc_maximum_msat: 99_000,
5716 fee_base_msat: u32::max_value(),
5717 fee_proportional_millionths: u32::max_value(),
5718 excess_data: Vec::new()
5720 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5721 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5722 short_channel_id: 2,
5725 cltv_expiry_delta: (5 << 4) | 3,
5726 htlc_minimum_msat: 0,
5727 htlc_maximum_msat: 99_000,
5728 fee_base_msat: u32::max_value(),
5729 fee_proportional_millionths: u32::max_value(),
5730 excess_data: Vec::new()
5732 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5733 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5734 short_channel_id: 4,
5737 cltv_expiry_delta: (4 << 4) | 1,
5738 htlc_minimum_msat: 0,
5739 htlc_maximum_msat: MAX_VALUE_MSAT,
5741 fee_proportional_millionths: 0,
5742 excess_data: Vec::new()
5744 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5745 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5746 short_channel_id: 13,
5748 flags: 0|2, // Channel disabled
5749 cltv_expiry_delta: (13 << 4) | 1,
5750 htlc_minimum_msat: 0,
5751 htlc_maximum_msat: MAX_VALUE_MSAT,
5753 fee_proportional_millionths: 2000000,
5754 excess_data: Vec::new()
5757 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5759 let route_params = RouteParameters::from_payment_params_and_value(
5760 payment_params, 100_000);
5761 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5762 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5763 assert_eq!(route.paths.len(), 2);
5764 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5765 // Paths are manually ordered ordered by SCID, so:
5766 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5767 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5768 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5769 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5770 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5771 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5772 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5773 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5774 assert_eq!(route.get_total_fees(), 1);
5775 assert_eq!(route.get_total_amount(), 100_000);
5779 fn drop_lowest_channel_mpp_route_test() {
5780 // This test checks that low-capacity channel is dropped when after
5781 // path finding we realize that we found more capacity than we need.
5782 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5783 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5784 let scorer = ln_test_utils::TestScorer::new();
5785 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5786 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5787 let config = UserConfig::default();
5788 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5789 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5791 .with_max_channel_saturation_power_of_half(0);
5793 // We need a route consisting of 3 paths:
5794 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5796 // The first and the second paths should be sufficient, but the third should be
5797 // cheaper, so that we select it but drop later.
5799 // First, we set limits on these (previously unlimited) channels.
5800 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5802 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5803 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5804 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5805 short_channel_id: 1,
5808 cltv_expiry_delta: 0,
5809 htlc_minimum_msat: 0,
5810 htlc_maximum_msat: 100_000,
5812 fee_proportional_millionths: 0,
5813 excess_data: Vec::new()
5815 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5816 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5817 short_channel_id: 3,
5820 cltv_expiry_delta: 0,
5821 htlc_minimum_msat: 0,
5822 htlc_maximum_msat: 50_000,
5824 fee_proportional_millionths: 0,
5825 excess_data: Vec::new()
5828 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5829 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5830 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5831 short_channel_id: 12,
5834 cltv_expiry_delta: 0,
5835 htlc_minimum_msat: 0,
5836 htlc_maximum_msat: 60_000,
5838 fee_proportional_millionths: 0,
5839 excess_data: Vec::new()
5841 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5842 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5843 short_channel_id: 13,
5846 cltv_expiry_delta: 0,
5847 htlc_minimum_msat: 0,
5848 htlc_maximum_msat: 60_000,
5850 fee_proportional_millionths: 0,
5851 excess_data: Vec::new()
5854 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5855 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5856 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5857 short_channel_id: 2,
5860 cltv_expiry_delta: 0,
5861 htlc_minimum_msat: 0,
5862 htlc_maximum_msat: 20_000,
5864 fee_proportional_millionths: 0,
5865 excess_data: Vec::new()
5867 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5868 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5869 short_channel_id: 4,
5872 cltv_expiry_delta: 0,
5873 htlc_minimum_msat: 0,
5874 htlc_maximum_msat: 20_000,
5876 fee_proportional_millionths: 0,
5877 excess_data: Vec::new()
5881 // Attempt to route more than available results in a failure.
5882 let route_params = RouteParameters::from_payment_params_and_value(
5883 payment_params.clone(), 150_000);
5884 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5885 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5886 &scorer, &Default::default(), &random_seed_bytes) {
5887 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5888 } else { panic!(); }
5892 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5893 // Our algorithm should provide us with these 3 paths.
5894 let route_params = RouteParameters::from_payment_params_and_value(
5895 payment_params.clone(), 125_000);
5896 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5897 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5898 assert_eq!(route.paths.len(), 3);
5899 let mut total_amount_paid_msat = 0;
5900 for path in &route.paths {
5901 assert_eq!(path.hops.len(), 2);
5902 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5903 total_amount_paid_msat += path.final_value_msat();
5905 assert_eq!(total_amount_paid_msat, 125_000);
5909 // Attempt to route without the last small cheap channel
5910 let route_params = RouteParameters::from_payment_params_and_value(
5911 payment_params, 90_000);
5912 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5913 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5914 assert_eq!(route.paths.len(), 2);
5915 let mut total_amount_paid_msat = 0;
5916 for path in &route.paths {
5917 assert_eq!(path.hops.len(), 2);
5918 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5919 total_amount_paid_msat += path.final_value_msat();
5921 assert_eq!(total_amount_paid_msat, 90_000);
5926 fn min_criteria_consistency() {
5927 // Test that we don't use an inconsistent metric between updating and walking nodes during
5928 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5929 // was updated with a different criterion from the heap sorting, resulting in loops in
5930 // calculated paths. We test for that specific case here.
5932 // We construct a network that looks like this:
5934 // node2 -1(3)2- node3
5938 // node1 -1(5)2- node4 -1(1)2- node6
5944 // We create a loop on the side of our real path - our destination is node 6, with a
5945 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5946 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5947 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5948 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5949 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5950 // "previous hop" being set to node 3, creating a loop in the path.
5951 let secp_ctx = Secp256k1::new();
5952 let logger = Arc::new(ln_test_utils::TestLogger::new());
5953 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5954 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5955 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5956 let scorer = ln_test_utils::TestScorer::new();
5957 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5958 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5959 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5961 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5962 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5963 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5964 short_channel_id: 6,
5967 cltv_expiry_delta: (6 << 4) | 0,
5968 htlc_minimum_msat: 0,
5969 htlc_maximum_msat: MAX_VALUE_MSAT,
5971 fee_proportional_millionths: 0,
5972 excess_data: Vec::new()
5974 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5976 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5977 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5978 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5979 short_channel_id: 5,
5982 cltv_expiry_delta: (5 << 4) | 0,
5983 htlc_minimum_msat: 0,
5984 htlc_maximum_msat: MAX_VALUE_MSAT,
5986 fee_proportional_millionths: 0,
5987 excess_data: Vec::new()
5989 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5991 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5992 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5993 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5994 short_channel_id: 4,
5997 cltv_expiry_delta: (4 << 4) | 0,
5998 htlc_minimum_msat: 0,
5999 htlc_maximum_msat: MAX_VALUE_MSAT,
6001 fee_proportional_millionths: 0,
6002 excess_data: Vec::new()
6004 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6006 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6007 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6008 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6009 short_channel_id: 3,
6012 cltv_expiry_delta: (3 << 4) | 0,
6013 htlc_minimum_msat: 0,
6014 htlc_maximum_msat: MAX_VALUE_MSAT,
6016 fee_proportional_millionths: 0,
6017 excess_data: Vec::new()
6019 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6021 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6022 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6023 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6024 short_channel_id: 2,
6027 cltv_expiry_delta: (2 << 4) | 0,
6028 htlc_minimum_msat: 0,
6029 htlc_maximum_msat: MAX_VALUE_MSAT,
6031 fee_proportional_millionths: 0,
6032 excess_data: Vec::new()
6035 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6036 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6037 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6038 short_channel_id: 1,
6041 cltv_expiry_delta: (1 << 4) | 0,
6042 htlc_minimum_msat: 100,
6043 htlc_maximum_msat: MAX_VALUE_MSAT,
6045 fee_proportional_millionths: 0,
6046 excess_data: Vec::new()
6048 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6051 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6052 let route_params = RouteParameters::from_payment_params_and_value(
6053 payment_params, 10_000);
6054 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6055 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6056 assert_eq!(route.paths.len(), 1);
6057 assert_eq!(route.paths[0].hops.len(), 3);
6059 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6060 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6061 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6062 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6063 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6064 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6066 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6067 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6068 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6069 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6070 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6071 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6073 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6074 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6075 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6076 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6077 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6078 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6084 fn exact_fee_liquidity_limit() {
6085 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6086 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6087 // we calculated fees on a higher value, resulting in us ignoring such paths.
6088 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6089 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6090 let scorer = ln_test_utils::TestScorer::new();
6091 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6092 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6093 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6095 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6097 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6098 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6099 short_channel_id: 2,
6102 cltv_expiry_delta: 0,
6103 htlc_minimum_msat: 0,
6104 htlc_maximum_msat: 85_000,
6106 fee_proportional_millionths: 0,
6107 excess_data: Vec::new()
6110 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6111 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6112 short_channel_id: 12,
6115 cltv_expiry_delta: (4 << 4) | 1,
6116 htlc_minimum_msat: 0,
6117 htlc_maximum_msat: 270_000,
6119 fee_proportional_millionths: 1000000,
6120 excess_data: Vec::new()
6124 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6125 // 200% fee charged channel 13 in the 1-to-2 direction.
6126 let mut route_params = RouteParameters::from_payment_params_and_value(
6127 payment_params, 90_000);
6128 route_params.max_total_routing_fee_msat = Some(90_000*2);
6129 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6130 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6131 assert_eq!(route.paths.len(), 1);
6132 assert_eq!(route.paths[0].hops.len(), 2);
6134 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6135 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6136 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6137 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6138 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6139 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6141 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6142 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6143 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6144 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6145 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6146 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6151 fn htlc_max_reduction_below_min() {
6152 // Test that if, while walking the graph, we reduce the value being sent to meet an
6153 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6154 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6155 // resulting in us thinking there is no possible path, even if other paths exist.
6156 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6157 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6158 let scorer = ln_test_utils::TestScorer::new();
6159 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6160 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6161 let config = UserConfig::default();
6162 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6163 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6166 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6167 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6168 // then try to send 90_000.
6169 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6170 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6171 short_channel_id: 2,
6174 cltv_expiry_delta: 0,
6175 htlc_minimum_msat: 0,
6176 htlc_maximum_msat: 80_000,
6178 fee_proportional_millionths: 0,
6179 excess_data: Vec::new()
6181 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6182 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6183 short_channel_id: 4,
6186 cltv_expiry_delta: (4 << 4) | 1,
6187 htlc_minimum_msat: 90_000,
6188 htlc_maximum_msat: MAX_VALUE_MSAT,
6190 fee_proportional_millionths: 0,
6191 excess_data: Vec::new()
6195 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6196 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6197 // expensive) channels 12-13 path.
6198 let mut route_params = RouteParameters::from_payment_params_and_value(
6199 payment_params, 90_000);
6200 route_params.max_total_routing_fee_msat = Some(90_000*2);
6201 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6202 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6203 assert_eq!(route.paths.len(), 1);
6204 assert_eq!(route.paths[0].hops.len(), 2);
6206 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6207 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6208 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6209 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6210 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6211 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6213 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6214 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6215 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6216 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6217 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6218 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6223 fn multiple_direct_first_hops() {
6224 // Previously we'd only ever considered one first hop path per counterparty.
6225 // However, as we don't restrict users to one channel per peer, we really need to support
6226 // looking at all first hop paths.
6227 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6228 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6229 // route over multiple channels with the same first hop.
6230 let secp_ctx = Secp256k1::new();
6231 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6232 let logger = Arc::new(ln_test_utils::TestLogger::new());
6233 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6234 let scorer = ln_test_utils::TestScorer::new();
6235 let config = UserConfig::default();
6236 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6237 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6239 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6240 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6243 let route_params = RouteParameters::from_payment_params_and_value(
6244 payment_params.clone(), 100_000);
6245 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6246 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6247 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6248 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6249 assert_eq!(route.paths.len(), 1);
6250 assert_eq!(route.paths[0].hops.len(), 1);
6252 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6253 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6254 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6257 let route_params = RouteParameters::from_payment_params_and_value(
6258 payment_params.clone(), 100_000);
6259 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6260 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6261 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6262 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6263 assert_eq!(route.paths.len(), 2);
6264 assert_eq!(route.paths[0].hops.len(), 1);
6265 assert_eq!(route.paths[1].hops.len(), 1);
6267 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6268 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6270 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6271 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6273 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6274 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6278 // If we have a bunch of outbound channels to the same node, where most are not
6279 // sufficient to pay the full payment, but one is, we should default to just using the
6280 // one single channel that has sufficient balance, avoiding MPP.
6282 // If we have several options above the 3xpayment value threshold, we should pick the
6283 // smallest of them, avoiding further fragmenting our available outbound balance to
6285 let route_params = RouteParameters::from_payment_params_and_value(
6286 payment_params, 100_000);
6287 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6288 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6289 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6290 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6291 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6292 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6293 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6294 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6295 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6296 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6297 assert_eq!(route.paths.len(), 1);
6298 assert_eq!(route.paths[0].hops.len(), 1);
6300 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6301 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6302 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6307 fn prefers_shorter_route_with_higher_fees() {
6308 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6309 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6310 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6312 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6313 let scorer = ln_test_utils::TestScorer::new();
6314 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6315 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6316 let route_params = RouteParameters::from_payment_params_and_value(
6317 payment_params.clone(), 100);
6318 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6319 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6320 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6322 assert_eq!(route.get_total_fees(), 100);
6323 assert_eq!(route.get_total_amount(), 100);
6324 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6326 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6327 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6328 let scorer = FixedPenaltyScorer::with_penalty(100);
6329 let route_params = RouteParameters::from_payment_params_and_value(
6330 payment_params, 100);
6331 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6332 Arc::clone(&logger), &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]);
6340 struct BadChannelScorer {
6341 short_channel_id: u64,
6345 impl Writeable for BadChannelScorer {
6346 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6348 impl ScoreLookUp for BadChannelScorer {
6349 type ScoreParams = ();
6350 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6351 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6355 struct BadNodeScorer {
6360 impl Writeable for BadNodeScorer {
6361 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6364 impl ScoreLookUp for BadNodeScorer {
6365 type ScoreParams = ();
6366 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6367 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6372 fn avoids_routing_through_bad_channels_and_nodes() {
6373 let (secp_ctx, network, _, _, logger) = build_graph();
6374 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6375 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6376 let network_graph = network.read_only();
6378 // A path to nodes[6] exists when no penalties are applied to any channel.
6379 let scorer = ln_test_utils::TestScorer::new();
6380 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6381 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6382 let route_params = RouteParameters::from_payment_params_and_value(
6383 payment_params, 100);
6384 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6385 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6386 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6388 assert_eq!(route.get_total_fees(), 100);
6389 assert_eq!(route.get_total_amount(), 100);
6390 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6392 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6393 let scorer = BadChannelScorer { short_channel_id: 6 };
6394 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6395 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6396 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6398 assert_eq!(route.get_total_fees(), 300);
6399 assert_eq!(route.get_total_amount(), 100);
6400 assert_eq!(path, vec![2, 4, 7, 10]);
6402 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6403 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6404 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6405 &scorer, &Default::default(), &random_seed_bytes) {
6406 Err(LightningError { err, .. } ) => {
6407 assert_eq!(err, "Failed to find a path to the given destination");
6409 Ok(_) => panic!("Expected error"),
6414 fn total_fees_single_path() {
6416 paths: vec![Path { hops: vec![
6418 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6419 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6420 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6423 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6424 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6425 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6428 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6429 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6430 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6432 ], blinded_tail: None }],
6436 assert_eq!(route.get_total_fees(), 250);
6437 assert_eq!(route.get_total_amount(), 225);
6441 fn total_fees_multi_path() {
6443 paths: vec![Path { hops: vec![
6445 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6446 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6447 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6450 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6451 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6452 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6454 ], blinded_tail: None }, Path { hops: vec![
6456 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6457 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6458 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6461 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6462 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6463 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6465 ], blinded_tail: None }],
6469 assert_eq!(route.get_total_fees(), 200);
6470 assert_eq!(route.get_total_amount(), 300);
6474 fn total_empty_route_no_panic() {
6475 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6476 // would both panic if the route was completely empty. We test to ensure they return 0
6477 // here, even though its somewhat nonsensical as a route.
6478 let route = Route { paths: Vec::new(), route_params: None };
6480 assert_eq!(route.get_total_fees(), 0);
6481 assert_eq!(route.get_total_amount(), 0);
6485 fn limits_total_cltv_delta() {
6486 let (secp_ctx, network, _, _, logger) = build_graph();
6487 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6488 let network_graph = network.read_only();
6490 let scorer = ln_test_utils::TestScorer::new();
6492 // Make sure that generally there is at least one route available
6493 let feasible_max_total_cltv_delta = 1008;
6494 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6495 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6496 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6497 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6498 let route_params = RouteParameters::from_payment_params_and_value(
6499 feasible_payment_params, 100);
6500 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6501 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6502 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6503 assert_ne!(path.len(), 0);
6505 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6506 let fail_max_total_cltv_delta = 23;
6507 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6508 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6509 let route_params = RouteParameters::from_payment_params_and_value(
6510 fail_payment_params, 100);
6511 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6512 &Default::default(), &random_seed_bytes)
6514 Err(LightningError { err, .. } ) => {
6515 assert_eq!(err, "Failed to find a path to the given destination");
6517 Ok(_) => panic!("Expected error"),
6522 fn avoids_recently_failed_paths() {
6523 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6524 // randomly inserting channels into it until we can't find a route anymore.
6525 let (secp_ctx, network, _, _, logger) = build_graph();
6526 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6527 let network_graph = network.read_only();
6529 let scorer = ln_test_utils::TestScorer::new();
6530 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6531 .with_max_path_count(1);
6532 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6533 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6535 // We should be able to find a route initially, and then after we fail a few random
6536 // channels eventually we won't be able to any longer.
6537 let route_params = RouteParameters::from_payment_params_and_value(
6538 payment_params.clone(), 100);
6539 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6540 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6542 let route_params = RouteParameters::from_payment_params_and_value(
6543 payment_params.clone(), 100);
6544 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6545 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6547 for chan in route.paths[0].hops.iter() {
6548 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6550 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6551 % route.paths[0].hops.len();
6552 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6558 fn limits_path_length() {
6559 let (secp_ctx, network, _, _, logger) = build_line_graph();
6560 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6561 let network_graph = network.read_only();
6563 let scorer = ln_test_utils::TestScorer::new();
6564 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6565 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6567 // First check we can actually create a long route on this graph.
6568 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6569 let route_params = RouteParameters::from_payment_params_and_value(
6570 feasible_payment_params, 100);
6571 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6572 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6573 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6574 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6576 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6577 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6578 let route_params = RouteParameters::from_payment_params_and_value(
6579 fail_payment_params, 100);
6580 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6581 &Default::default(), &random_seed_bytes)
6583 Err(LightningError { err, .. } ) => {
6584 assert_eq!(err, "Failed to find a path to the given destination");
6586 Ok(_) => panic!("Expected error"),
6591 fn adds_and_limits_cltv_offset() {
6592 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6593 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6595 let scorer = ln_test_utils::TestScorer::new();
6597 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6598 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6599 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6600 let route_params = RouteParameters::from_payment_params_and_value(
6601 payment_params.clone(), 100);
6602 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6603 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6604 assert_eq!(route.paths.len(), 1);
6606 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6608 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6609 let mut route_default = route.clone();
6610 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6611 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6612 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6613 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6614 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6616 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6617 let mut route_limited = route.clone();
6618 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6619 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6620 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6621 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6622 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6626 fn adds_plausible_cltv_offset() {
6627 let (secp_ctx, network, _, _, logger) = build_graph();
6628 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6629 let network_graph = network.read_only();
6630 let network_nodes = network_graph.nodes();
6631 let network_channels = network_graph.channels();
6632 let scorer = ln_test_utils::TestScorer::new();
6633 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6634 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6635 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6637 let route_params = RouteParameters::from_payment_params_and_value(
6638 payment_params.clone(), 100);
6639 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6640 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6641 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6643 let mut path_plausibility = vec![];
6645 for p in route.paths {
6646 // 1. Select random observation point
6647 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6648 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6650 prng.process_in_place(&mut random_bytes);
6651 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6652 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6654 // 2. Calculate what CLTV expiry delta we would observe there
6655 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6657 // 3. Starting from the observation point, find candidate paths
6658 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6659 candidates.push_back((observation_point, vec![]));
6661 let mut found_plausible_candidate = false;
6663 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6664 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6665 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6666 found_plausible_candidate = true;
6667 break 'candidate_loop;
6671 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6672 for channel_id in &cur_node.channels {
6673 if let Some(channel_info) = network_channels.get(&channel_id) {
6674 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6675 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6676 if cur_path_cltv_deltas.iter().sum::<u32>()
6677 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6678 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6679 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6680 candidates.push_back((*next_id, new_path_cltv_deltas));
6688 path_plausibility.push(found_plausible_candidate);
6690 assert!(path_plausibility.iter().all(|x| *x));
6694 fn builds_correct_path_from_hops() {
6695 let (secp_ctx, network, _, _, logger) = build_graph();
6696 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6697 let network_graph = network.read_only();
6699 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6700 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6702 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6703 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6704 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6705 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6706 Arc::clone(&logger), &random_seed_bytes).unwrap();
6707 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6708 assert_eq!(hops.len(), route.paths[0].hops.len());
6709 for (idx, hop_pubkey) in hops.iter().enumerate() {
6710 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6715 fn avoids_saturating_channels() {
6716 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6717 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6718 let decay_params = ProbabilisticScoringDecayParameters::default();
6719 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6721 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6722 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6723 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6724 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6725 short_channel_id: 4,
6728 cltv_expiry_delta: (4 << 4) | 1,
6729 htlc_minimum_msat: 0,
6730 htlc_maximum_msat: 250_000_000,
6732 fee_proportional_millionths: 0,
6733 excess_data: Vec::new()
6735 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6736 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6737 short_channel_id: 13,
6740 cltv_expiry_delta: (13 << 4) | 1,
6741 htlc_minimum_msat: 0,
6742 htlc_maximum_msat: 250_000_000,
6744 fee_proportional_millionths: 0,
6745 excess_data: Vec::new()
6748 let config = UserConfig::default();
6749 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6750 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6752 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6753 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6754 // 100,000 sats is less than the available liquidity on each channel, set above.
6755 let route_params = RouteParameters::from_payment_params_and_value(
6756 payment_params, 100_000_000);
6757 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6758 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6759 assert_eq!(route.paths.len(), 2);
6760 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6761 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6764 #[cfg(not(feature = "no-std"))]
6765 pub(super) fn random_init_seed() -> u64 {
6766 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6767 use core::hash::{BuildHasher, Hasher};
6768 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6769 println!("Using seed of {}", seed);
6774 #[cfg(not(feature = "no-std"))]
6775 fn generate_routes() {
6776 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6778 let logger = ln_test_utils::TestLogger::new();
6779 let graph = match super::bench_utils::read_network_graph(&logger) {
6787 let params = ProbabilisticScoringFeeParameters::default();
6788 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6789 let features = super::Bolt11InvoiceFeatures::empty();
6791 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6795 #[cfg(not(feature = "no-std"))]
6796 fn generate_routes_mpp() {
6797 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6799 let logger = ln_test_utils::TestLogger::new();
6800 let graph = match super::bench_utils::read_network_graph(&logger) {
6808 let params = ProbabilisticScoringFeeParameters::default();
6809 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6810 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6812 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6816 #[cfg(not(feature = "no-std"))]
6817 fn generate_large_mpp_routes() {
6818 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6820 let logger = ln_test_utils::TestLogger::new();
6821 let graph = match super::bench_utils::read_network_graph(&logger) {
6829 let params = ProbabilisticScoringFeeParameters::default();
6830 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6831 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6833 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6837 fn honors_manual_penalties() {
6838 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6839 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6841 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6842 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6844 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6845 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6847 // First check set manual penalties are returned by the scorer.
6848 let usage = ChannelUsage {
6850 inflight_htlc_msat: 0,
6851 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6853 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6854 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6855 let network_graph = network_graph.read_only();
6856 let channels = network_graph.channels();
6857 let channel = channels.get(&5).unwrap();
6858 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
6859 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop {
6861 short_channel_id: 5,
6863 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
6865 // Then check we can get a normal route
6866 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6867 let route_params = RouteParameters::from_payment_params_and_value(
6868 payment_params, 100);
6869 let route = get_route(&our_id, &route_params, &network_graph, None,
6870 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6871 assert!(route.is_ok());
6873 // Then check that we can't get a route if we ban an intermediate node.
6874 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6875 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6876 assert!(route.is_err());
6878 // Finally make sure we can route again, when we remove the ban.
6879 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6880 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6881 assert!(route.is_ok());
6885 fn abide_by_route_hint_max_htlc() {
6886 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6887 // params in the final route.
6888 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6889 let netgraph = network_graph.read_only();
6890 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6891 let scorer = ln_test_utils::TestScorer::new();
6892 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6893 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6894 let config = UserConfig::default();
6896 let max_htlc_msat = 50_000;
6897 let route_hint_1 = RouteHint(vec![RouteHintHop {
6898 src_node_id: nodes[2],
6899 short_channel_id: 42,
6902 proportional_millionths: 0,
6904 cltv_expiry_delta: 10,
6905 htlc_minimum_msat: None,
6906 htlc_maximum_msat: Some(max_htlc_msat),
6908 let dest_node_id = ln_test_utils::pubkey(42);
6909 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6910 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6911 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6914 // Make sure we'll error if our route hints don't have enough liquidity according to their
6915 // htlc_maximum_msat.
6916 let mut route_params = RouteParameters::from_payment_params_and_value(
6917 payment_params, max_htlc_msat + 1);
6918 route_params.max_total_routing_fee_msat = None;
6919 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6920 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6923 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6924 } else { panic!(); }
6926 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6927 let mut route_hint_2 = route_hint_1.clone();
6928 route_hint_2.0[0].short_channel_id = 43;
6929 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6930 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6931 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6933 let mut route_params = RouteParameters::from_payment_params_and_value(
6934 payment_params, max_htlc_msat + 1);
6935 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
6936 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6937 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6938 assert_eq!(route.paths.len(), 2);
6939 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6940 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6944 fn direct_channel_to_hints_with_max_htlc() {
6945 // Check that if we have a first hop channel peer that's connected to multiple provided route
6946 // hints, that we properly split the payment between the route hints if needed.
6947 let logger = Arc::new(ln_test_utils::TestLogger::new());
6948 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6949 let scorer = ln_test_utils::TestScorer::new();
6950 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6951 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6952 let config = UserConfig::default();
6954 let our_node_id = ln_test_utils::pubkey(42);
6955 let intermed_node_id = ln_test_utils::pubkey(43);
6956 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6958 let amt_msat = 900_000;
6959 let max_htlc_msat = 500_000;
6960 let route_hint_1 = RouteHint(vec![RouteHintHop {
6961 src_node_id: intermed_node_id,
6962 short_channel_id: 44,
6965 proportional_millionths: 0,
6967 cltv_expiry_delta: 10,
6968 htlc_minimum_msat: None,
6969 htlc_maximum_msat: Some(max_htlc_msat),
6971 src_node_id: intermed_node_id,
6972 short_channel_id: 45,
6975 proportional_millionths: 0,
6977 cltv_expiry_delta: 10,
6978 htlc_minimum_msat: None,
6979 // Check that later route hint max htlcs don't override earlier ones
6980 htlc_maximum_msat: Some(max_htlc_msat - 50),
6982 let mut route_hint_2 = route_hint_1.clone();
6983 route_hint_2.0[0].short_channel_id = 46;
6984 route_hint_2.0[1].short_channel_id = 47;
6985 let dest_node_id = ln_test_utils::pubkey(44);
6986 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6987 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6988 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6991 let route_params = RouteParameters::from_payment_params_and_value(
6992 payment_params, amt_msat);
6993 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6994 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6995 &Default::default(), &random_seed_bytes).unwrap();
6996 assert_eq!(route.paths.len(), 2);
6997 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6998 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6999 assert_eq!(route.get_total_amount(), amt_msat);
7001 // Re-run but with two first hop channels connected to the same route hint peers that must be
7003 let first_hops = vec![
7004 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7005 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7007 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7008 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7009 &Default::default(), &random_seed_bytes).unwrap();
7010 assert_eq!(route.paths.len(), 2);
7011 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7012 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7013 assert_eq!(route.get_total_amount(), amt_msat);
7015 // Make sure this works for blinded route hints.
7016 let blinded_path = BlindedPath {
7017 introduction_node_id: intermed_node_id,
7018 blinding_point: ln_test_utils::pubkey(42),
7020 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7021 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7024 let blinded_payinfo = BlindedPayInfo {
7026 fee_proportional_millionths: 0,
7027 htlc_minimum_msat: 1,
7028 htlc_maximum_msat: max_htlc_msat,
7029 cltv_expiry_delta: 10,
7030 features: BlindedHopFeatures::empty(),
7032 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7033 let payment_params = PaymentParameters::blinded(vec![
7034 (blinded_payinfo.clone(), blinded_path.clone()),
7035 (blinded_payinfo.clone(), blinded_path.clone())])
7036 .with_bolt12_features(bolt12_features).unwrap();
7037 let route_params = RouteParameters::from_payment_params_and_value(
7038 payment_params, amt_msat);
7039 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7040 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7041 &Default::default(), &random_seed_bytes).unwrap();
7042 assert_eq!(route.paths.len(), 2);
7043 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7044 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7045 assert_eq!(route.get_total_amount(), amt_msat);
7049 fn blinded_route_ser() {
7050 let blinded_path_1 = BlindedPath {
7051 introduction_node_id: ln_test_utils::pubkey(42),
7052 blinding_point: ln_test_utils::pubkey(43),
7054 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7055 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7058 let blinded_path_2 = BlindedPath {
7059 introduction_node_id: ln_test_utils::pubkey(46),
7060 blinding_point: ln_test_utils::pubkey(47),
7062 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7063 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7066 // (De)serialize a Route with 1 blinded path out of two total paths.
7067 let mut route = Route { paths: vec![Path {
7068 hops: vec![RouteHop {
7069 pubkey: ln_test_utils::pubkey(50),
7070 node_features: NodeFeatures::empty(),
7071 short_channel_id: 42,
7072 channel_features: ChannelFeatures::empty(),
7074 cltv_expiry_delta: 0,
7075 maybe_announced_channel: true,
7077 blinded_tail: Some(BlindedTail {
7078 hops: blinded_path_1.blinded_hops,
7079 blinding_point: blinded_path_1.blinding_point,
7080 excess_final_cltv_expiry_delta: 40,
7081 final_value_msat: 100,
7083 hops: vec![RouteHop {
7084 pubkey: ln_test_utils::pubkey(51),
7085 node_features: NodeFeatures::empty(),
7086 short_channel_id: 43,
7087 channel_features: ChannelFeatures::empty(),
7089 cltv_expiry_delta: 0,
7090 maybe_announced_channel: true,
7091 }], blinded_tail: None }],
7094 let encoded_route = route.encode();
7095 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7096 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7097 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7099 // (De)serialize a Route with two paths, each containing a blinded tail.
7100 route.paths[1].blinded_tail = Some(BlindedTail {
7101 hops: blinded_path_2.blinded_hops,
7102 blinding_point: blinded_path_2.blinding_point,
7103 excess_final_cltv_expiry_delta: 41,
7104 final_value_msat: 101,
7106 let encoded_route = route.encode();
7107 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7108 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7109 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7113 fn blinded_path_inflight_processing() {
7114 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7115 // account for the blinded tail's final amount_msat.
7116 let mut inflight_htlcs = InFlightHtlcs::new();
7117 let blinded_path = BlindedPath {
7118 introduction_node_id: ln_test_utils::pubkey(43),
7119 blinding_point: ln_test_utils::pubkey(48),
7120 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7123 hops: vec![RouteHop {
7124 pubkey: ln_test_utils::pubkey(42),
7125 node_features: NodeFeatures::empty(),
7126 short_channel_id: 42,
7127 channel_features: ChannelFeatures::empty(),
7129 cltv_expiry_delta: 0,
7130 maybe_announced_channel: false,
7133 pubkey: blinded_path.introduction_node_id,
7134 node_features: NodeFeatures::empty(),
7135 short_channel_id: 43,
7136 channel_features: ChannelFeatures::empty(),
7138 cltv_expiry_delta: 0,
7139 maybe_announced_channel: false,
7141 blinded_tail: Some(BlindedTail {
7142 hops: blinded_path.blinded_hops,
7143 blinding_point: blinded_path.blinding_point,
7144 excess_final_cltv_expiry_delta: 0,
7145 final_value_msat: 200,
7148 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7149 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7150 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7154 fn blinded_path_cltv_shadow_offset() {
7155 // Make sure we add a shadow offset when sending to blinded paths.
7156 let blinded_path = BlindedPath {
7157 introduction_node_id: ln_test_utils::pubkey(43),
7158 blinding_point: ln_test_utils::pubkey(44),
7160 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7161 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7164 let mut route = Route { paths: vec![Path {
7165 hops: vec![RouteHop {
7166 pubkey: ln_test_utils::pubkey(42),
7167 node_features: NodeFeatures::empty(),
7168 short_channel_id: 42,
7169 channel_features: ChannelFeatures::empty(),
7171 cltv_expiry_delta: 0,
7172 maybe_announced_channel: false,
7175 pubkey: blinded_path.introduction_node_id,
7176 node_features: NodeFeatures::empty(),
7177 short_channel_id: 43,
7178 channel_features: ChannelFeatures::empty(),
7180 cltv_expiry_delta: 0,
7181 maybe_announced_channel: false,
7184 blinded_tail: Some(BlindedTail {
7185 hops: blinded_path.blinded_hops,
7186 blinding_point: blinded_path.blinding_point,
7187 excess_final_cltv_expiry_delta: 0,
7188 final_value_msat: 200,
7190 }], route_params: None};
7192 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7193 let (_, network_graph, _, _, _) = build_line_graph();
7194 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7195 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7196 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7200 fn simple_blinded_route_hints() {
7201 do_simple_blinded_route_hints(1);
7202 do_simple_blinded_route_hints(2);
7203 do_simple_blinded_route_hints(3);
7206 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7207 // Check that we can generate a route to a blinded path with the expected hops.
7208 let (secp_ctx, network, _, _, logger) = build_graph();
7209 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7210 let network_graph = network.read_only();
7212 let scorer = ln_test_utils::TestScorer::new();
7213 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7214 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7216 let mut blinded_path = BlindedPath {
7217 introduction_node_id: nodes[2],
7218 blinding_point: ln_test_utils::pubkey(42),
7219 blinded_hops: Vec::with_capacity(num_blinded_hops),
7221 for i in 0..num_blinded_hops {
7222 blinded_path.blinded_hops.push(
7223 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7226 let blinded_payinfo = BlindedPayInfo {
7228 fee_proportional_millionths: 500,
7229 htlc_minimum_msat: 1000,
7230 htlc_maximum_msat: 100_000_000,
7231 cltv_expiry_delta: 15,
7232 features: BlindedHopFeatures::empty(),
7235 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7236 let route_params = RouteParameters::from_payment_params_and_value(
7237 payment_params, 1001);
7238 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7239 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7240 assert_eq!(route.paths.len(), 1);
7241 assert_eq!(route.paths[0].hops.len(), 2);
7243 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7244 assert_eq!(tail.hops, blinded_path.blinded_hops);
7245 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7246 assert_eq!(tail.final_value_msat, 1001);
7248 let final_hop = route.paths[0].hops.last().unwrap();
7249 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7250 if tail.hops.len() > 1 {
7251 assert_eq!(final_hop.fee_msat,
7252 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7253 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7255 assert_eq!(final_hop.fee_msat, 0);
7256 assert_eq!(final_hop.cltv_expiry_delta, 0);
7261 fn blinded_path_routing_errors() {
7262 // Check that we can generate a route to a blinded path with the expected hops.
7263 let (secp_ctx, network, _, _, logger) = build_graph();
7264 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7265 let network_graph = network.read_only();
7267 let scorer = ln_test_utils::TestScorer::new();
7268 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7269 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7271 let mut invalid_blinded_path = BlindedPath {
7272 introduction_node_id: nodes[2],
7273 blinding_point: ln_test_utils::pubkey(42),
7275 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7278 let blinded_payinfo = BlindedPayInfo {
7280 fee_proportional_millionths: 500,
7281 htlc_minimum_msat: 1000,
7282 htlc_maximum_msat: 100_000_000,
7283 cltv_expiry_delta: 15,
7284 features: BlindedHopFeatures::empty(),
7287 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7288 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7289 let payment_params = PaymentParameters::blinded(vec![
7290 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7291 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7292 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7293 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7294 &scorer, &Default::default(), &random_seed_bytes)
7296 Err(LightningError { err, .. }) => {
7297 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7299 _ => panic!("Expected error")
7302 invalid_blinded_path.introduction_node_id = our_id;
7303 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7304 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7305 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7306 &Default::default(), &random_seed_bytes)
7308 Err(LightningError { err, .. }) => {
7309 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7311 _ => panic!("Expected error")
7314 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7315 invalid_blinded_path.blinded_hops.clear();
7316 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7317 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7318 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7319 &Default::default(), &random_seed_bytes)
7321 Err(LightningError { err, .. }) => {
7322 assert_eq!(err, "0-hop blinded path provided");
7324 _ => panic!("Expected error")
7329 fn matching_intro_node_paths_provided() {
7330 // Check that if multiple blinded paths with the same intro node are provided in payment
7331 // parameters, we'll return the correct paths in the resulting MPP route.
7332 let (secp_ctx, network, _, _, logger) = build_graph();
7333 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7334 let network_graph = network.read_only();
7336 let scorer = ln_test_utils::TestScorer::new();
7337 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7338 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7339 let config = UserConfig::default();
7341 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7342 let blinded_path_1 = BlindedPath {
7343 introduction_node_id: nodes[2],
7344 blinding_point: ln_test_utils::pubkey(42),
7346 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7347 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7350 let blinded_payinfo_1 = BlindedPayInfo {
7352 fee_proportional_millionths: 0,
7353 htlc_minimum_msat: 0,
7354 htlc_maximum_msat: 30_000,
7355 cltv_expiry_delta: 0,
7356 features: BlindedHopFeatures::empty(),
7359 let mut blinded_path_2 = blinded_path_1.clone();
7360 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7361 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7362 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7364 let blinded_hints = vec![
7365 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7366 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7368 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7369 .with_bolt12_features(bolt12_features).unwrap();
7371 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7372 route_params.max_total_routing_fee_msat = Some(100_000);
7373 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7374 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7375 assert_eq!(route.paths.len(), 2);
7376 let mut total_amount_paid_msat = 0;
7377 for path in route.paths.into_iter() {
7378 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7379 if let Some(bt) = &path.blinded_tail {
7380 assert_eq!(bt.blinding_point,
7381 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7382 .map(|(_, bp)| bp.blinding_point).unwrap());
7383 } else { panic!(); }
7384 total_amount_paid_msat += path.final_value_msat();
7386 assert_eq!(total_amount_paid_msat, 100_000);
7390 fn direct_to_intro_node() {
7391 // This previously caused a debug panic in the router when asserting
7392 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7393 // direct channels we failed to account for the fee charged for use of the blinded path.
7396 // node0 -1(1)2 - node1
7397 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7398 // doesn't account for the blinded path fee.
7400 let secp_ctx = Secp256k1::new();
7401 let logger = Arc::new(ln_test_utils::TestLogger::new());
7402 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7403 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7404 let scorer = ln_test_utils::TestScorer::new();
7405 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7406 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7408 let amt_msat = 10_000_000;
7409 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7410 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7411 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7412 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7413 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7414 short_channel_id: 1,
7417 cltv_expiry_delta: 42,
7418 htlc_minimum_msat: 1_000,
7419 htlc_maximum_msat: 10_000_000,
7421 fee_proportional_millionths: 0,
7422 excess_data: Vec::new()
7424 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7425 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7426 short_channel_id: 1,
7429 cltv_expiry_delta: 42,
7430 htlc_minimum_msat: 1_000,
7431 htlc_maximum_msat: 10_000_000,
7433 fee_proportional_millionths: 0,
7434 excess_data: Vec::new()
7436 let first_hops = vec![
7437 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7439 let blinded_path = BlindedPath {
7440 introduction_node_id: nodes[1],
7441 blinding_point: ln_test_utils::pubkey(42),
7443 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7444 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7447 let blinded_payinfo = BlindedPayInfo {
7448 fee_base_msat: 1000,
7449 fee_proportional_millionths: 0,
7450 htlc_minimum_msat: 1000,
7451 htlc_maximum_msat: MAX_VALUE_MSAT,
7452 cltv_expiry_delta: 0,
7453 features: BlindedHopFeatures::empty(),
7455 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7457 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7459 let netgraph = network_graph.read_only();
7460 let route_params = RouteParameters::from_payment_params_and_value(
7461 payment_params.clone(), amt_msat);
7462 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7463 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7464 &Default::default(), &random_seed_bytes) {
7465 assert_eq!(err, "Failed to find a path to the given destination");
7466 } else { panic!("Expected error") }
7468 // Sending an exact amount accounting for the blinded path fee works.
7469 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7470 let route_params = RouteParameters::from_payment_params_and_value(
7471 payment_params, amt_minus_blinded_path_fee);
7472 let route = get_route(&nodes[0], &route_params, &netgraph,
7473 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7474 &Default::default(), &random_seed_bytes).unwrap();
7475 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7476 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7480 fn direct_to_matching_intro_nodes() {
7481 // This previously caused us to enter `unreachable` code in the following situation:
7482 // 1. We add a route candidate for intro_node contributing a high amount
7483 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7484 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7485 // amount, and update our route candidate for intro_node for the lower amount
7486 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7487 // lower contribution amount, but fail (this was previously caused by failure to account for
7488 // blinded path fees when adding first_hop<>intro_node candidates)
7489 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7490 // candidate still thinks its path is contributing the original higher amount. This caused us
7491 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7493 let secp_ctx = Secp256k1::new();
7494 let logger = Arc::new(ln_test_utils::TestLogger::new());
7495 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7496 let scorer = ln_test_utils::TestScorer::new();
7497 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7498 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7499 let config = UserConfig::default();
7501 // Values are taken from the fuzz input that uncovered this panic.
7502 let amt_msat = 21_7020_5185_1403_2640;
7503 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7504 let first_hops = vec![
7505 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7506 18446744073709551615)];
7508 let blinded_path = BlindedPath {
7509 introduction_node_id: nodes[1],
7510 blinding_point: ln_test_utils::pubkey(42),
7512 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7513 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7516 let blinded_payinfo = BlindedPayInfo {
7517 fee_base_msat: 5046_2720,
7518 fee_proportional_millionths: 0,
7519 htlc_minimum_msat: 4503_5996_2737_0496,
7520 htlc_maximum_msat: 45_0359_9627_3704_9600,
7521 cltv_expiry_delta: 0,
7522 features: BlindedHopFeatures::empty(),
7524 let mut blinded_hints = vec![
7525 (blinded_payinfo.clone(), blinded_path.clone()),
7526 (blinded_payinfo.clone(), blinded_path.clone()),
7528 blinded_hints[1].0.fee_base_msat = 419_4304;
7529 blinded_hints[1].0.fee_proportional_millionths = 257;
7530 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7531 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7532 blinded_hints[1].0.cltv_expiry_delta = 0;
7534 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7535 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7536 .with_bolt12_features(bolt12_features).unwrap();
7538 let netgraph = network_graph.read_only();
7539 let route_params = RouteParameters::from_payment_params_and_value(
7540 payment_params, amt_msat);
7541 let route = get_route(&nodes[0], &route_params, &netgraph,
7542 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7543 &Default::default(), &random_seed_bytes).unwrap();
7544 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7545 assert_eq!(route.get_total_amount(), amt_msat);
7549 fn we_are_intro_node_candidate_hops() {
7550 // This previously led to a panic in the router because we'd generate a Path with only a
7551 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7552 // where the origin node is the intro node. We now fully disallow considering candidate hops
7553 // where the origin node is the intro node.
7554 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7555 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7556 let scorer = ln_test_utils::TestScorer::new();
7557 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7558 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7559 let config = UserConfig::default();
7561 // Values are taken from the fuzz input that uncovered this panic.
7562 let amt_msat = 21_7020_5185_1423_0019;
7564 let blinded_path = BlindedPath {
7565 introduction_node_id: our_id,
7566 blinding_point: ln_test_utils::pubkey(42),
7568 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7569 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7572 let blinded_payinfo = BlindedPayInfo {
7573 fee_base_msat: 5052_9027,
7574 fee_proportional_millionths: 0,
7575 htlc_minimum_msat: 21_7020_5185_1423_0019,
7576 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7577 cltv_expiry_delta: 0,
7578 features: BlindedHopFeatures::empty(),
7580 let mut blinded_hints = vec![
7581 (blinded_payinfo.clone(), blinded_path.clone()),
7582 (blinded_payinfo.clone(), blinded_path.clone()),
7584 blinded_hints[1].1.introduction_node_id = nodes[6];
7586 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7587 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7588 .with_bolt12_features(bolt12_features.clone()).unwrap();
7590 let netgraph = network_graph.read_only();
7591 let route_params = RouteParameters::from_payment_params_and_value(
7592 payment_params, amt_msat);
7593 if let Err(LightningError { err, .. }) = get_route(
7594 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7596 assert_eq!(err, "Failed to find a path to the given destination");
7601 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7602 // This previously led to a debug panic in the router because we'd find an invalid Path with
7603 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7604 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7605 // the payment, when it was intended to only include the final value of the payment.
7606 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7607 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7608 let scorer = ln_test_utils::TestScorer::new();
7609 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7610 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7611 let config = UserConfig::default();
7613 // Values are taken from the fuzz input that uncovered this panic.
7614 let amt_msat = 21_7020_5185_1423_0019;
7616 let blinded_path = BlindedPath {
7617 introduction_node_id: our_id,
7618 blinding_point: ln_test_utils::pubkey(42),
7620 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7621 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7624 let blinded_payinfo = BlindedPayInfo {
7625 fee_base_msat: 10_4425_1395,
7626 fee_proportional_millionths: 0,
7627 htlc_minimum_msat: 21_7301_9934_9094_0931,
7628 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7629 cltv_expiry_delta: 0,
7630 features: BlindedHopFeatures::empty(),
7632 let mut blinded_hints = vec![
7633 (blinded_payinfo.clone(), blinded_path.clone()),
7634 (blinded_payinfo.clone(), blinded_path.clone()),
7635 (blinded_payinfo.clone(), blinded_path.clone()),
7637 blinded_hints[1].0.fee_base_msat = 5052_9027;
7638 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7639 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7641 blinded_hints[2].1.introduction_node_id = nodes[6];
7643 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7644 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7645 .with_bolt12_features(bolt12_features.clone()).unwrap();
7647 let netgraph = network_graph.read_only();
7648 let route_params = RouteParameters::from_payment_params_and_value(
7649 payment_params, amt_msat);
7650 if let Err(LightningError { err, .. }) = get_route(
7651 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7653 assert_eq!(err, "Failed to find a path to the given destination");
7658 fn min_htlc_overpay_violates_max_htlc() {
7659 do_min_htlc_overpay_violates_max_htlc(true);
7660 do_min_htlc_overpay_violates_max_htlc(false);
7662 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7663 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7664 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7665 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7666 // that the used liquidity for a hop was less than its available liquidity limit.
7667 let secp_ctx = Secp256k1::new();
7668 let logger = Arc::new(ln_test_utils::TestLogger::new());
7669 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7670 let scorer = ln_test_utils::TestScorer::new();
7671 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7672 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7673 let config = UserConfig::default();
7675 // Values are taken from the fuzz input that uncovered this panic.
7676 let amt_msat = 7_4009_8048;
7677 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7678 let first_hop_outbound_capacity = 2_7345_2000;
7679 let first_hops = vec![get_channel_details(
7680 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7681 first_hop_outbound_capacity
7684 let base_fee = 1_6778_3453;
7685 let htlc_min = 2_5165_8240;
7686 let payment_params = if blinded_payee {
7687 let blinded_path = BlindedPath {
7688 introduction_node_id: nodes[0],
7689 blinding_point: ln_test_utils::pubkey(42),
7691 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7692 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7695 let blinded_payinfo = BlindedPayInfo {
7696 fee_base_msat: base_fee,
7697 fee_proportional_millionths: 0,
7698 htlc_minimum_msat: htlc_min,
7699 htlc_maximum_msat: htlc_min * 1000,
7700 cltv_expiry_delta: 0,
7701 features: BlindedHopFeatures::empty(),
7703 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7704 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7705 .with_bolt12_features(bolt12_features.clone()).unwrap()
7707 let route_hint = RouteHint(vec![RouteHintHop {
7708 src_node_id: nodes[0],
7709 short_channel_id: 42,
7711 base_msat: base_fee,
7712 proportional_millionths: 0,
7714 cltv_expiry_delta: 10,
7715 htlc_minimum_msat: Some(htlc_min),
7716 htlc_maximum_msat: None,
7719 PaymentParameters::from_node_id(nodes[1], 42)
7720 .with_route_hints(vec![route_hint]).unwrap()
7721 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7724 let netgraph = network_graph.read_only();
7725 let route_params = RouteParameters::from_payment_params_and_value(
7726 payment_params, amt_msat);
7727 if let Err(LightningError { err, .. }) = get_route(
7728 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7729 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7731 assert_eq!(err, "Failed to find a path to the given destination");
7736 fn previously_used_liquidity_violates_max_htlc() {
7737 do_previously_used_liquidity_violates_max_htlc(true);
7738 do_previously_used_liquidity_violates_max_htlc(false);
7741 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7742 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7743 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7744 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7745 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7746 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7747 let secp_ctx = Secp256k1::new();
7748 let logger = Arc::new(ln_test_utils::TestLogger::new());
7749 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7750 let scorer = ln_test_utils::TestScorer::new();
7751 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7752 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7753 let config = UserConfig::default();
7755 // Values are taken from the fuzz input that uncovered this panic.
7756 let amt_msat = 52_4288;
7757 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7758 let first_hops = vec![get_channel_details(
7759 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7760 ), get_channel_details(
7761 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7764 let base_fees = [0, 425_9840, 0, 0];
7765 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7766 let payment_params = if blinded_payee {
7767 let blinded_path = BlindedPath {
7768 introduction_node_id: nodes[0],
7769 blinding_point: ln_test_utils::pubkey(42),
7771 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7772 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7775 let mut blinded_hints = Vec::new();
7776 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7777 blinded_hints.push((BlindedPayInfo {
7778 fee_base_msat: *base_fee,
7779 fee_proportional_millionths: 0,
7780 htlc_minimum_msat: *htlc_min,
7781 htlc_maximum_msat: htlc_min * 100,
7782 cltv_expiry_delta: 10,
7783 features: BlindedHopFeatures::empty(),
7784 }, blinded_path.clone()));
7786 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7787 PaymentParameters::blinded(blinded_hints.clone())
7788 .with_bolt12_features(bolt12_features.clone()).unwrap()
7790 let mut route_hints = Vec::new();
7791 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7792 route_hints.push(RouteHint(vec![RouteHintHop {
7793 src_node_id: nodes[0],
7794 short_channel_id: 42 + idx as u64,
7796 base_msat: *base_fee,
7797 proportional_millionths: 0,
7799 cltv_expiry_delta: 10,
7800 htlc_minimum_msat: Some(*htlc_min),
7801 htlc_maximum_msat: Some(htlc_min * 100),
7804 PaymentParameters::from_node_id(nodes[1], 42)
7805 .with_route_hints(route_hints).unwrap()
7806 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7809 let netgraph = network_graph.read_only();
7810 let route_params = RouteParameters::from_payment_params_and_value(
7811 payment_params, amt_msat);
7813 let route = get_route(
7814 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7815 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7817 assert_eq!(route.paths.len(), 1);
7818 assert_eq!(route.get_total_amount(), amt_msat);
7822 fn candidate_path_min() {
7823 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7824 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7825 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7826 // would add a connecting first_hop node that did not have enough contribution amount, leading
7827 // to a debug panic upon invalid path construction.
7828 let secp_ctx = Secp256k1::new();
7829 let logger = Arc::new(ln_test_utils::TestLogger::new());
7830 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7831 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7832 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7833 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7834 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7835 let config = UserConfig::default();
7837 // Values are taken from the fuzz input that uncovered this panic.
7838 let amt_msat = 7_4009_8048;
7839 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7840 let first_hops = vec![get_channel_details(
7841 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7844 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7845 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7846 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7847 short_channel_id: 6,
7850 cltv_expiry_delta: (6 << 4) | 0,
7851 htlc_minimum_msat: 0,
7852 htlc_maximum_msat: MAX_VALUE_MSAT,
7854 fee_proportional_millionths: 0,
7855 excess_data: Vec::new()
7857 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
7859 let htlc_min = 2_5165_8240;
7860 let blinded_hints = vec![
7862 fee_base_msat: 1_6778_3453,
7863 fee_proportional_millionths: 0,
7864 htlc_minimum_msat: htlc_min,
7865 htlc_maximum_msat: htlc_min * 100,
7866 cltv_expiry_delta: 10,
7867 features: BlindedHopFeatures::empty(),
7869 introduction_node_id: nodes[0],
7870 blinding_point: ln_test_utils::pubkey(42),
7872 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7873 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7877 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7878 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7879 .with_bolt12_features(bolt12_features.clone()).unwrap();
7880 let route_params = RouteParameters::from_payment_params_and_value(
7881 payment_params, amt_msat);
7882 let netgraph = network_graph.read_only();
7884 if let Err(LightningError { err, .. }) = get_route(
7885 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7886 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7889 assert_eq!(err, "Failed to find a path to the given destination");
7894 fn path_contribution_includes_min_htlc_overpay() {
7895 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
7896 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
7897 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
7898 // selection, both tested here.
7899 let secp_ctx = Secp256k1::new();
7900 let logger = Arc::new(ln_test_utils::TestLogger::new());
7901 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7902 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7903 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7904 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7905 let config = UserConfig::default();
7907 // Values are taken from the fuzz input that uncovered this panic.
7908 let amt_msat = 562_0000;
7909 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7910 let first_hops = vec![
7911 get_channel_details(
7912 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
7916 let htlc_mins = [49_0000, 1125_0000];
7917 let payment_params = {
7918 let blinded_path = BlindedPath {
7919 introduction_node_id: nodes[0],
7920 blinding_point: ln_test_utils::pubkey(42),
7922 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7923 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7926 let mut blinded_hints = Vec::new();
7927 for htlc_min in htlc_mins.iter() {
7928 blinded_hints.push((BlindedPayInfo {
7930 fee_proportional_millionths: 0,
7931 htlc_minimum_msat: *htlc_min,
7932 htlc_maximum_msat: *htlc_min * 100,
7933 cltv_expiry_delta: 10,
7934 features: BlindedHopFeatures::empty(),
7935 }, blinded_path.clone()));
7937 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7938 PaymentParameters::blinded(blinded_hints.clone())
7939 .with_bolt12_features(bolt12_features.clone()).unwrap()
7942 let netgraph = network_graph.read_only();
7943 let route_params = RouteParameters::from_payment_params_and_value(
7944 payment_params, amt_msat);
7945 let route = get_route(
7946 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7947 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7950 assert_eq!(route.paths.len(), 1);
7951 assert_eq!(route.get_total_amount(), amt_msat);
7955 fn first_hop_preferred_over_hint() {
7956 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
7957 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
7958 let secp_ctx = Secp256k1::new();
7959 let logger = Arc::new(ln_test_utils::TestLogger::new());
7960 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7961 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7962 let scorer = ln_test_utils::TestScorer::new();
7963 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7964 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7965 let config = UserConfig::default();
7967 let amt_msat = 1_000_000;
7968 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
7970 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
7971 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7972 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
7973 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7974 short_channel_id: 1,
7977 cltv_expiry_delta: 42,
7978 htlc_minimum_msat: 1_000,
7979 htlc_maximum_msat: 10_000_000,
7981 fee_proportional_millionths: 0,
7982 excess_data: Vec::new()
7984 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7985 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7986 short_channel_id: 1,
7989 cltv_expiry_delta: 42,
7990 htlc_minimum_msat: 1_000,
7991 htlc_maximum_msat: 10_000_000,
7993 fee_proportional_millionths: 0,
7994 excess_data: Vec::new()
7997 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7998 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
7999 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8000 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8001 short_channel_id: 2,
8004 cltv_expiry_delta: 42,
8005 htlc_minimum_msat: 1_000,
8006 htlc_maximum_msat: 10_000_000,
8008 fee_proportional_millionths: 0,
8009 excess_data: Vec::new()
8011 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8012 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8013 short_channel_id: 2,
8016 cltv_expiry_delta: 42,
8017 htlc_minimum_msat: 1_000,
8018 htlc_maximum_msat: 10_000_000,
8020 fee_proportional_millionths: 0,
8021 excess_data: Vec::new()
8024 let dest_node_id = nodes[2];
8026 let route_hint = RouteHint(vec![RouteHintHop {
8027 src_node_id: our_node_id,
8028 short_channel_id: 44,
8031 proportional_millionths: 0,
8033 cltv_expiry_delta: 10,
8034 htlc_minimum_msat: None,
8035 htlc_maximum_msat: Some(5_000_000),
8038 src_node_id: nodes[0],
8039 short_channel_id: 45,
8042 proportional_millionths: 0,
8044 cltv_expiry_delta: 10,
8045 htlc_minimum_msat: None,
8046 htlc_maximum_msat: None,
8049 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8050 .with_route_hints(vec![route_hint]).unwrap()
8051 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8052 let route_params = RouteParameters::from_payment_params_and_value(
8053 payment_params, amt_msat);
8055 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8057 let first_hop = get_channel_details(Some(1), nodes[0],
8058 channelmanager::provided_init_features(&config), 999_999);
8059 let first_hops = vec![first_hop];
8061 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8062 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8063 &Default::default(), &random_seed_bytes).unwrap();
8064 assert_eq!(route.paths.len(), 1);
8065 assert_eq!(route.get_total_amount(), amt_msat);
8066 assert_eq!(route.paths[0].hops.len(), 2);
8067 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8068 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8069 assert_eq!(route.get_total_fees(), 123);
8071 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8072 // for a first hop channel.
8073 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8074 first_hop.outbound_scid_alias = Some(44);
8075 let first_hops = vec![first_hop];
8077 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8078 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8079 &Default::default(), &random_seed_bytes);
8080 assert!(route_res.is_err());
8082 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8083 // use the cheaper second hop of the route hint.
8084 let mut first_hop = get_channel_details(Some(1), nodes[0],
8085 channelmanager::provided_init_features(&config), 10_000_000);
8086 first_hop.outbound_scid_alias = Some(44);
8087 let first_hops = vec![first_hop];
8089 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8090 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8091 &Default::default(), &random_seed_bytes).unwrap();
8092 assert_eq!(route.paths.len(), 1);
8093 assert_eq!(route.get_total_amount(), amt_msat);
8094 assert_eq!(route.paths[0].hops.len(), 2);
8095 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8096 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8097 assert_eq!(route.get_total_fees(), 123);
8101 fn allow_us_being_first_hint() {
8102 // Check that we consider a route hint even if we are the src of the first hop.
8103 let secp_ctx = Secp256k1::new();
8104 let logger = Arc::new(ln_test_utils::TestLogger::new());
8105 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8106 let scorer = ln_test_utils::TestScorer::new();
8107 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8108 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8109 let config = UserConfig::default();
8111 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8113 let amt_msat = 1_000_000;
8114 let dest_node_id = nodes[1];
8116 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8117 let first_hops = vec![first_hop];
8119 let route_hint = RouteHint(vec![RouteHintHop {
8120 src_node_id: our_node_id,
8121 short_channel_id: 44,
8124 proportional_millionths: 0,
8126 cltv_expiry_delta: 10,
8127 htlc_minimum_msat: None,
8128 htlc_maximum_msat: None,
8131 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8132 .with_route_hints(vec![route_hint]).unwrap()
8133 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8135 let route_params = RouteParameters::from_payment_params_and_value(
8136 payment_params, amt_msat);
8139 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8140 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8141 &Default::default(), &random_seed_bytes).unwrap();
8143 assert_eq!(route.paths.len(), 1);
8144 assert_eq!(route.get_total_amount(), amt_msat);
8145 assert_eq!(route.get_total_fees(), 0);
8146 assert_eq!(route.paths[0].hops.len(), 1);
8148 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8152 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8153 pub(crate) mod bench_utils {
8157 use bitcoin::hashes::Hash;
8158 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8160 use crate::chain::transaction::OutPoint;
8161 use crate::routing::scoring::ScoreUpdate;
8162 use crate::sign::{EntropySource, KeysManager};
8163 use crate::ln::ChannelId;
8164 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8165 use crate::ln::features::Bolt11InvoiceFeatures;
8166 use crate::routing::gossip::NetworkGraph;
8167 use crate::util::config::UserConfig;
8168 use crate::util::ser::ReadableArgs;
8169 use crate::util::test_utils::TestLogger;
8171 /// Tries to open a network graph file, or panics with a URL to fetch it.
8172 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8173 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8174 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8175 .or_else(|_| { // Fall back to guessing based on the binary location
8176 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8177 let mut path = std::env::current_exe().unwrap();
8178 path.pop(); // lightning-...
8180 path.pop(); // debug
8181 path.pop(); // target
8182 path.push("lightning");
8183 path.push("net_graph-2023-01-18.bin");
8186 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8187 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8188 let mut path = std::env::current_exe().unwrap();
8189 path.pop(); // bench...
8191 path.pop(); // debug
8192 path.pop(); // target
8193 path.pop(); // bench
8194 path.push("lightning");
8195 path.push("net_graph-2023-01-18.bin");
8198 .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");
8199 #[cfg(require_route_graph_test)]
8200 return Ok(res.unwrap());
8201 #[cfg(not(require_route_graph_test))]
8205 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8206 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8209 pub(crate) fn payer_pubkey() -> PublicKey {
8210 let secp_ctx = Secp256k1::new();
8211 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8215 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8217 channel_id: ChannelId::new_zero(),
8218 counterparty: ChannelCounterparty {
8219 features: channelmanager::provided_init_features(&UserConfig::default()),
8221 unspendable_punishment_reserve: 0,
8222 forwarding_info: None,
8223 outbound_htlc_minimum_msat: None,
8224 outbound_htlc_maximum_msat: None,
8226 funding_txo: Some(OutPoint {
8227 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8230 short_channel_id: Some(1),
8231 inbound_scid_alias: None,
8232 outbound_scid_alias: None,
8233 channel_value_satoshis: 10_000_000_000,
8235 balance_msat: 10_000_000_000,
8236 outbound_capacity_msat: 10_000_000_000,
8237 next_outbound_htlc_minimum_msat: 0,
8238 next_outbound_htlc_limit_msat: 10_000_000_000,
8239 inbound_capacity_msat: 0,
8240 unspendable_punishment_reserve: None,
8241 confirmations_required: None,
8242 confirmations: None,
8243 force_close_spend_delay: None,
8245 is_channel_ready: true,
8248 inbound_htlc_minimum_msat: None,
8249 inbound_htlc_maximum_msat: None,
8251 feerate_sat_per_1000_weight: None,
8252 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8256 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8257 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8258 starting_amount: u64, route_count: usize,
8259 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8260 let payer = payer_pubkey();
8261 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8262 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8264 let nodes = graph.read_only().nodes().clone();
8265 let mut route_endpoints = Vec::new();
8266 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8267 // with some routes we picked being un-routable.
8268 for _ in 0..route_count * 3 / 2 {
8270 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8271 let src = PublicKey::from_slice(nodes.unordered_keys()
8272 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8273 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8274 let dst = PublicKey::from_slice(nodes.unordered_keys()
8275 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8276 let params = PaymentParameters::from_node_id(dst, 42)
8277 .with_bolt11_features(features.clone()).unwrap();
8278 let first_hop = first_hop(src);
8279 let amt_msat = starting_amount + seed % 1_000_000;
8280 let route_params = RouteParameters::from_payment_params_and_value(
8281 params.clone(), amt_msat);
8283 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8284 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8286 // ...and seed the scorer with success and failure data...
8287 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8288 let mut score_amt = seed % 1_000_000_000;
8290 // Generate fail/success paths for a wider range of potential amounts with
8291 // MPP enabled to give us a chance to apply penalties for more potential
8293 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8294 let params = PaymentParameters::from_node_id(dst, 42)
8295 .with_bolt11_features(mpp_features).unwrap();
8296 let route_params = RouteParameters::from_payment_params_and_value(
8297 params.clone(), score_amt);
8298 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8299 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8300 &random_seed_bytes);
8301 if let Ok(route) = route_res {
8302 for path in route.paths {
8303 if seed & 0x80 == 0 {
8304 scorer.payment_path_successful(&path);
8306 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8307 scorer.payment_path_failed(&path, short_channel_id);
8309 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8313 // If we couldn't find a path with a higer amount, reduce and try again.
8317 route_endpoints.push((first_hop, params, amt_msat));
8323 // Because we've changed channel scores, it's possible we'll take different routes to the
8324 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8325 // requires a too-high CLTV delta.
8326 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8327 let route_params = RouteParameters::from_payment_params_and_value(
8328 params.clone(), *amt_msat);
8329 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8330 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8332 route_endpoints.truncate(route_count);
8333 assert_eq!(route_endpoints.len(), route_count);
8341 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8342 use crate::sign::{EntropySource, KeysManager};
8343 use crate::ln::channelmanager;
8344 use crate::ln::features::Bolt11InvoiceFeatures;
8345 use crate::routing::gossip::NetworkGraph;
8346 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8347 use crate::util::config::UserConfig;
8348 use crate::util::logger::{Logger, Record};
8349 use crate::util::test_utils::TestLogger;
8351 use criterion::Criterion;
8353 struct DummyLogger {}
8354 impl Logger for DummyLogger {
8355 fn log(&self, _record: Record) {}
8358 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8359 let logger = TestLogger::new();
8360 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8361 let scorer = FixedPenaltyScorer::with_penalty(0);
8362 generate_routes(bench, &network_graph, scorer, &Default::default(),
8363 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8366 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8367 let logger = TestLogger::new();
8368 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8369 let scorer = FixedPenaltyScorer::with_penalty(0);
8370 generate_routes(bench, &network_graph, scorer, &Default::default(),
8371 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8372 "generate_mpp_routes_with_zero_penalty_scorer");
8375 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8376 let logger = TestLogger::new();
8377 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8378 let params = ProbabilisticScoringFeeParameters::default();
8379 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8380 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8381 "generate_routes_with_probabilistic_scorer");
8384 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8385 let logger = TestLogger::new();
8386 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8387 let params = ProbabilisticScoringFeeParameters::default();
8388 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8389 generate_routes(bench, &network_graph, scorer, ¶ms,
8390 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8391 "generate_mpp_routes_with_probabilistic_scorer");
8394 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8395 let logger = TestLogger::new();
8396 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8397 let params = ProbabilisticScoringFeeParameters::default();
8398 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8399 generate_routes(bench, &network_graph, scorer, ¶ms,
8400 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8401 "generate_large_mpp_routes_with_probabilistic_scorer");
8404 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8405 let logger = TestLogger::new();
8406 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8407 let mut params = ProbabilisticScoringFeeParameters::default();
8408 params.linear_success_probability = false;
8409 let scorer = ProbabilisticScorer::new(
8410 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8411 generate_routes(bench, &network_graph, scorer, ¶ms,
8412 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8413 "generate_routes_with_nonlinear_probabilistic_scorer");
8416 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8417 let logger = TestLogger::new();
8418 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8419 let mut params = ProbabilisticScoringFeeParameters::default();
8420 params.linear_success_probability = false;
8421 let scorer = ProbabilisticScorer::new(
8422 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8423 generate_routes(bench, &network_graph, scorer, ¶ms,
8424 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8425 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8428 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8429 let logger = TestLogger::new();
8430 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8431 let mut params = ProbabilisticScoringFeeParameters::default();
8432 params.linear_success_probability = false;
8433 let scorer = ProbabilisticScorer::new(
8434 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8435 generate_routes(bench, &network_graph, scorer, ¶ms,
8436 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8437 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8440 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8441 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8442 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8443 bench_name: &'static str,
8445 let payer = bench_utils::payer_pubkey();
8446 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8447 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8449 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8450 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8452 // ...then benchmark finding paths between the nodes we learned.
8454 bench.bench_function(bench_name, |b| b.iter(|| {
8455 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8456 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8457 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8458 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());