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 #[repr(align(64))] // Force the size to 64 bytes
972 struct RouteGraphNode {
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 total_cltv_delta: u32,
982 /// The number of hops walked up to this node.
983 path_length_to_node: u8,
986 impl cmp::Ord for RouteGraphNode {
987 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
988 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
992 impl cmp::PartialOrd for RouteGraphNode {
993 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
994 Some(self.cmp(other))
998 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
999 // substantially when it is laid out at exactly 64 bytes.
1000 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1001 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1003 /// A wrapper around the various hop representations.
1005 /// Can be used to examine the properties of a hop,
1006 /// potentially to decide whether to include it in a route.
1007 #[derive(Clone, Debug)]
1008 pub enum CandidateRouteHop<'a> {
1009 /// A hop from the payer, where the outbound liquidity is known.
1011 /// Channel details of the first hop
1013 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1014 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1016 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1017 details: &'a ChannelDetails,
1018 /// The node id of the payer, which is also the source side of this candidate route hop.
1019 payer_node_id: &'a NodeId,
1021 payer_node_counter: u32,
1023 target_node_counter: u32,
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 source_node_counter: u32,
1046 target_node_counter: u32,
1048 /// A blinded path which starts with an introduction point and ultimately terminates with the
1051 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1052 /// `None` in this state.
1054 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1055 /// path, the full path is treated as a single [`CandidateRouteHop`].
1057 /// Information about the blinded path including the fee, HTLC amount limits, and
1058 /// cryptographic material required to build an HTLC through the given path.
1059 hint: &'a (BlindedPayInfo, BlindedPath),
1060 /// Index of the hint in the original list of blinded hints.
1062 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1063 /// a short channel ID for this hop.
1066 source_node_counter: u32,
1068 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1070 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1071 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1072 /// payee's identity - it's the introduction point!
1074 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1075 /// to the hops *between* the introduction node and the destination.
1077 /// This primarily exists to track that we need to included a blinded path at the end of our
1078 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1080 /// Information about the blinded path including the fee, HTLC amount limits, and
1081 /// cryptographic material required to build an HTLC terminating with the given path.
1083 /// Note that the [`BlindedPayInfo`] is ignored here.
1084 hint: &'a (BlindedPayInfo, BlindedPath),
1085 /// Index of the hint in the original list of blinded hints.
1087 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1088 /// a short channel ID for this hop.
1091 source_node_counter: u32,
1095 impl<'a> CandidateRouteHop<'a> {
1096 /// Returns the short channel ID for this hop, if one is known.
1098 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1099 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1101 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1102 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1103 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1104 /// (which is always true for channels which are funded and ready for use).
1106 /// In other words, this should always return `Some` as long as the candidate hop is not a
1107 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1109 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1110 /// define a global namespace.
1112 fn short_channel_id(&self) -> Option<u64> {
1114 CandidateRouteHop::FirstHop { details, .. } => details.get_outbound_payment_scid(),
1115 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1116 CandidateRouteHop::PrivateHop { hint, .. } => Some(hint.short_channel_id),
1117 CandidateRouteHop::Blinded { .. } => None,
1118 CandidateRouteHop::OneHopBlinded { .. } => None,
1122 /// Returns the globally unique short channel ID for this hop, if one is known.
1124 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1125 /// from the public network graph), and thus the short channel ID we have for this channel is
1126 /// globally unique and identifies this channel in a global namespace.
1128 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1130 CandidateRouteHop::FirstHop { details, .. } => if details.is_public { details.short_channel_id } else { None },
1131 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1132 CandidateRouteHop::PrivateHop { .. } => None,
1133 CandidateRouteHop::Blinded { .. } => None,
1134 CandidateRouteHop::OneHopBlinded { .. } => None,
1138 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1139 fn features(&self) -> ChannelFeatures {
1141 CandidateRouteHop::FirstHop { details, .. } => details.counterparty.features.to_context(),
1142 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1143 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1144 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1145 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1149 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1150 /// next-hop for an HTLC taking this hop.
1152 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1153 /// next-hop goes on chain with a payment preimage.
1155 pub fn cltv_expiry_delta(&self) -> u32 {
1157 CandidateRouteHop::FirstHop { .. } => 0,
1158 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1159 CandidateRouteHop::PrivateHop { hint, .. } => hint.cltv_expiry_delta as u32,
1160 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1161 CandidateRouteHop::OneHopBlinded { .. } => 0,
1165 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1167 pub fn htlc_minimum_msat(&self) -> u64 {
1169 CandidateRouteHop::FirstHop { details, .. } => details.next_outbound_htlc_minimum_msat,
1170 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1171 CandidateRouteHop::PrivateHop { hint, .. } => hint.htlc_minimum_msat.unwrap_or(0),
1172 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1173 CandidateRouteHop::OneHopBlinded { .. } => 0,
1178 fn src_node_counter(&self) -> u32 {
1180 CandidateRouteHop::FirstHop { payer_node_counter, .. } => *payer_node_counter,
1181 CandidateRouteHop::PublicHop { info, .. } => info.source_counter(),
1182 CandidateRouteHop::PrivateHop { source_node_counter, .. } => *source_node_counter,
1183 CandidateRouteHop::Blinded { source_node_counter, .. } => *source_node_counter,
1184 CandidateRouteHop::OneHopBlinded { source_node_counter, .. } => *source_node_counter,
1189 fn target_node_counter(&self) -> Option<u32> {
1191 CandidateRouteHop::FirstHop { target_node_counter, .. } => Some(*target_node_counter),
1192 CandidateRouteHop::PublicHop { info, .. } => Some(info.target_counter()),
1193 CandidateRouteHop::PrivateHop { target_node_counter, .. } => Some(*target_node_counter),
1194 CandidateRouteHop::Blinded { .. } => None,
1195 CandidateRouteHop::OneHopBlinded { .. } => None,
1199 /// Returns the fees that must be paid to route an HTLC over this channel.
1201 pub fn fees(&self) -> RoutingFees {
1203 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1204 base_msat: 0, proportional_millionths: 0,
1206 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1207 CandidateRouteHop::PrivateHop { hint, .. } => hint.fees,
1208 CandidateRouteHop::Blinded { hint, .. } => {
1210 base_msat: hint.0.fee_base_msat,
1211 proportional_millionths: hint.0.fee_proportional_millionths
1214 CandidateRouteHop::OneHopBlinded { .. } =>
1215 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1219 /// Fetch the effective capacity of this hop.
1221 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1223 fn effective_capacity(&self) -> EffectiveCapacity {
1225 CandidateRouteHop::FirstHop { details, .. } => EffectiveCapacity::ExactLiquidity {
1226 liquidity_msat: details.next_outbound_htlc_limit_msat,
1228 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1229 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. } =>
1230 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1231 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. } =>
1232 EffectiveCapacity::Infinite,
1233 CandidateRouteHop::Blinded { hint, .. } =>
1234 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1235 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1239 /// Returns an ID describing the given hop.
1241 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1243 fn id(&self) -> CandidateHopId {
1245 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1246 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1247 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1250 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1252 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1258 /// Returns the source node id of current hop.
1260 /// Source node id refers to the node forwarding the HTLC through this hop.
1262 /// For [`Self::FirstHop`] we return payer's node id.
1264 pub fn source(&self) -> NodeId {
1266 CandidateRouteHop::FirstHop { payer_node_id, .. } => **payer_node_id,
1267 CandidateRouteHop::PublicHop { info, .. } => *info.source(),
1268 CandidateRouteHop::PrivateHop { hint, .. } => hint.src_node_id.into(),
1269 CandidateRouteHop::Blinded { hint, .. } => hint.1.introduction_node_id.into(),
1270 CandidateRouteHop::OneHopBlinded { hint, .. } => hint.1.introduction_node_id.into(),
1273 /// Returns the target node id of this hop, if known.
1275 /// Target node id refers to the node receiving the HTLC after this hop.
1277 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1278 /// path is unknown.
1280 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1281 /// and such a return value would be somewhat nonsensical.
1283 pub fn target(&self) -> Option<NodeId> {
1285 CandidateRouteHop::FirstHop { details, .. } => Some(details.counterparty.node_id.into()),
1286 CandidateRouteHop::PublicHop { info, .. } => Some(*info.target()),
1287 CandidateRouteHop::PrivateHop { target_node_id, .. } => Some(**target_node_id),
1288 CandidateRouteHop::Blinded { .. } => None,
1289 CandidateRouteHop::OneHopBlinded { .. } => None,
1294 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1296 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1298 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1299 /// isn't guaranteed to be unique at all.
1301 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1302 /// difficult-to-use API.
1303 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1304 enum CandidateHopId {
1305 /// Contains (scid, src_node_id < target_node_id)
1307 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1312 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1313 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1315 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1316 EffectiveCapacity::Infinite => u64::max_value(),
1317 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1318 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1319 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1320 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1321 // expected to have been generated from up-to-date capacity information.
1322 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1323 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1324 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1328 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1329 -> bool where I1::Item: PartialEq<I2::Item> {
1331 let a = iter_a.next();
1332 let b = iter_b.next();
1333 if a.is_none() && b.is_none() { return true; }
1334 if a.is_none() || b.is_none() { return false; }
1335 if a.unwrap().ne(&b.unwrap()) { return false; }
1339 /// It's useful to keep track of the hops associated with the fees required to use them,
1340 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1341 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1342 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1345 struct PathBuildingHop<'a> {
1346 candidate: CandidateRouteHop<'a>,
1347 target_node_counter: Option<u32>,
1348 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1349 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1350 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1351 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1352 /// avoid processing them again.
1353 was_processed: bool,
1355 is_first_hop_target: bool,
1356 /// Used to compare channels when choosing the for routing.
1357 /// Includes paying for the use of a hop and the following hops, as well as
1358 /// an estimated cost of reaching this hop.
1359 /// Might get stale when fees are recomputed. Primarily for internal use.
1360 total_fee_msat: u64,
1361 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1362 /// walk and may be invalid thereafter.
1363 path_htlc_minimum_msat: u64,
1364 /// All penalties incurred from this channel on the way to the destination, as calculated using
1365 /// channel scoring.
1366 path_penalty_msat: u64,
1370 /// All the fees paid *after* this channel on the way to the destination
1371 next_hops_fee_msat: u64,
1372 /// Fee paid for the use of the current channel (see candidate.fees()).
1373 /// The value will be actually deducted from the counterparty balance on the previous link.
1374 hop_use_fee_msat: u64,
1376 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1377 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1378 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1379 // value_contribution_msat, which requires tracking it here. See comments below where it is
1380 // used for more info.
1381 value_contribution_msat: u64,
1384 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<Option<PathBuildingHop>>();
1385 const _NODE_MAP_SIZE_EXACTLY_TWO_CACHE_LINES: usize = core::mem::size_of::<Option<PathBuildingHop>>() - 128;
1387 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1388 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1389 let mut debug_struct = f.debug_struct("PathBuildingHop");
1391 .field("source_node_id", &self.candidate.source())
1392 .field("target_node_id", &self.candidate.target())
1393 .field("short_channel_id", &self.candidate.short_channel_id())
1394 .field("total_fee_msat", &self.total_fee_msat)
1395 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1396 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1397 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat.saturating_sub(self.next_hops_fee_msat).saturating_sub(self.hop_use_fee_msat)))
1398 .field("path_penalty_msat", &self.path_penalty_msat)
1399 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1400 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1401 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1402 let debug_struct = debug_struct
1403 .field("value_contribution_msat", &self.value_contribution_msat);
1404 debug_struct.finish()
1408 // Instantiated with a list of hops with correct data in them collected during path finding,
1409 // an instance of this struct should be further modified only via given methods.
1411 struct PaymentPath<'a> {
1412 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1415 impl<'a> PaymentPath<'a> {
1416 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1417 fn get_value_msat(&self) -> u64 {
1418 self.hops.last().unwrap().0.fee_msat
1421 fn get_path_penalty_msat(&self) -> u64 {
1422 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1425 fn get_total_fee_paid_msat(&self) -> u64 {
1426 if self.hops.len() < 1 {
1430 // Can't use next_hops_fee_msat because it gets outdated.
1431 for (i, (hop, _)) in self.hops.iter().enumerate() {
1432 if i != self.hops.len() - 1 {
1433 result += hop.fee_msat;
1439 fn get_cost_msat(&self) -> u64 {
1440 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1443 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1444 // to change fees may result in an inconsistency.
1446 // Sometimes we call this function right after constructing a path which is inconsistent in
1447 // that it the value being transferred has decreased while we were doing path finding, leading
1448 // to the fees being paid not lining up with the actual limits.
1450 // Note that this function is not aware of the available_liquidity limit, and thus does not
1451 // support increasing the value being transferred beyond what was selected during the initial
1454 // Returns the amount that this path contributes to the total payment value, which may be greater
1455 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1456 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1457 let mut extra_contribution_msat = 0;
1458 let mut total_fee_paid_msat = 0 as u64;
1459 for i in (0..self.hops.len()).rev() {
1460 let last_hop = i == self.hops.len() - 1;
1462 // For non-last-hop, this value will represent the fees paid on the current hop. It
1463 // will consist of the fees for the use of the next hop, and extra fees to match
1464 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1465 let mut cur_hop_fees_msat = 0;
1467 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1470 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1471 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1472 cur_hop.path_penalty_msat += extra_contribution_msat;
1473 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1474 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1475 // set it too high just to maliciously take more fees by exploiting this
1476 // match htlc_minimum_msat logic.
1477 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1478 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1479 // Note that there is a risk that *previous hops* (those closer to us, as we go
1480 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1482 // This might make us end up with a broken route, although this should be super-rare
1483 // in practice, both because of how healthy channels look like, and how we pick
1484 // channels in add_entry.
1485 // Also, this can't be exploited more heavily than *announce a free path and fail
1487 cur_hop_transferred_amount_msat += extra_fees_msat;
1489 // We remember and return the extra fees on the final hop to allow accounting for
1490 // them in the path's value contribution.
1492 extra_contribution_msat = extra_fees_msat;
1494 total_fee_paid_msat += extra_fees_msat;
1495 cur_hop_fees_msat += extra_fees_msat;
1500 // Final hop is a special case: it usually has just value_msat (by design), but also
1501 // it still could overpay for the htlc_minimum_msat.
1502 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1504 // Propagate updated fees for the use of the channels to one hop back, where they
1505 // will be actually paid (fee_msat). The last hop is handled above separately.
1506 cur_hop.fee_msat = cur_hop_fees_msat;
1509 // Fee for the use of the current hop which will be deducted on the previous hop.
1510 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1511 // this channel is free for us.
1513 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1514 cur_hop.hop_use_fee_msat = new_fee;
1515 total_fee_paid_msat += new_fee;
1517 // It should not be possible because this function is called only to reduce the
1518 // value. In that case, compute_fee was already called with the same fees for
1519 // larger amount and there was no overflow.
1524 value_msat + extra_contribution_msat
1529 /// Calculate the fees required to route the given amount over a channel with the given fees.
1530 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1531 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1532 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1536 /// Calculate the fees required to route the given amount over a channel with the given fees,
1537 /// saturating to [`u64::max_value`].
1538 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1539 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1540 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1541 .saturating_add(channel_fees.base_msat as u64)
1544 /// The default `features` we assume for a node in a route, when no `features` are known about that
1547 /// Default features are:
1548 /// * variable_length_onion_optional
1549 fn default_node_features() -> NodeFeatures {
1550 let mut features = NodeFeatures::empty();
1551 features.set_variable_length_onion_optional();
1555 struct LoggedPayeePubkey(Option<PublicKey>);
1556 impl fmt::Display for LoggedPayeePubkey {
1557 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1560 "payee node id ".fmt(f)?;
1564 "blinded payee".fmt(f)
1570 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1571 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1572 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1574 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1575 "blinded route hint with introduction node id ".fmt(f)?;
1576 hint.1.introduction_node_id.fmt(f)?;
1577 " and blinding point ".fmt(f)?;
1578 hint.1.blinding_point.fmt(f)
1580 CandidateRouteHop::FirstHop { .. } => {
1581 "first hop with SCID ".fmt(f)?;
1582 self.0.short_channel_id().unwrap().fmt(f)
1584 CandidateRouteHop::PrivateHop { .. } => {
1585 "route hint with SCID ".fmt(f)?;
1586 self.0.short_channel_id().unwrap().fmt(f)
1590 self.0.short_channel_id().unwrap().fmt(f)
1597 fn sort_first_hop_channels(
1598 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1599 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1601 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1602 // most like to use.
1604 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1605 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1608 // Second, because simply always sorting in descending order would always use our largest
1609 // available outbound capacity, needlessly fragmenting our available channel capacities,
1610 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1611 // which have enough, but not too much, capacity for the payment.
1613 // Available outbound balances factor in liquidity already reserved for previously found paths.
1614 channels.sort_unstable_by(|chan_a, chan_b| {
1615 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1616 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1617 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1618 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1619 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1620 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1621 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1622 // Sort in descending order
1623 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1625 // Sort in ascending order
1626 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1631 /// Finds a route from us (payer) to the given target node (payee).
1633 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1634 /// in the given [`RouteParameters::payment_params`].
1635 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1637 /// Private routing paths between a public node and the target may be included in the `payee` field
1638 /// of [`RouteParameters::payment_params`].
1640 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1641 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1642 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1644 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1645 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1646 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1650 /// Panics if first_hops contains channels without `short_channel_id`s;
1651 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1653 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1654 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1655 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1656 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1657 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1658 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1659 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1660 ) -> Result<Route, LightningError>
1661 where L::Target: Logger, GL::Target: Logger {
1662 let graph_lock = network_graph.read_only();
1663 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1664 scorer, score_params, random_seed_bytes)?;
1665 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1669 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1670 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1671 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1672 _random_seed_bytes: &[u8; 32]
1673 ) -> Result<Route, LightningError>
1674 where L::Target: Logger {
1676 let payment_params = &route_params.payment_params;
1677 let final_value_msat = route_params.final_value_msat;
1678 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1679 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1680 // so use a dummy id for this in the blinded case.
1681 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1682 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1683 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1684 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1685 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1687 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1688 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1690 if our_node_id == maybe_dummy_payee_node_id {
1691 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1694 if final_value_msat > MAX_VALUE_MSAT {
1695 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1698 if final_value_msat == 0 {
1699 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1702 match &payment_params.payee {
1703 Payee::Clear { route_hints, node_id, .. } => {
1704 for route in route_hints.iter() {
1705 for hop in &route.0 {
1706 if hop.src_node_id == *node_id {
1707 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1712 Payee::Blinded { route_hints, .. } => {
1713 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1714 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});
1716 for (_, blinded_path) in route_hints.iter() {
1717 if blinded_path.blinded_hops.len() == 0 {
1718 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1719 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1720 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1721 } else if blinded_path.blinded_hops.len() == 1 &&
1722 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1723 && p.introduction_node_id != blinded_path.introduction_node_id)
1725 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1730 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1731 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1732 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});
1735 // The general routing idea is the following:
1736 // 1. Fill first/last hops communicated by the caller.
1737 // 2. Attempt to construct a path from payer to payee for transferring
1738 // any ~sufficient (described later) value.
1739 // If succeed, remember which channels were used and how much liquidity they have available,
1740 // so that future paths don't rely on the same liquidity.
1741 // 3. Proceed to the next step if:
1742 // - we hit the recommended target value;
1743 // - OR if we could not construct a new path. Any next attempt will fail too.
1744 // Otherwise, repeat step 2.
1745 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1746 // (not recommended value).
1747 // 5. If yes, proceed. If not, fail routing.
1748 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1749 // transferred up to the transfer target value.
1750 // 7. Reduce the value of the last path until we are sending only the target value.
1751 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1752 // them so that we're not sending two HTLCs along the same path.
1754 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1755 // distance from the payee
1757 // We are not a faithful Dijkstra's implementation because we can change values which impact
1758 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1759 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1760 // the value we are currently attempting to send over a path, we simply reduce the value being
1761 // sent along the path for any hops after that channel. This may imply that later fees (which
1762 // we've already tabulated) are lower because a smaller value is passing through the channels
1763 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1764 // channels which were selected earlier (and which may still be used for other paths without a
1765 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1768 // One potentially problematic case for this algorithm would be if there are many
1769 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1770 // graph walking), we may never find a path which is not liquidity-limited and has lower
1771 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1772 // Because we only consider paths with at least 5% of the total value being sent, the damage
1773 // from such a case should be limited, however this could be further reduced in the future by
1774 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1775 // limits for the purposes of fee calculation.
1777 // Alternatively, we could store more detailed path information in the heap (targets, below)
1778 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1779 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1780 // and practically (as we would need to store dynamically-allocated path information in heap
1781 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1782 // results of such an algorithm would likely be biased towards lower-value paths.
1784 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1785 // outside of our current search value, running a path search more times to gather candidate
1786 // paths at different values. While this may be acceptable, further path searches may increase
1787 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1788 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1789 // the same time, remaining generic across different payment values.
1791 let network_channels = network_graph.channels();
1792 let network_nodes = network_graph.nodes();
1794 if payment_params.max_path_count == 0 {
1795 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1798 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1799 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1801 let allow_mpp = if payment_params.max_path_count == 1 {
1803 } else if payment_params.payee.supports_basic_mpp() {
1805 } else if let Some(payee) = payee_node_id_opt {
1806 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1807 |info| info.features.supports_basic_mpp()))
1810 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1812 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1813 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1814 if allow_mpp { "with" } else { "without" },
1815 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1816 max_total_routing_fee_msat);
1818 let private_hop_targets_node_counter_offset = network_graph.max_node_counter() + 2;
1819 let mut private_node_id_to_node_counter = HashMap::new();
1821 let mut private_hop_key_cache = HashMap::with_capacity(
1822 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
1825 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
1826 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
1827 // we'll need here and simply fetch them when routing.
1828 let payee_node_counter = payee_node_id_opt
1829 .and_then(|payee| network_nodes.get(&payee))
1830 .map(|node| node.node_counter)
1831 .unwrap_or(private_hop_targets_node_counter_offset);
1832 private_node_id_to_node_counter.insert(maybe_dummy_payee_node_id, payee_node_counter);
1833 private_hop_key_cache.insert(maybe_dummy_payee_pk, (NodeId::from_pubkey(&maybe_dummy_payee_pk), payee_node_counter));
1835 for route in payment_params.payee.unblinded_route_hints().iter() {
1836 for hop in route.0.iter() {
1837 let hop_node_id = NodeId::from_pubkey(&hop.src_node_id);
1838 let node_counter = if let Some(node) = network_nodes.get(&hop_node_id) {
1841 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
1842 *private_node_id_to_node_counter.entry(hop_node_id)
1843 .or_insert(next_node_counter)
1845 private_hop_key_cache.insert(hop.src_node_id, (hop_node_id, node_counter));
1850 // Prepare the data we'll use for payee-to-payer search by
1851 // inserting first hops suggested by the caller as targets.
1852 // Our search will then attempt to reach them while traversing from the payee node.
1853 let mut first_hop_targets: HashMap<_, (Vec<&ChannelDetails>, u32)> =
1854 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1855 if let Some(hops) = first_hops {
1857 if chan.get_outbound_payment_scid().is_none() {
1858 panic!("first_hops should be filled in with usable channels, not pending ones");
1860 if chan.counterparty.node_id == *our_node_pubkey {
1861 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1863 let counterparty_node_id = NodeId::from_pubkey(&chan.counterparty.node_id);
1865 .entry(counterparty_node_id)
1866 .or_insert_with(|| {
1867 let node_counter = if let Some(node) = network_nodes.get(&counterparty_node_id) {
1870 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
1871 *private_node_id_to_node_counter.entry(counterparty_node_id)
1872 .or_insert(next_node_counter)
1874 (Vec::new(), node_counter)
1878 if first_hop_targets.is_empty() {
1879 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1883 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1884 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1885 // adding duplicate entries when we find a better path to a given node.
1886 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1888 // Map from node_id to information about the best current path to that node, including feerate
1890 let dist_len = private_hop_targets_node_counter_offset + private_hop_key_cache.len() as u32 + 1;
1891 let mut dist: Vec<Option<PathBuildingHop>> = vec![None; dist_len as usize];
1892 let payer_node_counter = network_nodes
1894 .map(|node| node.node_counter)
1896 private_node_id_to_node_counter.get(&our_node_id).map(|counter| *counter)
1898 .unwrap_or(network_graph.max_node_counter() + 1);
1900 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1901 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1902 // htlc_minimum with extra fees while still finding a cheaper path.
1903 let mut hit_minimum_limit;
1905 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1906 // We start with a path_value of the exact amount we want, and if that generates a route we may
1907 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1908 // amount we want in total across paths, selecting the best subset at the end.
1909 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1910 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1911 let mut path_value_msat = final_value_msat;
1913 // Routing Fragmentation Mitigation heuristic:
1915 // Routing fragmentation across many payment paths increases the overall routing
1916 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1917 // Taking too many smaller paths also increases the chance of payment failure.
1918 // Thus to avoid this effect, we require from our collected links to provide
1919 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1920 // This requirement is currently set to be 1/max_path_count of the payment
1921 // value to ensure we only ever return routes that do not violate this limit.
1922 let minimal_value_contribution_msat: u64 = if allow_mpp {
1923 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1928 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1929 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1930 // drop the requirement by setting this to 0.
1931 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1933 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1934 // determine if the channel can be used by additional MPP paths or to inform path finding
1935 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1936 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1938 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1939 HashMap::with_capacity(network_nodes.len());
1941 // Keeping track of how much value we already collected across other paths. Helps to decide
1942 // when we want to stop looking for new paths.
1943 let mut already_collected_value_msat = 0;
1945 for (_, (channels, _)) in first_hop_targets.iter_mut() {
1946 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1950 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1951 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1953 // Remember how many candidates we ignored to allow for some logging afterwards.
1954 let mut num_ignored_value_contribution: u32 = 0;
1955 let mut num_ignored_path_length_limit: u32 = 0;
1956 let mut num_ignored_cltv_delta_limit: u32 = 0;
1957 let mut num_ignored_previously_failed: u32 = 0;
1958 let mut num_ignored_total_fee_limit: u32 = 0;
1959 let mut num_ignored_avoid_overpayment: u32 = 0;
1960 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
1962 macro_rules! add_entry {
1963 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
1964 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1965 // since that value has to be transferred over this channel.
1966 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
1967 ( $candidate: expr, $next_hops_fee_msat: expr,
1968 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1969 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1970 // We "return" whether we updated the path at the end, and how much we can route via
1971 // this channel, via this:
1972 let mut hop_contribution_amt_msat = None;
1973 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1974 // practice these cases should be caught earlier:
1975 // - for regular channels at channel announcement (TODO)
1976 // - for first and last hops early in get_route
1977 let src_node_id = $candidate.source();
1978 if Some(src_node_id) != $candidate.target() {
1979 let scid_opt = $candidate.short_channel_id();
1980 let effective_capacity = $candidate.effective_capacity();
1981 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1983 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1984 // It may be misleading because we might later choose to reduce the value transferred
1985 // over these channels, and the channel which was insufficient might become sufficient.
1986 // Worst case: we drop a good channel here because it can't cover the high following
1987 // fees caused by one expensive channel, but then this channel could have been used
1988 // if the amount being transferred over this path is lower.
1989 // We do this for now, but this is a subject for removal.
1990 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1991 let cltv_expiry_delta = $candidate.cltv_expiry_delta();
1992 let htlc_minimum_msat = $candidate.htlc_minimum_msat();
1993 let used_liquidity_msat = used_liquidities
1994 .get(&$candidate.id())
1995 .map_or(0, |used_liquidity_msat| {
1996 available_value_contribution_msat = available_value_contribution_msat
1997 .saturating_sub(*used_liquidity_msat);
1998 *used_liquidity_msat
2001 // Verify the liquidity offered by this channel complies to the minimal contribution.
2002 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2003 // Do not consider candidate hops that would exceed the maximum path length.
2004 let path_length_to_node = $next_hops_path_length + 1;
2005 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2007 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2008 // In order to already account for some of the privacy enhancing random CLTV
2009 // expiry delta offset we add on top later, we subtract a rough estimate
2010 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2011 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2012 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2013 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2014 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2015 .saturating_add(cltv_expiry_delta);
2016 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2018 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2019 // Includes paying fees for the use of the following channels.
2020 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2021 Some(result) => result,
2022 // Can't overflow due to how the values were computed right above.
2023 None => unreachable!(),
2025 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2026 let over_path_minimum_msat = amount_to_transfer_over_msat >= htlc_minimum_msat &&
2027 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2029 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2030 let may_overpay_to_meet_path_minimum_msat =
2031 ((amount_to_transfer_over_msat < htlc_minimum_msat &&
2032 recommended_value_msat >= htlc_minimum_msat) ||
2033 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2034 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2036 let payment_failed_on_this_channel = scid_opt.map_or(false,
2037 |scid| payment_params.previously_failed_channels.contains(&scid));
2039 let (should_log_candidate, first_hop_details) = match $candidate {
2040 CandidateRouteHop::FirstHop { details, .. } => (true, Some(details)),
2041 CandidateRouteHop::PrivateHop { .. } => (true, None),
2042 CandidateRouteHop::Blinded { .. } => (true, None),
2043 CandidateRouteHop::OneHopBlinded { .. } => (true, None),
2047 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2048 // bother considering this channel. If retrying with recommended_value_msat may
2049 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2050 // around again with a higher amount.
2051 if !contributes_sufficient_value {
2052 if should_log_candidate {
2053 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2055 if let Some(details) = first_hop_details {
2057 "First hop candidate next_outbound_htlc_limit_msat: {}",
2058 details.next_outbound_htlc_limit_msat,
2062 num_ignored_value_contribution += 1;
2063 } else if exceeds_max_path_length {
2064 if should_log_candidate {
2065 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2067 num_ignored_path_length_limit += 1;
2068 } else if exceeds_cltv_delta_limit {
2069 if should_log_candidate {
2070 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2072 if let Some(_) = first_hop_details {
2074 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2075 hop_total_cltv_delta,
2076 max_total_cltv_expiry_delta,
2080 num_ignored_cltv_delta_limit += 1;
2081 } else if payment_failed_on_this_channel {
2082 if should_log_candidate {
2083 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2085 num_ignored_previously_failed += 1;
2086 } else if may_overpay_to_meet_path_minimum_msat {
2087 if should_log_candidate {
2089 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2090 LoggedCandidateHop(&$candidate));
2092 if let Some(details) = first_hop_details {
2094 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2095 details.next_outbound_htlc_minimum_msat,
2099 num_ignored_avoid_overpayment += 1;
2100 hit_minimum_limit = true;
2101 } else if over_path_minimum_msat {
2102 // Note that low contribution here (limited by available_liquidity_msat)
2103 // might violate htlc_minimum_msat on the hops which are next along the
2104 // payment path (upstream to the payee). To avoid that, we recompute
2105 // path fees knowing the final path contribution after constructing it.
2106 let curr_min = cmp::max(
2107 $next_hops_path_htlc_minimum_msat, htlc_minimum_msat
2109 let candidate_fees = $candidate.fees();
2110 let src_node_counter = $candidate.src_node_counter();
2111 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, candidate_fees)
2112 .saturating_add(curr_min);
2114 let dist_entry = &mut dist[src_node_counter as usize];
2115 let old_entry = if let Some(hop) = dist_entry {
2118 // If there was previously no known way to access the source node
2119 // (recall it goes payee-to-payer) of short_channel_id, first add a
2120 // semi-dummy record just to compute the fees to reach the source node.
2121 // This will affect our decision on selecting short_channel_id
2122 // as a way to reach the $candidate.target() node.
2123 *dist_entry = Some(PathBuildingHop {
2124 candidate: $candidate.clone(),
2125 target_node_counter: None,
2127 next_hops_fee_msat: u64::max_value(),
2128 hop_use_fee_msat: u64::max_value(),
2129 total_fee_msat: u64::max_value(),
2130 path_htlc_minimum_msat,
2131 path_penalty_msat: u64::max_value(),
2132 was_processed: false,
2133 is_first_hop_target: false,
2134 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2135 value_contribution_msat,
2137 dist_entry.as_mut().unwrap()
2140 #[allow(unused_mut)] // We only use the mut in cfg(test)
2141 let mut should_process = !old_entry.was_processed;
2142 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2144 // In test/fuzzing builds, we do extra checks to make sure the skipping
2145 // of already-seen nodes only happens in cases we expect (see below).
2146 if !should_process { should_process = true; }
2150 let mut hop_use_fee_msat = 0;
2151 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2153 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2154 // will have the same effective-fee
2155 if src_node_id != our_node_id {
2156 // Note that `u64::max_value` means we'll always fail the
2157 // `old_entry.total_fee_msat > total_fee_msat` check below
2158 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, candidate_fees);
2159 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2162 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2163 if total_fee_msat > max_total_routing_fee_msat {
2164 if should_log_candidate {
2165 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2167 if let Some(_) = first_hop_details {
2169 "First hop candidate routing fee: {}. Limit: {}",
2171 max_total_routing_fee_msat,
2175 num_ignored_total_fee_limit += 1;
2177 let channel_usage = ChannelUsage {
2178 amount_msat: amount_to_transfer_over_msat,
2179 inflight_htlc_msat: used_liquidity_msat,
2182 let channel_penalty_msat =
2183 scorer.channel_penalty_msat($candidate,
2186 let path_penalty_msat = $next_hops_path_penalty_msat
2187 .saturating_add(channel_penalty_msat);
2189 // Update the way of reaching $candidate.source()
2190 // with the given short_channel_id (from $candidate.target()),
2191 // if this way is cheaper than the already known
2192 // (considering the cost to "reach" this channel from the route destination,
2193 // the cost of using this channel,
2194 // and the cost of routing to the source node of this channel).
2195 // Also, consider that htlc_minimum_msat_difference, because we might end up
2196 // paying it. Consider the following exploit:
2197 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2198 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2199 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2200 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2202 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2203 // but it may require additional tracking - we don't want to double-count
2204 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2205 // can't use something that may decrease on future hops.
2206 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2207 .saturating_add(old_entry.path_penalty_msat);
2208 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2209 .saturating_add(path_penalty_msat);
2211 if !old_entry.was_processed && new_cost < old_cost {
2212 let new_graph_node = RouteGraphNode {
2213 node_id: src_node_id,
2214 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2215 total_cltv_delta: hop_total_cltv_delta,
2216 value_contribution_msat,
2217 path_length_to_node,
2219 targets.push(new_graph_node);
2220 old_entry.target_node_counter = $candidate.target_node_counter();
2221 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2222 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2223 old_entry.total_fee_msat = total_fee_msat;
2224 old_entry.candidate = $candidate.clone();
2225 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2226 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2227 old_entry.path_penalty_msat = path_penalty_msat;
2228 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2230 old_entry.value_contribution_msat = value_contribution_msat;
2232 hop_contribution_amt_msat = Some(value_contribution_msat);
2233 } else if old_entry.was_processed && new_cost < old_cost {
2234 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2236 // If we're skipping processing a node which was previously
2237 // processed even though we found another path to it with a
2238 // cheaper fee, check that it was because the second path we
2239 // found (which we are processing now) has a lower value
2240 // contribution due to an HTLC minimum limit.
2242 // e.g. take a graph with two paths from node 1 to node 2, one
2243 // through channel A, and one through channel B. Channel A and
2244 // B are both in the to-process heap, with their scores set by
2245 // a higher htlc_minimum than fee.
2246 // Channel A is processed first, and the channels onwards from
2247 // node 1 are added to the to-process heap. Thereafter, we pop
2248 // Channel B off of the heap, note that it has a much more
2249 // restrictive htlc_maximum_msat, and recalculate the fees for
2250 // all of node 1's channels using the new, reduced, amount.
2252 // This would be bogus - we'd be selecting a higher-fee path
2253 // with a lower htlc_maximum_msat instead of the one we'd
2254 // already decided to use.
2255 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2257 value_contribution_msat + path_penalty_msat <
2258 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2265 if should_log_candidate {
2267 "Ignoring {} due to its htlc_minimum_msat limit.",
2268 LoggedCandidateHop(&$candidate));
2270 if let Some(details) = first_hop_details {
2272 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2273 details.next_outbound_htlc_minimum_msat,
2277 num_ignored_htlc_minimum_msat_limit += 1;
2281 hop_contribution_amt_msat
2285 let default_node_features = default_node_features();
2287 // Find ways (channels with destination) to reach a given node and store them
2288 // in the corresponding data structures (routing graph etc).
2289 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2290 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2291 // This data can later be helpful to optimize routing (pay lower fees).
2292 macro_rules! add_entries_to_cheapest_to_target_node {
2293 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2294 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2295 let fee_to_target_msat;
2296 let next_hops_path_htlc_minimum_msat;
2297 let next_hops_path_penalty_msat;
2298 let is_first_hop_target;
2299 let skip_node = if let Some(elem) = &mut dist[$node.node_counter as usize] {
2300 let was_processed = elem.was_processed;
2301 elem.was_processed = true;
2302 fee_to_target_msat = elem.total_fee_msat;
2303 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2304 next_hops_path_penalty_msat = elem.path_penalty_msat;
2305 is_first_hop_target = elem.is_first_hop_target;
2308 // Entries are added to dist in add_entry!() when there is a channel from a node.
2309 // Because there are no channels from payee, it will not have a dist entry at this point.
2310 // If we're processing any other node, it is always be the result of a channel from it.
2311 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2313 fee_to_target_msat = 0;
2314 next_hops_path_htlc_minimum_msat = 0;
2315 next_hops_path_penalty_msat = 0;
2316 is_first_hop_target = false;
2321 if is_first_hop_target {
2322 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get(&$node_id) {
2323 for details in first_channels {
2324 debug_assert_eq!(*peer_node_counter, $node.node_counter);
2325 let candidate = CandidateRouteHop::FirstHop {
2326 details, payer_node_id: &our_node_id, payer_node_counter,
2327 target_node_counter: $node.node_counter,
2329 add_entry!(&candidate, fee_to_target_msat,
2330 $next_hops_value_contribution,
2331 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2332 $next_hops_cltv_delta, $next_hops_path_length);
2337 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2340 &default_node_features
2343 if !features.requires_unknown_bits() {
2344 for chan_id in $node.channels.iter() {
2345 let chan = network_channels.get(chan_id).unwrap();
2346 if !chan.features.requires_unknown_bits() {
2347 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2348 if first_hops.is_none() || *source != our_node_id {
2349 if directed_channel.direction().enabled {
2350 let candidate = CandidateRouteHop::PublicHop {
2351 info: directed_channel,
2352 short_channel_id: *chan_id,
2354 add_entry!(&candidate,
2356 $next_hops_value_contribution,
2357 next_hops_path_htlc_minimum_msat,
2358 next_hops_path_penalty_msat,
2359 $next_hops_cltv_delta, $next_hops_path_length);
2370 let mut payment_paths = Vec::<PaymentPath>::new();
2372 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2373 'paths_collection: loop {
2374 // For every new path, start from scratch, except for used_liquidities, which
2375 // helps to avoid reusing previously selected paths in future iterations.
2377 for e in dist.iter_mut() {
2380 for (node_id, (chans, peer_node_counter)) in first_hop_targets.iter() {
2381 // In order to avoid looking up whether each node is a first-hop target, we store a
2382 // dummy entry in dist for each first-hop target, allowing us to do this lookup for
2383 // free since we're already looking at the `was_processed` flag.
2385 // Note that all the fields (except `is_first_hop_target`) will be overwritten whenever
2386 // we find a path to the target, so are left as dummies here.
2387 dist[*peer_node_counter as usize] = Some(PathBuildingHop {
2388 candidate: CandidateRouteHop::FirstHop {
2390 payer_node_id: &our_node_id,
2391 target_node_counter: u32::max_value(),
2392 payer_node_counter: u32::max_value(),
2394 target_node_counter: None,
2396 next_hops_fee_msat: u64::max_value(),
2397 hop_use_fee_msat: u64::max_value(),
2398 total_fee_msat: u64::max_value(),
2399 path_htlc_minimum_msat: u64::max_value(),
2400 path_penalty_msat: u64::max_value(),
2401 was_processed: false,
2402 is_first_hop_target: true,
2403 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2404 value_contribution_msat: 0,
2407 hit_minimum_limit = false;
2409 // If first hop is a private channel and the only way to reach the payee, this is the only
2410 // place where it could be added.
2411 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|(first_channels, peer_node_counter)| {
2412 debug_assert_eq!(*peer_node_counter, payee_node_counter);
2413 for details in first_channels {
2414 let candidate = CandidateRouteHop::FirstHop {
2415 details, payer_node_id: &our_node_id, payer_node_counter,
2416 target_node_counter: payee_node_counter,
2418 let added = add_entry!(&candidate, 0, path_value_msat,
2419 0, 0u64, 0, 0).is_some();
2420 log_trace!(logger, "{} direct route to payee via {}",
2421 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2425 // Add the payee as a target, so that the payee-to-payer
2426 // search algorithm knows what to start with.
2427 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2428 // The payee is not in our network graph, so nothing to add here.
2429 // There is still a chance of reaching them via last_hops though,
2430 // so don't yet fail the payment here.
2431 // If not, targets.pop() will not even let us enter the loop in step 2.
2434 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2439 // If a caller provided us with last hops, add them to routing targets. Since this happens
2440 // earlier than general path finding, they will be somewhat prioritized, although currently
2441 // it matters only if the fees are exactly the same.
2442 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2443 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2444 let intro_node_counter_opt =
2445 // Only add the hops in this route to our candidate set if either
2446 // we have a direct channel to the first hop or the first hop is
2447 // in the regular network graph.
2448 network_nodes.get(&intro_node_id).map(|node| node.node_counter)
2450 first_hop_targets.get(&intro_node_id).map(|(_, node_counter)| *node_counter)
2452 if intro_node_counter_opt.is_none() || our_node_id == intro_node_id { continue }
2453 let candidate = if hint.1.blinded_hops.len() == 1 {
2454 CandidateRouteHop::OneHopBlinded {
2457 source_node_counter: intro_node_counter_opt.unwrap(),
2460 CandidateRouteHop::Blinded {
2463 source_node_counter: intro_node_counter_opt.unwrap(),
2466 let mut path_contribution_msat = path_value_msat;
2467 if let Some(hop_used_msat) = add_entry!(&candidate,
2468 0, path_contribution_msat, 0, 0_u64, 0, 0)
2470 path_contribution_msat = hop_used_msat;
2472 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2473 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2475 for details in first_channels {
2476 let first_hop_candidate = CandidateRouteHop::FirstHop {
2477 details, payer_node_id: &our_node_id, payer_node_counter,
2478 target_node_counter: *peer_node_counter,
2480 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2484 let path_min = candidate.htlc_minimum_msat().saturating_add(
2485 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2486 add_entry!(&first_hop_candidate, blinded_path_fee,
2487 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2488 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2492 for route in payment_params.payee.unblinded_route_hints().iter()
2493 .filter(|route| !route.0.is_empty())
2495 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2496 let first_hop_src_is_reachable =
2497 // Only add the hops in this route to our candidate set if either we are part of
2498 // the first hop, we have a direct channel to the first hop, or the first hop is in
2499 // the regular network graph.
2500 our_node_id == first_hop_src_id ||
2501 first_hop_targets.get(&first_hop_src_id).is_some() ||
2502 network_nodes.get(&first_hop_src_id).is_some();
2503 if first_hop_src_is_reachable {
2504 // We start building the path from reverse, i.e., from payee
2505 // to the first RouteHintHop in the path.
2506 let hop_iter = route.0.iter().rev();
2507 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2508 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2509 let mut hop_used = true;
2510 let mut aggregate_next_hops_fee_msat: u64 = 0;
2511 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2512 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2513 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2514 let mut aggregate_next_hops_path_length: u8 = 0;
2515 let mut aggregate_path_contribution_msat = path_value_msat;
2517 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2518 let (target, private_target_node_counter) = private_hop_key_cache.get(&prev_hop_id).unwrap();
2519 let (_src_id, private_source_node_counter) = private_hop_key_cache.get(&hop.src_node_id).unwrap();
2521 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2522 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2523 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2524 hop.short_channel_id);
2529 let candidate = network_channels
2530 .get(&hop.short_channel_id)
2531 .and_then(|channel| channel.as_directed_to(&target))
2532 .map(|(info, _)| CandidateRouteHop::PublicHop {
2534 short_channel_id: hop.short_channel_id,
2536 .unwrap_or_else(|| CandidateRouteHop::PrivateHop {
2537 hint: hop, target_node_id: target,
2538 source_node_counter: *private_source_node_counter,
2539 target_node_counter: *private_target_node_counter,
2542 if let Some(hop_used_msat) = add_entry!(&candidate,
2543 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2544 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2545 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2547 aggregate_path_contribution_msat = hop_used_msat;
2549 // If this hop was not used then there is no use checking the preceding
2550 // hops in the RouteHint. We can break by just searching for a direct
2551 // channel between last checked hop and first_hop_targets.
2555 let used_liquidity_msat = used_liquidities
2556 .get(&candidate.id()).copied()
2558 let channel_usage = ChannelUsage {
2559 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2560 inflight_htlc_msat: used_liquidity_msat,
2561 effective_capacity: candidate.effective_capacity(),
2563 let channel_penalty_msat = scorer.channel_penalty_msat(
2564 &candidate, channel_usage, score_params
2566 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2567 .saturating_add(channel_penalty_msat);
2569 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2570 .saturating_add(hop.cltv_expiry_delta as u32);
2572 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2575 // Searching for a direct channel between last checked hop and first_hop_targets
2576 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&target) {
2577 sort_first_hop_channels(first_channels, &used_liquidities,
2578 recommended_value_msat, our_node_pubkey);
2579 for details in first_channels {
2580 let first_hop_candidate = CandidateRouteHop::FirstHop {
2581 details, payer_node_id: &our_node_id, payer_node_counter,
2582 target_node_counter: *peer_node_counter,
2584 add_entry!(&first_hop_candidate,
2585 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2586 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2587 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2595 // In the next values of the iterator, the aggregate fees already reflects
2596 // the sum of value sent from payer (final_value_msat) and routing fees
2597 // for the last node in the RouteHint. We need to just add the fees to
2598 // route through the current node so that the preceding node (next iteration)
2600 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2601 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2602 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2604 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2605 // this route hint's source node to forward said min over this channel.
2606 aggregate_next_hops_path_htlc_minimum_msat = {
2607 let curr_htlc_min = cmp::max(
2608 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2610 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2611 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2614 if idx == route.0.len() - 1 {
2615 // The last hop in this iterator is the first hop in
2616 // overall RouteHint.
2617 // If this hop connects to a node with which we have a direct channel,
2618 // ignore the network graph and, if the last hop was added, add our
2619 // direct channel to the candidate set.
2621 // Note that we *must* check if the last hop was added as `add_entry`
2622 // always assumes that the third argument is a node to which we have a
2624 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2625 sort_first_hop_channels(first_channels, &used_liquidities,
2626 recommended_value_msat, our_node_pubkey);
2627 for details in first_channels {
2628 let first_hop_candidate = CandidateRouteHop::FirstHop {
2629 details, payer_node_id: &our_node_id, payer_node_counter,
2630 target_node_counter: *peer_node_counter,
2632 add_entry!(&first_hop_candidate,
2633 aggregate_next_hops_fee_msat,
2634 aggregate_path_contribution_msat,
2635 aggregate_next_hops_path_htlc_minimum_msat,
2636 aggregate_next_hops_path_penalty_msat,
2637 aggregate_next_hops_cltv_delta,
2638 aggregate_next_hops_path_length);
2646 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2648 // At this point, targets are filled with the data from first and
2649 // last hops communicated by the caller, and the payment receiver.
2650 let mut found_new_path = false;
2653 // If this loop terminates due the exhaustion of targets, two situations are possible:
2654 // - not enough outgoing liquidity:
2655 // 0 < already_collected_value_msat < final_value_msat
2656 // - enough outgoing liquidity:
2657 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2658 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2659 // paths_collection will be stopped because found_new_path==false.
2660 // This is not necessarily a routing failure.
2661 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2663 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2664 // traversing the graph and arrange the path out of what we found.
2665 if node_id == our_node_id {
2666 let mut new_entry = dist[payer_node_counter as usize].take().unwrap();
2667 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2670 let mut features_set = false;
2671 let candidate = &ordered_hops.last().unwrap().0.candidate;
2672 let target = candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2673 let target_node_counter = candidate.target_node_counter();
2674 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2675 for details in first_channels {
2676 if let CandidateRouteHop::FirstHop { details: last_hop_details, .. }
2677 = ordered_hops.last().unwrap().0.candidate
2679 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2680 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2681 features_set = true;
2688 if let Some(node) = network_nodes.get(&target) {
2689 if let Some(node_info) = node.announcement_info.as_ref() {
2690 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2692 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2695 // We can fill in features for everything except hops which were
2696 // provided via the invoice we're paying. We could guess based on the
2697 // recipient's features but for now we simply avoid guessing at all.
2701 // Means we succesfully traversed from the payer to the payee, now
2702 // save this path for the payment route. Also, update the liquidity
2703 // remaining on the used hops, so that we take them into account
2704 // while looking for more paths.
2705 if target_node_counter.is_none() {
2708 if target_node_counter == Some(payee_node_counter) { break 'path_walk; }
2710 new_entry = match dist[target_node_counter.unwrap() as usize].take() {
2711 Some(payment_hop) => payment_hop,
2712 // We can't arrive at None because, if we ever add an entry to targets,
2713 // we also fill in the entry in dist (see add_entry!).
2714 None => unreachable!(),
2716 // We "propagate" the fees one hop backward (topologically) here,
2717 // so that fees paid for a HTLC forwarding on the current channel are
2718 // associated with the previous channel (where they will be subtracted).
2719 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2720 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2722 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2723 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2725 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2726 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2728 let mut payment_path = PaymentPath {hops: ordered_hops};
2730 // We could have possibly constructed a slightly inconsistent path: since we reduce
2731 // value being transferred along the way, we could have violated htlc_minimum_msat
2732 // on some channels we already passed (assuming dest->source direction). Here, we
2733 // recompute the fees again, so that if that's the case, we match the currently
2734 // underpaid htlc_minimum_msat with fees.
2735 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2736 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2737 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2739 // Since a path allows to transfer as much value as
2740 // the smallest channel it has ("bottleneck"), we should recompute
2741 // the fees so sender HTLC don't overpay fees when traversing
2742 // larger channels than the bottleneck. This may happen because
2743 // when we were selecting those channels we were not aware how much value
2744 // this path will transfer, and the relative fee for them
2745 // might have been computed considering a larger value.
2746 // Remember that we used these channels so that we don't rely
2747 // on the same liquidity in future paths.
2748 let mut prevented_redundant_path_selection = false;
2749 for (hop, _) in payment_path.hops.iter() {
2750 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2751 let used_liquidity_msat = used_liquidities
2752 .entry(hop.candidate.id())
2753 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2754 .or_insert(spent_on_hop_msat);
2755 let hop_capacity = hop.candidate.effective_capacity();
2756 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2757 if *used_liquidity_msat == hop_max_msat {
2758 // If this path used all of this channel's available liquidity, we know
2759 // this path will not be selected again in the next loop iteration.
2760 prevented_redundant_path_selection = true;
2762 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2764 if !prevented_redundant_path_selection {
2765 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2766 // we'll probably end up picking the same path again on the next iteration.
2767 // Decrease the available liquidity of a hop in the middle of the path.
2768 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2769 let exhausted = u64::max_value();
2771 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2772 LoggedCandidateHop(victim_candidate));
2773 if let Some(scid) = victim_candidate.short_channel_id() {
2774 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2775 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2779 // Track the total amount all our collected paths allow to send so that we know
2780 // when to stop looking for more paths
2781 already_collected_value_msat += value_contribution_msat;
2783 payment_paths.push(payment_path);
2784 found_new_path = true;
2785 break 'path_construction;
2788 // If we found a path back to the payee, we shouldn't try to process it again. This is
2789 // the equivalent of the `elem.was_processed` check in
2790 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2791 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2793 // Otherwise, since the current target node is not us,
2794 // keep "unrolling" the payment graph from payee to payer by
2795 // finding a way to reach the current target from the payer side.
2796 match network_nodes.get(&node_id) {
2799 add_entries_to_cheapest_to_target_node!(node, node_id,
2800 value_contribution_msat,
2801 total_cltv_delta, path_length_to_node);
2807 if !found_new_path && channel_saturation_pow_half != 0 {
2808 channel_saturation_pow_half = 0;
2809 continue 'paths_collection;
2811 // If we don't support MPP, no use trying to gather more value ever.
2812 break 'paths_collection;
2816 // Stop either when the recommended value is reached or if no new path was found in this
2818 // In the latter case, making another path finding attempt won't help,
2819 // because we deterministically terminated the search due to low liquidity.
2820 if !found_new_path && channel_saturation_pow_half != 0 {
2821 channel_saturation_pow_half = 0;
2822 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2823 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2824 path_value_msat = recommended_value_msat;
2825 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2826 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2827 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2828 break 'paths_collection;
2829 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2830 // Further, if this was our first walk of the graph, and we weren't limited by an
2831 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2832 // limited by an htlc_minimum_msat value, find another path with a higher value,
2833 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2834 // still keeping a lower total fee than this path.
2835 if !hit_minimum_limit {
2836 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2837 break 'paths_collection;
2839 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.");
2840 path_value_msat = recommended_value_msat;
2844 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2845 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2846 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2847 num_ignored_total_fee_limit;
2848 if num_ignored_total > 0 {
2850 "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.",
2851 num_ignored_value_contribution, num_ignored_path_length_limit,
2852 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2853 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2854 num_ignored_total_fee_limit, num_ignored_total);
2858 if payment_paths.len() == 0 {
2859 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2862 if already_collected_value_msat < final_value_msat {
2863 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2867 let mut selected_route = payment_paths;
2869 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2870 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2872 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2873 // the value they contribute towards the payment amount.
2874 // We sort in descending order as we will remove from the front in `retain`, next.
2875 selected_route.sort_unstable_by(|a, b|
2876 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2877 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2880 // We should make sure that at least 1 path left.
2881 let mut paths_left = selected_route.len();
2882 selected_route.retain(|path| {
2883 if paths_left == 1 {
2886 let path_value_msat = path.get_value_msat();
2887 if path_value_msat <= overpaid_value_msat {
2888 overpaid_value_msat -= path_value_msat;
2894 debug_assert!(selected_route.len() > 0);
2896 if overpaid_value_msat != 0 {
2898 // Now, subtract the remaining overpaid value from the most-expensive path.
2899 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2900 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2901 selected_route.sort_unstable_by(|a, b| {
2902 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2903 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2904 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2906 let expensive_payment_path = selected_route.first_mut().unwrap();
2908 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2909 // can't go negative.
2910 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2911 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2915 // Sort by the path itself and combine redundant paths.
2916 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2917 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2919 selected_route.sort_unstable_by_key(|path| {
2920 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2921 debug_assert!(path.hops.len() <= key.len());
2922 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2927 for idx in 0..(selected_route.len() - 1) {
2928 if idx + 1 >= selected_route.len() { break; }
2929 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2930 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2931 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2932 selected_route[idx].update_value_and_recompute_fees(new_value);
2933 selected_route.remove(idx + 1);
2937 let mut paths = Vec::new();
2938 for payment_path in selected_route {
2939 let mut hops = Vec::with_capacity(payment_path.hops.len());
2940 for (hop, node_features) in payment_path.hops.iter()
2941 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2943 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2944 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2945 // If we sourced the hop from the graph we're sure the target node is announced.
2947 } else if let CandidateRouteHop::FirstHop { details, .. } = hop.candidate {
2948 // If this is a first hop we also know if it's announced.
2951 // If we sourced it any other way, we double-check the network graph to see if
2952 // there are announced channels between the endpoints. If so, the hop might be
2953 // referring to any of the announced channels, as its `short_channel_id` might be
2954 // an alias, in which case we don't take any chances here.
2955 network_graph.node(&target).map_or(false, |hop_node|
2956 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2957 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
2961 hops.push(RouteHop {
2962 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2963 node_features: node_features.clone(),
2964 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2965 channel_features: hop.candidate.features(),
2966 fee_msat: hop.fee_msat,
2967 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2968 maybe_announced_channel,
2971 let mut final_cltv_delta = final_cltv_expiry_delta;
2972 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2973 if let Some(blinded_path) = h.candidate.blinded_path() {
2974 final_cltv_delta = h.candidate.cltv_expiry_delta();
2976 hops: blinded_path.blinded_hops.clone(),
2977 blinding_point: blinded_path.blinding_point,
2978 excess_final_cltv_expiry_delta: 0,
2979 final_value_msat: h.fee_msat,
2983 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2984 // applicable for the previous hop.
2985 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2986 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2989 paths.push(Path { hops, blinded_tail });
2991 // Make sure we would never create a route with more paths than we allow.
2992 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2994 if let Some(node_features) = payment_params.payee.node_features() {
2995 for path in paths.iter_mut() {
2996 path.hops.last_mut().unwrap().node_features = node_features.clone();
3000 let route = Route { paths, route_params: Some(route_params.clone()) };
3002 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3003 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3004 if route.get_total_fees() > max_total_routing_fee_msat {
3005 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3006 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3010 log_info!(logger, "Got route: {}", log_route!(route));
3014 // When an adversarial intermediary node observes a payment, it may be able to infer its
3015 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3016 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3017 // payment path by adding a randomized 'shadow route' offset to the final hop.
3018 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3019 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3021 let network_channels = network_graph.channels();
3022 let network_nodes = network_graph.nodes();
3024 for path in route.paths.iter_mut() {
3025 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3027 // Remember the last three nodes of the random walk and avoid looping back on them.
3028 // Init with the last three nodes from the actual path, if possible.
3029 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3030 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3031 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3033 // Choose the last publicly known node as the starting point for the random walk.
3034 let mut cur_hop: Option<NodeId> = None;
3035 let mut path_nonce = [0u8; 12];
3036 if let Some(starting_hop) = path.hops.iter().rev()
3037 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3038 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3039 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3042 // Init PRNG with the path-dependant nonce, which is static for private paths.
3043 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3044 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3046 // Pick a random path length in [1 .. 3]
3047 prng.process_in_place(&mut random_path_bytes);
3048 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3050 for random_hop in 0..random_walk_length {
3051 // If we don't find a suitable offset in the public network graph, we default to
3052 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3053 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3055 if let Some(cur_node_id) = cur_hop {
3056 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3057 // Randomly choose the next unvisited hop.
3058 prng.process_in_place(&mut random_path_bytes);
3059 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3060 .checked_rem(cur_node.channels.len())
3061 .and_then(|index| cur_node.channels.get(index))
3062 .and_then(|id| network_channels.get(id)) {
3063 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3064 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3065 nodes_to_avoid[random_hop] = *next_id;
3066 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3067 cur_hop = Some(*next_id);
3074 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3075 .checked_add(random_hop_offset)
3076 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3079 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3080 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3081 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3083 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3084 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3085 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3086 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3087 max_path_offset = cmp::max(
3088 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3089 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3090 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3092 // Add 'shadow' CLTV offset to the final hop
3093 if let Some(tail) = path.blinded_tail.as_mut() {
3094 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3095 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3097 if let Some(last_hop) = path.hops.last_mut() {
3098 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3099 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3104 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3105 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3107 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3108 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3109 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3110 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3111 ) -> Result<Route, LightningError>
3112 where L::Target: Logger, GL::Target: Logger {
3113 let graph_lock = network_graph.read_only();
3114 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3115 &graph_lock, logger, random_seed_bytes)?;
3116 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3120 fn build_route_from_hops_internal<L: Deref>(
3121 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3122 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3123 ) -> Result<Route, LightningError> where L::Target: Logger {
3126 our_node_id: NodeId,
3127 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3130 impl ScoreLookUp for HopScorer {
3131 type ScoreParams = ();
3132 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3133 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3135 let mut cur_id = self.our_node_id;
3136 for i in 0..self.hop_ids.len() {
3137 if let Some(next_id) = self.hop_ids[i] {
3138 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3150 impl<'a> Writeable for HopScorer {
3152 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3157 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3158 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3161 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3162 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3163 for i in 0..hops.len() {
3164 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3167 let scorer = HopScorer { our_node_id, hop_ids };
3169 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3174 use crate::blinded_path::{BlindedHop, BlindedPath};
3175 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3176 use crate::routing::utxo::UtxoResult;
3177 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3178 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3179 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop};
3180 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3181 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3182 use crate::chain::transaction::OutPoint;
3183 use crate::sign::EntropySource;
3184 use crate::ln::ChannelId;
3185 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3186 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3187 use crate::ln::channelmanager;
3188 use crate::offers::invoice::BlindedPayInfo;
3189 use crate::util::config::UserConfig;
3190 use crate::util::test_utils as ln_test_utils;
3191 use crate::util::chacha20::ChaCha20;
3192 use crate::util::ser::{Readable, Writeable};
3194 use crate::util::ser::Writer;
3196 use bitcoin::hashes::Hash;
3197 use bitcoin::network::constants::Network;
3198 use bitcoin::blockdata::constants::ChainHash;
3199 use bitcoin::blockdata::script::Builder;
3200 use bitcoin::blockdata::opcodes;
3201 use bitcoin::blockdata::transaction::TxOut;
3202 use bitcoin::hashes::hex::FromHex;
3203 use bitcoin::secp256k1::{PublicKey,SecretKey};
3204 use bitcoin::secp256k1::Secp256k1;
3206 use crate::io::Cursor;
3207 use crate::prelude::*;
3208 use crate::sync::Arc;
3210 use core::convert::TryInto;
3212 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3213 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3214 channelmanager::ChannelDetails {
3215 channel_id: ChannelId::new_zero(),
3216 counterparty: channelmanager::ChannelCounterparty {
3219 unspendable_punishment_reserve: 0,
3220 forwarding_info: None,
3221 outbound_htlc_minimum_msat: None,
3222 outbound_htlc_maximum_msat: None,
3224 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3227 outbound_scid_alias: None,
3228 inbound_scid_alias: None,
3229 channel_value_satoshis: 0,
3232 outbound_capacity_msat,
3233 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3234 next_outbound_htlc_minimum_msat: 0,
3235 inbound_capacity_msat: 42,
3236 unspendable_punishment_reserve: None,
3237 confirmations_required: None,
3238 confirmations: None,
3239 force_close_spend_delay: None,
3240 is_outbound: true, is_channel_ready: true,
3241 is_usable: true, is_public: true,
3242 inbound_htlc_minimum_msat: None,
3243 inbound_htlc_maximum_msat: None,
3245 feerate_sat_per_1000_weight: None,
3246 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3251 fn simple_route_test() {
3252 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3253 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3254 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3255 let scorer = ln_test_utils::TestScorer::new();
3256 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3257 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3259 // Simple route to 2 via 1
3261 let route_params = RouteParameters::from_payment_params_and_value(
3262 payment_params.clone(), 0);
3263 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3264 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3265 &Default::default(), &random_seed_bytes) {
3266 assert_eq!(err, "Cannot send a payment of 0 msat");
3267 } else { panic!(); }
3269 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3270 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3271 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3272 assert_eq!(route.paths[0].hops.len(), 2);
3274 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3275 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3276 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3277 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3278 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3279 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3281 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3282 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3283 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3284 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3285 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3286 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3290 fn invalid_first_hop_test() {
3291 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3292 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3293 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3294 let scorer = ln_test_utils::TestScorer::new();
3295 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3296 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3298 // Simple route to 2 via 1
3300 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3302 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3303 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3304 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3305 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3306 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3307 } else { panic!(); }
3309 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3310 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3311 assert_eq!(route.paths[0].hops.len(), 2);
3315 fn htlc_minimum_test() {
3316 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3317 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3318 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3319 let scorer = ln_test_utils::TestScorer::new();
3320 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3321 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3323 // Simple route to 2 via 1
3325 // Disable other paths
3326 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3327 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3328 short_channel_id: 12,
3330 flags: 2, // to disable
3331 cltv_expiry_delta: 0,
3332 htlc_minimum_msat: 0,
3333 htlc_maximum_msat: MAX_VALUE_MSAT,
3335 fee_proportional_millionths: 0,
3336 excess_data: Vec::new()
3338 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3339 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3340 short_channel_id: 3,
3342 flags: 2, // to disable
3343 cltv_expiry_delta: 0,
3344 htlc_minimum_msat: 0,
3345 htlc_maximum_msat: MAX_VALUE_MSAT,
3347 fee_proportional_millionths: 0,
3348 excess_data: Vec::new()
3350 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3351 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3352 short_channel_id: 13,
3354 flags: 2, // to disable
3355 cltv_expiry_delta: 0,
3356 htlc_minimum_msat: 0,
3357 htlc_maximum_msat: MAX_VALUE_MSAT,
3359 fee_proportional_millionths: 0,
3360 excess_data: Vec::new()
3362 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3363 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3364 short_channel_id: 6,
3366 flags: 2, // to disable
3367 cltv_expiry_delta: 0,
3368 htlc_minimum_msat: 0,
3369 htlc_maximum_msat: MAX_VALUE_MSAT,
3371 fee_proportional_millionths: 0,
3372 excess_data: Vec::new()
3374 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3375 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3376 short_channel_id: 7,
3378 flags: 2, // to disable
3379 cltv_expiry_delta: 0,
3380 htlc_minimum_msat: 0,
3381 htlc_maximum_msat: MAX_VALUE_MSAT,
3383 fee_proportional_millionths: 0,
3384 excess_data: Vec::new()
3387 // Check against amount_to_transfer_over_msat.
3388 // Set minimal HTLC of 200_000_000 msat.
3389 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3390 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3391 short_channel_id: 2,
3394 cltv_expiry_delta: 0,
3395 htlc_minimum_msat: 200_000_000,
3396 htlc_maximum_msat: MAX_VALUE_MSAT,
3398 fee_proportional_millionths: 0,
3399 excess_data: Vec::new()
3402 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3404 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3405 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3406 short_channel_id: 4,
3409 cltv_expiry_delta: 0,
3410 htlc_minimum_msat: 0,
3411 htlc_maximum_msat: 199_999_999,
3413 fee_proportional_millionths: 0,
3414 excess_data: Vec::new()
3417 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3418 let route_params = RouteParameters::from_payment_params_and_value(
3419 payment_params, 199_999_999);
3420 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3421 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3422 &Default::default(), &random_seed_bytes) {
3423 assert_eq!(err, "Failed to find a path to the given destination");
3424 } else { panic!(); }
3426 // Lift the restriction on the first hop.
3427 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3428 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3429 short_channel_id: 2,
3432 cltv_expiry_delta: 0,
3433 htlc_minimum_msat: 0,
3434 htlc_maximum_msat: MAX_VALUE_MSAT,
3436 fee_proportional_millionths: 0,
3437 excess_data: Vec::new()
3440 // A payment above the minimum should pass
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 assert_eq!(route.paths[0].hops.len(), 2);
3447 fn htlc_minimum_overpay_test() {
3448 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3449 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3450 let config = UserConfig::default();
3451 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3452 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3454 let scorer = ln_test_utils::TestScorer::new();
3455 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3456 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3458 // A route to node#2 via two paths.
3459 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3460 // Thus, they can't send 60 without overpaying.
3461 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3462 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3463 short_channel_id: 2,
3466 cltv_expiry_delta: 0,
3467 htlc_minimum_msat: 35_000,
3468 htlc_maximum_msat: 40_000,
3470 fee_proportional_millionths: 0,
3471 excess_data: Vec::new()
3473 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3474 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3475 short_channel_id: 12,
3478 cltv_expiry_delta: 0,
3479 htlc_minimum_msat: 35_000,
3480 htlc_maximum_msat: 40_000,
3482 fee_proportional_millionths: 0,
3483 excess_data: Vec::new()
3487 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3488 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3489 short_channel_id: 13,
3492 cltv_expiry_delta: 0,
3493 htlc_minimum_msat: 0,
3494 htlc_maximum_msat: MAX_VALUE_MSAT,
3496 fee_proportional_millionths: 0,
3497 excess_data: Vec::new()
3499 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3500 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3501 short_channel_id: 4,
3504 cltv_expiry_delta: 0,
3505 htlc_minimum_msat: 0,
3506 htlc_maximum_msat: MAX_VALUE_MSAT,
3508 fee_proportional_millionths: 0,
3509 excess_data: Vec::new()
3512 // Disable other paths
3513 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3514 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3515 short_channel_id: 1,
3517 flags: 2, // to disable
3518 cltv_expiry_delta: 0,
3519 htlc_minimum_msat: 0,
3520 htlc_maximum_msat: MAX_VALUE_MSAT,
3522 fee_proportional_millionths: 0,
3523 excess_data: Vec::new()
3526 let mut route_params = RouteParameters::from_payment_params_and_value(
3527 payment_params.clone(), 60_000);
3528 route_params.max_total_routing_fee_msat = Some(15_000);
3529 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3530 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3531 // Overpay fees to hit htlc_minimum_msat.
3532 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3533 // TODO: this could be better balanced to overpay 10k and not 15k.
3534 assert_eq!(overpaid_fees, 15_000);
3536 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3537 // while taking even more fee to match htlc_minimum_msat.
3538 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3539 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3540 short_channel_id: 12,
3543 cltv_expiry_delta: 0,
3544 htlc_minimum_msat: 65_000,
3545 htlc_maximum_msat: 80_000,
3547 fee_proportional_millionths: 0,
3548 excess_data: Vec::new()
3550 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3551 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3552 short_channel_id: 2,
3555 cltv_expiry_delta: 0,
3556 htlc_minimum_msat: 0,
3557 htlc_maximum_msat: MAX_VALUE_MSAT,
3559 fee_proportional_millionths: 0,
3560 excess_data: Vec::new()
3562 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3563 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3564 short_channel_id: 4,
3567 cltv_expiry_delta: 0,
3568 htlc_minimum_msat: 0,
3569 htlc_maximum_msat: MAX_VALUE_MSAT,
3571 fee_proportional_millionths: 100_000,
3572 excess_data: Vec::new()
3575 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3576 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3577 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3578 assert_eq!(route.paths.len(), 1);
3579 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3580 let fees = route.paths[0].hops[0].fee_msat;
3581 assert_eq!(fees, 5_000);
3583 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3584 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3585 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3586 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3587 // the other channel.
3588 assert_eq!(route.paths.len(), 1);
3589 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3590 let fees = route.paths[0].hops[0].fee_msat;
3591 assert_eq!(fees, 5_000);
3595 fn htlc_minimum_recipient_overpay_test() {
3596 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3597 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3598 let config = UserConfig::default();
3599 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3600 let scorer = ln_test_utils::TestScorer::new();
3601 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3602 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3604 // Route to node2 over a single path which requires overpaying the recipient themselves.
3606 // First disable all paths except the us -> node1 -> node2 path
3607 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3608 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3609 short_channel_id: 13,
3612 cltv_expiry_delta: 0,
3613 htlc_minimum_msat: 0,
3614 htlc_maximum_msat: 0,
3616 fee_proportional_millionths: 0,
3617 excess_data: Vec::new()
3620 // Set channel 4 to free but with a high htlc_minimum_msat
3621 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3622 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3623 short_channel_id: 4,
3626 cltv_expiry_delta: 0,
3627 htlc_minimum_msat: 15_000,
3628 htlc_maximum_msat: MAX_VALUE_MSAT,
3630 fee_proportional_millionths: 0,
3631 excess_data: Vec::new()
3634 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3635 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3636 // what we try to find a route for, so this test only just happens to work out to exactly
3638 let mut route_params = RouteParameters::from_payment_params_and_value(
3639 payment_params.clone(), 5_000);
3640 route_params.max_total_routing_fee_msat = Some(9_999);
3641 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3642 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3643 &Default::default(), &random_seed_bytes) {
3644 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3645 } else { panic!(); }
3647 let mut route_params = RouteParameters::from_payment_params_and_value(
3648 payment_params.clone(), 5_000);
3649 route_params.max_total_routing_fee_msat = Some(10_000);
3650 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3651 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3652 assert_eq!(route.get_total_fees(), 10_000);
3656 fn disable_channels_test() {
3657 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3658 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3659 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3660 let scorer = ln_test_utils::TestScorer::new();
3661 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3662 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3664 // // Disable channels 4 and 12 by flags=2
3665 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3666 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3667 short_channel_id: 4,
3669 flags: 2, // to disable
3670 cltv_expiry_delta: 0,
3671 htlc_minimum_msat: 0,
3672 htlc_maximum_msat: MAX_VALUE_MSAT,
3674 fee_proportional_millionths: 0,
3675 excess_data: Vec::new()
3677 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3678 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3679 short_channel_id: 12,
3681 flags: 2, // to disable
3682 cltv_expiry_delta: 0,
3683 htlc_minimum_msat: 0,
3684 htlc_maximum_msat: MAX_VALUE_MSAT,
3686 fee_proportional_millionths: 0,
3687 excess_data: Vec::new()
3690 // If all the channels require some features we don't understand, route should fail
3691 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3692 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3693 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3694 &Default::default(), &random_seed_bytes) {
3695 assert_eq!(err, "Failed to find a path to the given destination");
3696 } else { panic!(); }
3698 // If we specify a channel to node7, that overrides our local channel view and that gets used
3699 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3700 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3701 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3702 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3703 &Default::default(), &random_seed_bytes).unwrap();
3704 assert_eq!(route.paths[0].hops.len(), 2);
3706 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3707 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3708 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3709 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3710 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3711 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3713 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3714 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3715 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3716 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3717 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3718 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3722 fn disable_node_test() {
3723 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3724 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3725 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3726 let scorer = ln_test_utils::TestScorer::new();
3727 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3728 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3730 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3731 let mut unknown_features = NodeFeatures::empty();
3732 unknown_features.set_unknown_feature_required();
3733 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3734 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3735 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3737 // If all nodes require some features we don't understand, route should fail
3738 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3739 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3740 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3741 &Default::default(), &random_seed_bytes) {
3742 assert_eq!(err, "Failed to find a path to the given destination");
3743 } else { panic!(); }
3745 // If we specify a channel to node7, that overrides our local channel view and that gets used
3746 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3747 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3748 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3749 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3750 &Default::default(), &random_seed_bytes).unwrap();
3751 assert_eq!(route.paths[0].hops.len(), 2);
3753 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3754 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3755 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3756 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3757 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3758 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3760 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3761 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3762 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3763 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3764 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3765 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3767 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3768 // naively) assume that the user checked the feature bits on the invoice, which override
3769 // the node_announcement.
3773 fn our_chans_test() {
3774 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3775 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3776 let scorer = ln_test_utils::TestScorer::new();
3777 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3778 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3780 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3781 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3782 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3783 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3784 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3785 assert_eq!(route.paths[0].hops.len(), 3);
3787 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3788 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3789 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3790 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3791 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3792 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3794 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3795 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3796 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3797 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3798 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3799 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3801 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3802 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3803 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3804 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3805 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3806 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3808 // If we specify a channel to node7, that overrides our local channel view and that gets used
3809 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3810 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3811 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3812 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3813 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3814 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3815 &Default::default(), &random_seed_bytes).unwrap();
3816 assert_eq!(route.paths[0].hops.len(), 2);
3818 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3819 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3820 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3821 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3822 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3823 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3825 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3826 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3827 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3828 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3829 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3830 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3833 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3834 let zero_fees = RoutingFees {
3836 proportional_millionths: 0,
3838 vec![RouteHint(vec![RouteHintHop {
3839 src_node_id: nodes[3],
3840 short_channel_id: 8,
3842 cltv_expiry_delta: (8 << 4) | 1,
3843 htlc_minimum_msat: None,
3844 htlc_maximum_msat: None,
3846 ]), RouteHint(vec![RouteHintHop {
3847 src_node_id: nodes[4],
3848 short_channel_id: 9,
3851 proportional_millionths: 0,
3853 cltv_expiry_delta: (9 << 4) | 1,
3854 htlc_minimum_msat: None,
3855 htlc_maximum_msat: None,
3856 }]), RouteHint(vec![RouteHintHop {
3857 src_node_id: nodes[5],
3858 short_channel_id: 10,
3860 cltv_expiry_delta: (10 << 4) | 1,
3861 htlc_minimum_msat: None,
3862 htlc_maximum_msat: None,
3866 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3867 let zero_fees = RoutingFees {
3869 proportional_millionths: 0,
3871 vec![RouteHint(vec![RouteHintHop {
3872 src_node_id: nodes[2],
3873 short_channel_id: 5,
3876 proportional_millionths: 0,
3878 cltv_expiry_delta: (5 << 4) | 1,
3879 htlc_minimum_msat: None,
3880 htlc_maximum_msat: None,
3882 src_node_id: nodes[3],
3883 short_channel_id: 8,
3885 cltv_expiry_delta: (8 << 4) | 1,
3886 htlc_minimum_msat: None,
3887 htlc_maximum_msat: None,
3889 ]), RouteHint(vec![RouteHintHop {
3890 src_node_id: nodes[4],
3891 short_channel_id: 9,
3894 proportional_millionths: 0,
3896 cltv_expiry_delta: (9 << 4) | 1,
3897 htlc_minimum_msat: None,
3898 htlc_maximum_msat: None,
3899 }]), RouteHint(vec![RouteHintHop {
3900 src_node_id: nodes[5],
3901 short_channel_id: 10,
3903 cltv_expiry_delta: (10 << 4) | 1,
3904 htlc_minimum_msat: None,
3905 htlc_maximum_msat: None,
3910 fn partial_route_hint_test() {
3911 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3912 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3913 let scorer = ln_test_utils::TestScorer::new();
3914 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3915 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3917 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3918 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3919 // RouteHint may be partially used by the algo to build the best path.
3921 // First check that last hop can't have its source as the payee.
3922 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3923 src_node_id: nodes[6],
3924 short_channel_id: 8,
3927 proportional_millionths: 0,
3929 cltv_expiry_delta: (8 << 4) | 1,
3930 htlc_minimum_msat: None,
3931 htlc_maximum_msat: None,
3934 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3935 invalid_last_hops.push(invalid_last_hop);
3937 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3938 .with_route_hints(invalid_last_hops).unwrap();
3939 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3940 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3941 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3942 &Default::default(), &random_seed_bytes) {
3943 assert_eq!(err, "Route hint cannot have the payee as the source.");
3944 } else { panic!(); }
3947 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3948 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3949 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3950 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3951 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3952 assert_eq!(route.paths[0].hops.len(), 5);
3954 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3955 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3956 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3957 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3958 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3959 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3961 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3962 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3963 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3964 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3965 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3966 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3968 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3969 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3970 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3971 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3972 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3973 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3975 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3976 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3977 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3978 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3979 // If we have a peer in the node map, we'll use their features here since we don't have
3980 // a way of figuring out their features from the invoice:
3981 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3982 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3984 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3985 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3986 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3987 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3988 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3989 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3992 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3993 let zero_fees = RoutingFees {
3995 proportional_millionths: 0,
3997 vec![RouteHint(vec![RouteHintHop {
3998 src_node_id: nodes[3],
3999 short_channel_id: 8,
4001 cltv_expiry_delta: (8 << 4) | 1,
4002 htlc_minimum_msat: None,
4003 htlc_maximum_msat: None,
4004 }]), RouteHint(vec![
4006 ]), RouteHint(vec![RouteHintHop {
4007 src_node_id: nodes[5],
4008 short_channel_id: 10,
4010 cltv_expiry_delta: (10 << 4) | 1,
4011 htlc_minimum_msat: None,
4012 htlc_maximum_msat: None,
4017 fn ignores_empty_last_hops_test() {
4018 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4019 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4020 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4021 let scorer = ln_test_utils::TestScorer::new();
4022 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4023 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4025 // Test handling of an empty RouteHint passed in Invoice.
4026 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4027 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4028 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4029 assert_eq!(route.paths[0].hops.len(), 5);
4031 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4032 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4033 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4034 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4035 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4036 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4038 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4039 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4040 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4041 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4042 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4043 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4045 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4046 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4047 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4048 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4049 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4050 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4052 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4053 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4054 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4055 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4056 // If we have a peer in the node map, we'll use their features here since we don't have
4057 // a way of figuring out their features from the invoice:
4058 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4059 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4061 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4062 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4063 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4064 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4065 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4066 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4069 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4071 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4072 let zero_fees = RoutingFees {
4074 proportional_millionths: 0,
4076 vec![RouteHint(vec![RouteHintHop {
4077 src_node_id: hint_hops[0],
4078 short_channel_id: 0xff00,
4081 proportional_millionths: 0,
4083 cltv_expiry_delta: (5 << 4) | 1,
4084 htlc_minimum_msat: None,
4085 htlc_maximum_msat: None,
4087 src_node_id: hint_hops[1],
4088 short_channel_id: 0xff01,
4090 cltv_expiry_delta: (8 << 4) | 1,
4091 htlc_minimum_msat: None,
4092 htlc_maximum_msat: None,
4097 fn multi_hint_last_hops_test() {
4098 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4099 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4100 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4101 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4102 let scorer = ln_test_utils::TestScorer::new();
4103 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4104 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4105 // Test through channels 2, 3, 0xff00, 0xff01.
4106 // Test shows that multiple hop hints are considered.
4108 // Disabling channels 6 & 7 by flags=2
4109 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4110 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4111 short_channel_id: 6,
4113 flags: 2, // to disable
4114 cltv_expiry_delta: 0,
4115 htlc_minimum_msat: 0,
4116 htlc_maximum_msat: MAX_VALUE_MSAT,
4118 fee_proportional_millionths: 0,
4119 excess_data: Vec::new()
4121 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4122 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4123 short_channel_id: 7,
4125 flags: 2, // to disable
4126 cltv_expiry_delta: 0,
4127 htlc_minimum_msat: 0,
4128 htlc_maximum_msat: MAX_VALUE_MSAT,
4130 fee_proportional_millionths: 0,
4131 excess_data: Vec::new()
4134 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4135 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4136 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4137 assert_eq!(route.paths[0].hops.len(), 4);
4139 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4140 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4141 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4142 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4143 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4144 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4146 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4147 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4148 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4149 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4150 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4151 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4153 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4154 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4155 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4156 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4157 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4158 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4160 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4161 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4162 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4163 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4164 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4165 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4169 fn private_multi_hint_last_hops_test() {
4170 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4171 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4173 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4174 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4176 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4177 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4178 let scorer = ln_test_utils::TestScorer::new();
4179 // Test through channels 2, 3, 0xff00, 0xff01.
4180 // Test shows that multiple hop hints are considered.
4182 // Disabling channels 6 & 7 by flags=2
4183 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4184 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4185 short_channel_id: 6,
4187 flags: 2, // to disable
4188 cltv_expiry_delta: 0,
4189 htlc_minimum_msat: 0,
4190 htlc_maximum_msat: MAX_VALUE_MSAT,
4192 fee_proportional_millionths: 0,
4193 excess_data: Vec::new()
4195 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4196 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4197 short_channel_id: 7,
4199 flags: 2, // to disable
4200 cltv_expiry_delta: 0,
4201 htlc_minimum_msat: 0,
4202 htlc_maximum_msat: MAX_VALUE_MSAT,
4204 fee_proportional_millionths: 0,
4205 excess_data: Vec::new()
4208 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4209 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4210 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4211 assert_eq!(route.paths[0].hops.len(), 4);
4213 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4214 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4215 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4216 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4217 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4218 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4220 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4221 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4222 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4223 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4224 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4225 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4227 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4228 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4229 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4230 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4231 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4232 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4234 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4235 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4236 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4237 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4238 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4239 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4242 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4243 let zero_fees = RoutingFees {
4245 proportional_millionths: 0,
4247 vec![RouteHint(vec![RouteHintHop {
4248 src_node_id: nodes[4],
4249 short_channel_id: 11,
4251 cltv_expiry_delta: (11 << 4) | 1,
4252 htlc_minimum_msat: None,
4253 htlc_maximum_msat: None,
4255 src_node_id: nodes[3],
4256 short_channel_id: 8,
4258 cltv_expiry_delta: (8 << 4) | 1,
4259 htlc_minimum_msat: None,
4260 htlc_maximum_msat: None,
4261 }]), RouteHint(vec![RouteHintHop {
4262 src_node_id: nodes[4],
4263 short_channel_id: 9,
4266 proportional_millionths: 0,
4268 cltv_expiry_delta: (9 << 4) | 1,
4269 htlc_minimum_msat: None,
4270 htlc_maximum_msat: None,
4271 }]), RouteHint(vec![RouteHintHop {
4272 src_node_id: nodes[5],
4273 short_channel_id: 10,
4275 cltv_expiry_delta: (10 << 4) | 1,
4276 htlc_minimum_msat: None,
4277 htlc_maximum_msat: None,
4282 fn last_hops_with_public_channel_test() {
4283 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4284 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4285 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4286 let scorer = ln_test_utils::TestScorer::new();
4287 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4288 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4289 // This test shows that public routes can be present in the invoice
4290 // which would be handled in the same manner.
4292 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4293 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4294 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4295 assert_eq!(route.paths[0].hops.len(), 5);
4297 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4298 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4299 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4300 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4301 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4302 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4304 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4305 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4306 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4307 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4308 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4309 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4311 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4312 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4313 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4314 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4315 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4316 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4318 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4319 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4320 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4321 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4322 // If we have a peer in the node map, we'll use their features here since we don't have
4323 // a way of figuring out their features from the invoice:
4324 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4325 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4327 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4328 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4329 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4330 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4331 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4332 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4336 fn our_chans_last_hop_connect_test() {
4337 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4338 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4339 let scorer = ln_test_utils::TestScorer::new();
4340 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4341 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4343 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4344 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4345 let mut last_hops = last_hops(&nodes);
4346 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4347 .with_route_hints(last_hops.clone()).unwrap();
4348 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4349 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4350 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4351 &Default::default(), &random_seed_bytes).unwrap();
4352 assert_eq!(route.paths[0].hops.len(), 2);
4354 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4355 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4356 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4357 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4358 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4359 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4361 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4362 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4363 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4364 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4365 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4366 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4368 last_hops[0].0[0].fees.base_msat = 1000;
4370 // Revert to via 6 as the fee on 8 goes up
4371 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4372 .with_route_hints(last_hops).unwrap();
4373 let route_params = RouteParameters::from_payment_params_and_value(
4374 payment_params.clone(), 100);
4375 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4376 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4377 assert_eq!(route.paths[0].hops.len(), 4);
4379 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4380 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4381 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4382 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4383 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4384 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4386 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4387 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4388 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4389 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4390 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4391 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4393 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4394 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4395 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4396 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4397 // If we have a peer in the node map, we'll use their features here since we don't have
4398 // a way of figuring out their features from the invoice:
4399 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4400 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4402 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4403 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4404 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4405 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4406 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4407 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4409 // ...but still use 8 for larger payments as 6 has a variable feerate
4410 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4411 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4412 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4413 assert_eq!(route.paths[0].hops.len(), 5);
4415 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4416 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4417 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4418 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4419 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4420 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4422 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4423 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4424 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4425 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4426 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4427 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4429 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4430 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4431 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4432 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4433 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4434 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4436 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4437 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4438 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4439 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4440 // If we have a peer in the node map, we'll use their features here since we don't have
4441 // a way of figuring out their features from the invoice:
4442 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4443 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4445 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4446 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4447 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4448 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4449 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4450 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4453 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> {
4454 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4455 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4456 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4458 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4459 let last_hops = RouteHint(vec![RouteHintHop {
4460 src_node_id: middle_node_id,
4461 short_channel_id: 8,
4464 proportional_millionths: last_hop_fee_prop,
4466 cltv_expiry_delta: (8 << 4) | 1,
4467 htlc_minimum_msat: None,
4468 htlc_maximum_msat: last_hop_htlc_max,
4470 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4471 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4472 let scorer = ln_test_utils::TestScorer::new();
4473 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4474 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4475 let logger = ln_test_utils::TestLogger::new();
4476 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4477 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4478 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4479 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4480 &random_seed_bytes);
4485 fn unannounced_path_test() {
4486 // We should be able to send a payment to a destination without any help of a routing graph
4487 // if we have a channel with a common counterparty that appears in the first and last hop
4489 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4491 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4492 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4493 assert_eq!(route.paths[0].hops.len(), 2);
4495 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4496 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4497 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4498 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4499 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4500 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4502 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4503 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4504 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4505 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4506 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4507 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4511 fn overflow_unannounced_path_test_liquidity_underflow() {
4512 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4513 // the last-hop had a fee which overflowed a u64, we'd panic.
4514 // This was due to us adding the first-hop from us unconditionally, causing us to think
4515 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4516 // In this test, we previously hit a subtraction underflow due to having less available
4517 // liquidity at the last hop than 0.
4518 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());
4522 fn overflow_unannounced_path_test_feerate_overflow() {
4523 // This tests for the same case as above, except instead of hitting a subtraction
4524 // underflow, we hit a case where the fee charged at a hop overflowed.
4525 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());
4529 fn available_amount_while_routing_test() {
4530 // Tests whether we choose the correct available channel amount while routing.
4532 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4533 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4534 let scorer = ln_test_utils::TestScorer::new();
4535 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4536 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4537 let config = UserConfig::default();
4538 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4539 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4542 // We will use a simple single-path route from
4543 // our node to node2 via node0: channels {1, 3}.
4545 // First disable all other paths.
4546 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4547 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4548 short_channel_id: 2,
4551 cltv_expiry_delta: 0,
4552 htlc_minimum_msat: 0,
4553 htlc_maximum_msat: 100_000,
4555 fee_proportional_millionths: 0,
4556 excess_data: Vec::new()
4558 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4559 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4560 short_channel_id: 12,
4563 cltv_expiry_delta: 0,
4564 htlc_minimum_msat: 0,
4565 htlc_maximum_msat: 100_000,
4567 fee_proportional_millionths: 0,
4568 excess_data: Vec::new()
4571 // Make the first channel (#1) very permissive,
4572 // and we will be testing all limits on the second channel.
4573 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4574 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4575 short_channel_id: 1,
4578 cltv_expiry_delta: 0,
4579 htlc_minimum_msat: 0,
4580 htlc_maximum_msat: 1_000_000_000,
4582 fee_proportional_millionths: 0,
4583 excess_data: Vec::new()
4586 // First, let's see if routing works if we have absolutely no idea about the available amount.
4587 // In this case, it should be set to 250_000 sats.
4588 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4589 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4590 short_channel_id: 3,
4593 cltv_expiry_delta: 0,
4594 htlc_minimum_msat: 0,
4595 htlc_maximum_msat: 250_000_000,
4597 fee_proportional_millionths: 0,
4598 excess_data: Vec::new()
4602 // Attempt to route more than available results in a failure.
4603 let route_params = RouteParameters::from_payment_params_and_value(
4604 payment_params.clone(), 250_000_001);
4605 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4606 &our_id, &route_params, &network_graph.read_only(), None,
4607 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4608 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4609 } else { panic!(); }
4613 // Now, attempt to route an exact amount we have should be fine.
4614 let route_params = RouteParameters::from_payment_params_and_value(
4615 payment_params.clone(), 250_000_000);
4616 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4617 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4618 assert_eq!(route.paths.len(), 1);
4619 let path = route.paths.last().unwrap();
4620 assert_eq!(path.hops.len(), 2);
4621 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4622 assert_eq!(path.final_value_msat(), 250_000_000);
4625 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4626 // Disable channel #1 and use another first hop.
4627 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4628 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4629 short_channel_id: 1,
4632 cltv_expiry_delta: 0,
4633 htlc_minimum_msat: 0,
4634 htlc_maximum_msat: 1_000_000_000,
4636 fee_proportional_millionths: 0,
4637 excess_data: Vec::new()
4640 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4641 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4644 // Attempt to route more than available results in a failure.
4645 let route_params = RouteParameters::from_payment_params_and_value(
4646 payment_params.clone(), 200_000_001);
4647 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4648 &our_id, &route_params, &network_graph.read_only(),
4649 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4650 &Default::default(), &random_seed_bytes) {
4651 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4652 } else { panic!(); }
4656 // Now, attempt to route an exact amount we have should be fine.
4657 let route_params = RouteParameters::from_payment_params_and_value(
4658 payment_params.clone(), 200_000_000);
4659 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4660 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4661 &Default::default(), &random_seed_bytes).unwrap();
4662 assert_eq!(route.paths.len(), 1);
4663 let path = route.paths.last().unwrap();
4664 assert_eq!(path.hops.len(), 2);
4665 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4666 assert_eq!(path.final_value_msat(), 200_000_000);
4669 // Enable channel #1 back.
4670 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4671 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4672 short_channel_id: 1,
4675 cltv_expiry_delta: 0,
4676 htlc_minimum_msat: 0,
4677 htlc_maximum_msat: 1_000_000_000,
4679 fee_proportional_millionths: 0,
4680 excess_data: Vec::new()
4684 // Now let's see if routing works if we know only htlc_maximum_msat.
4685 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4686 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4687 short_channel_id: 3,
4690 cltv_expiry_delta: 0,
4691 htlc_minimum_msat: 0,
4692 htlc_maximum_msat: 15_000,
4694 fee_proportional_millionths: 0,
4695 excess_data: Vec::new()
4699 // Attempt to route more than available results in a failure.
4700 let route_params = RouteParameters::from_payment_params_and_value(
4701 payment_params.clone(), 15_001);
4702 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4703 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4704 &scorer, &Default::default(), &random_seed_bytes) {
4705 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4706 } else { panic!(); }
4710 // Now, attempt to route an exact amount we have should be fine.
4711 let route_params = RouteParameters::from_payment_params_and_value(
4712 payment_params.clone(), 15_000);
4713 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4714 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4715 assert_eq!(route.paths.len(), 1);
4716 let path = route.paths.last().unwrap();
4717 assert_eq!(path.hops.len(), 2);
4718 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4719 assert_eq!(path.final_value_msat(), 15_000);
4722 // Now let's see if routing works if we know only capacity from the UTXO.
4724 // We can't change UTXO capacity on the fly, so we'll disable
4725 // the existing channel and add another one with the capacity we need.
4726 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4727 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4728 short_channel_id: 3,
4731 cltv_expiry_delta: 0,
4732 htlc_minimum_msat: 0,
4733 htlc_maximum_msat: MAX_VALUE_MSAT,
4735 fee_proportional_millionths: 0,
4736 excess_data: Vec::new()
4739 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4740 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4741 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4742 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4743 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4745 *chain_monitor.utxo_ret.lock().unwrap() =
4746 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4747 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4749 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4750 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4751 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4752 short_channel_id: 333,
4755 cltv_expiry_delta: (3 << 4) | 1,
4756 htlc_minimum_msat: 0,
4757 htlc_maximum_msat: 15_000,
4759 fee_proportional_millionths: 0,
4760 excess_data: Vec::new()
4762 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4763 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4764 short_channel_id: 333,
4767 cltv_expiry_delta: (3 << 4) | 2,
4768 htlc_minimum_msat: 0,
4769 htlc_maximum_msat: 15_000,
4771 fee_proportional_millionths: 0,
4772 excess_data: Vec::new()
4776 // Attempt to route more than available results in a failure.
4777 let route_params = RouteParameters::from_payment_params_and_value(
4778 payment_params.clone(), 15_001);
4779 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4780 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4781 &scorer, &Default::default(), &random_seed_bytes) {
4782 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4783 } else { panic!(); }
4787 // Now, attempt to route an exact amount we have should be fine.
4788 let route_params = RouteParameters::from_payment_params_and_value(
4789 payment_params.clone(), 15_000);
4790 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4791 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4792 assert_eq!(route.paths.len(), 1);
4793 let path = route.paths.last().unwrap();
4794 assert_eq!(path.hops.len(), 2);
4795 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4796 assert_eq!(path.final_value_msat(), 15_000);
4799 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4800 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4801 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4802 short_channel_id: 333,
4805 cltv_expiry_delta: 0,
4806 htlc_minimum_msat: 0,
4807 htlc_maximum_msat: 10_000,
4809 fee_proportional_millionths: 0,
4810 excess_data: Vec::new()
4814 // Attempt to route more than available results in a failure.
4815 let route_params = RouteParameters::from_payment_params_and_value(
4816 payment_params.clone(), 10_001);
4817 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4818 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4819 &scorer, &Default::default(), &random_seed_bytes) {
4820 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4821 } else { panic!(); }
4825 // Now, attempt to route an exact amount we have should be fine.
4826 let route_params = RouteParameters::from_payment_params_and_value(
4827 payment_params.clone(), 10_000);
4828 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4829 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4830 assert_eq!(route.paths.len(), 1);
4831 let path = route.paths.last().unwrap();
4832 assert_eq!(path.hops.len(), 2);
4833 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4834 assert_eq!(path.final_value_msat(), 10_000);
4839 fn available_liquidity_last_hop_test() {
4840 // Check that available liquidity properly limits the path even when only
4841 // one of the latter hops is limited.
4842 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4843 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4844 let scorer = ln_test_utils::TestScorer::new();
4845 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4846 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4847 let config = UserConfig::default();
4848 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4849 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4852 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4853 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4854 // Total capacity: 50 sats.
4856 // Disable other potential paths.
4857 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4858 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4859 short_channel_id: 2,
4862 cltv_expiry_delta: 0,
4863 htlc_minimum_msat: 0,
4864 htlc_maximum_msat: 100_000,
4866 fee_proportional_millionths: 0,
4867 excess_data: Vec::new()
4869 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4870 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4871 short_channel_id: 7,
4874 cltv_expiry_delta: 0,
4875 htlc_minimum_msat: 0,
4876 htlc_maximum_msat: 100_000,
4878 fee_proportional_millionths: 0,
4879 excess_data: Vec::new()
4884 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4885 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4886 short_channel_id: 12,
4889 cltv_expiry_delta: 0,
4890 htlc_minimum_msat: 0,
4891 htlc_maximum_msat: 100_000,
4893 fee_proportional_millionths: 0,
4894 excess_data: Vec::new()
4896 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4897 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4898 short_channel_id: 13,
4901 cltv_expiry_delta: 0,
4902 htlc_minimum_msat: 0,
4903 htlc_maximum_msat: 100_000,
4905 fee_proportional_millionths: 0,
4906 excess_data: Vec::new()
4909 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4910 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4911 short_channel_id: 6,
4914 cltv_expiry_delta: 0,
4915 htlc_minimum_msat: 0,
4916 htlc_maximum_msat: 50_000,
4918 fee_proportional_millionths: 0,
4919 excess_data: Vec::new()
4921 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4922 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4923 short_channel_id: 11,
4926 cltv_expiry_delta: 0,
4927 htlc_minimum_msat: 0,
4928 htlc_maximum_msat: 100_000,
4930 fee_proportional_millionths: 0,
4931 excess_data: Vec::new()
4934 // Attempt to route more than available results in a failure.
4935 let route_params = RouteParameters::from_payment_params_and_value(
4936 payment_params.clone(), 60_000);
4937 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4938 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4939 &scorer, &Default::default(), &random_seed_bytes) {
4940 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4941 } else { panic!(); }
4945 // Now, attempt to route 49 sats (just a bit below the capacity).
4946 let route_params = RouteParameters::from_payment_params_and_value(
4947 payment_params.clone(), 49_000);
4948 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4949 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4950 assert_eq!(route.paths.len(), 1);
4951 let mut total_amount_paid_msat = 0;
4952 for path in &route.paths {
4953 assert_eq!(path.hops.len(), 4);
4954 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4955 total_amount_paid_msat += path.final_value_msat();
4957 assert_eq!(total_amount_paid_msat, 49_000);
4961 // Attempt to route an exact amount is also fine
4962 let route_params = RouteParameters::from_payment_params_and_value(
4963 payment_params, 50_000);
4964 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4965 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4966 assert_eq!(route.paths.len(), 1);
4967 let mut total_amount_paid_msat = 0;
4968 for path in &route.paths {
4969 assert_eq!(path.hops.len(), 4);
4970 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4971 total_amount_paid_msat += path.final_value_msat();
4973 assert_eq!(total_amount_paid_msat, 50_000);
4978 fn ignore_fee_first_hop_test() {
4979 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4980 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4981 let scorer = ln_test_utils::TestScorer::new();
4982 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4983 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4984 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4986 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4987 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4988 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4989 short_channel_id: 1,
4992 cltv_expiry_delta: 0,
4993 htlc_minimum_msat: 0,
4994 htlc_maximum_msat: 100_000,
4995 fee_base_msat: 1_000_000,
4996 fee_proportional_millionths: 0,
4997 excess_data: Vec::new()
4999 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5000 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5001 short_channel_id: 3,
5004 cltv_expiry_delta: 0,
5005 htlc_minimum_msat: 0,
5006 htlc_maximum_msat: 50_000,
5008 fee_proportional_millionths: 0,
5009 excess_data: Vec::new()
5013 let route_params = RouteParameters::from_payment_params_and_value(
5014 payment_params, 50_000);
5015 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5016 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5017 assert_eq!(route.paths.len(), 1);
5018 let mut total_amount_paid_msat = 0;
5019 for path in &route.paths {
5020 assert_eq!(path.hops.len(), 2);
5021 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5022 total_amount_paid_msat += path.final_value_msat();
5024 assert_eq!(total_amount_paid_msat, 50_000);
5029 fn simple_mpp_route_test() {
5030 let (secp_ctx, _, _, _, _) = build_graph();
5031 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5032 let config = UserConfig::default();
5033 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5034 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5036 do_simple_mpp_route_test(clear_payment_params);
5038 // MPP to a 1-hop blinded path for nodes[2]
5039 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5040 let blinded_path = BlindedPath {
5041 introduction_node_id: nodes[2],
5042 blinding_point: ln_test_utils::pubkey(42),
5043 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5045 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5047 fee_proportional_millionths: 0,
5048 htlc_minimum_msat: 0,
5049 htlc_maximum_msat: 0,
5050 cltv_expiry_delta: 0,
5051 features: BlindedHopFeatures::empty(),
5053 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5054 .with_bolt12_features(bolt12_features.clone()).unwrap();
5055 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5057 // MPP to 3 2-hop blinded paths
5058 let mut blinded_path_node_0 = blinded_path.clone();
5059 blinded_path_node_0.introduction_node_id = nodes[0];
5060 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5061 let mut node_0_payinfo = blinded_payinfo.clone();
5062 node_0_payinfo.htlc_maximum_msat = 50_000;
5064 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5065 blinded_path_node_7.introduction_node_id = nodes[7];
5066 let mut node_7_payinfo = blinded_payinfo.clone();
5067 node_7_payinfo.htlc_maximum_msat = 60_000;
5069 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5070 blinded_path_node_1.introduction_node_id = nodes[1];
5071 let mut node_1_payinfo = blinded_payinfo.clone();
5072 node_1_payinfo.htlc_maximum_msat = 180_000;
5074 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5076 (node_0_payinfo, blinded_path_node_0),
5077 (node_7_payinfo, blinded_path_node_7),
5078 (node_1_payinfo, blinded_path_node_1)
5080 .with_bolt12_features(bolt12_features).unwrap();
5081 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5085 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5086 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5087 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5088 let scorer = ln_test_utils::TestScorer::new();
5089 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5090 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5092 // We need a route consisting of 3 paths:
5093 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5094 // To achieve this, the amount being transferred should be around
5095 // the total capacity of these 3 paths.
5097 // First, we set limits on these (previously unlimited) channels.
5098 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5100 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5101 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5102 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5103 short_channel_id: 1,
5106 cltv_expiry_delta: 0,
5107 htlc_minimum_msat: 0,
5108 htlc_maximum_msat: 100_000,
5110 fee_proportional_millionths: 0,
5111 excess_data: Vec::new()
5113 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5114 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5115 short_channel_id: 3,
5118 cltv_expiry_delta: 0,
5119 htlc_minimum_msat: 0,
5120 htlc_maximum_msat: 50_000,
5122 fee_proportional_millionths: 0,
5123 excess_data: Vec::new()
5126 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5127 // (total limit 60).
5128 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5129 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5130 short_channel_id: 12,
5133 cltv_expiry_delta: 0,
5134 htlc_minimum_msat: 0,
5135 htlc_maximum_msat: 60_000,
5137 fee_proportional_millionths: 0,
5138 excess_data: Vec::new()
5140 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5141 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5142 short_channel_id: 13,
5145 cltv_expiry_delta: 0,
5146 htlc_minimum_msat: 0,
5147 htlc_maximum_msat: 60_000,
5149 fee_proportional_millionths: 0,
5150 excess_data: Vec::new()
5153 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5154 // (total capacity 180 sats).
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: 200_000,
5164 fee_proportional_millionths: 0,
5165 excess_data: Vec::new()
5167 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5168 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5169 short_channel_id: 4,
5172 cltv_expiry_delta: 0,
5173 htlc_minimum_msat: 0,
5174 htlc_maximum_msat: 180_000,
5176 fee_proportional_millionths: 0,
5177 excess_data: Vec::new()
5181 // Attempt to route more than available results in a failure.
5182 let route_params = RouteParameters::from_payment_params_and_value(
5183 payment_params.clone(), 300_000);
5184 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5185 &our_id, &route_params, &network_graph.read_only(), None,
5186 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5187 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5188 } else { panic!(); }
5192 // Attempt to route while setting max_path_count to 0 results in a failure.
5193 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5194 let route_params = RouteParameters::from_payment_params_and_value(
5195 zero_payment_params, 100);
5196 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5197 &our_id, &route_params, &network_graph.read_only(), None,
5198 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5199 assert_eq!(err, "Can't find a route with no paths allowed.");
5200 } else { panic!(); }
5204 // Attempt to route while setting max_path_count to 3 results in a failure.
5205 // This is the case because the minimal_value_contribution_msat would require each path
5206 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5207 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5208 let route_params = RouteParameters::from_payment_params_and_value(
5209 fail_payment_params, 250_000);
5210 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5211 &our_id, &route_params, &network_graph.read_only(), None,
5212 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5213 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5214 } else { panic!(); }
5218 // Now, attempt to route 250 sats (just a bit below the capacity).
5219 // Our algorithm should provide us with these 3 paths.
5220 let route_params = RouteParameters::from_payment_params_and_value(
5221 payment_params.clone(), 250_000);
5222 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5223 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5224 assert_eq!(route.paths.len(), 3);
5225 let mut total_amount_paid_msat = 0;
5226 for path in &route.paths {
5227 if let Some(bt) = &path.blinded_tail {
5228 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5230 assert_eq!(path.hops.len(), 2);
5231 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5233 total_amount_paid_msat += path.final_value_msat();
5235 assert_eq!(total_amount_paid_msat, 250_000);
5239 // Attempt to route an exact amount is also fine
5240 let route_params = RouteParameters::from_payment_params_and_value(
5241 payment_params.clone(), 290_000);
5242 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5243 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5244 assert_eq!(route.paths.len(), 3);
5245 let mut total_amount_paid_msat = 0;
5246 for path in &route.paths {
5247 if payment_params.payee.blinded_route_hints().len() != 0 {
5248 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5249 if let Some(bt) = &path.blinded_tail {
5250 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5251 if bt.hops.len() > 1 {
5252 assert_eq!(path.hops.last().unwrap().pubkey,
5253 payment_params.payee.blinded_route_hints().iter()
5254 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5255 .map(|(_, p)| p.introduction_node_id).unwrap());
5257 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5260 assert_eq!(path.hops.len(), 2);
5261 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5263 total_amount_paid_msat += path.final_value_msat();
5265 assert_eq!(total_amount_paid_msat, 290_000);
5270 fn long_mpp_route_test() {
5271 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5272 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5273 let scorer = ln_test_utils::TestScorer::new();
5274 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5275 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5276 let config = UserConfig::default();
5277 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5278 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5281 // We need a route consisting of 3 paths:
5282 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5283 // Note that these paths overlap (channels 5, 12, 13).
5284 // We will route 300 sats.
5285 // Each path will have 100 sats capacity, those channels which
5286 // are used twice will have 200 sats capacity.
5288 // Disable other potential paths.
5289 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5290 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5291 short_channel_id: 2,
5294 cltv_expiry_delta: 0,
5295 htlc_minimum_msat: 0,
5296 htlc_maximum_msat: 100_000,
5298 fee_proportional_millionths: 0,
5299 excess_data: Vec::new()
5301 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5302 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5303 short_channel_id: 7,
5306 cltv_expiry_delta: 0,
5307 htlc_minimum_msat: 0,
5308 htlc_maximum_msat: 100_000,
5310 fee_proportional_millionths: 0,
5311 excess_data: Vec::new()
5314 // Path via {node0, node2} is channels {1, 3, 5}.
5315 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5316 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5317 short_channel_id: 1,
5320 cltv_expiry_delta: 0,
5321 htlc_minimum_msat: 0,
5322 htlc_maximum_msat: 100_000,
5324 fee_proportional_millionths: 0,
5325 excess_data: Vec::new()
5327 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5328 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5329 short_channel_id: 3,
5332 cltv_expiry_delta: 0,
5333 htlc_minimum_msat: 0,
5334 htlc_maximum_msat: 100_000,
5336 fee_proportional_millionths: 0,
5337 excess_data: Vec::new()
5340 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5341 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5342 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5343 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5344 short_channel_id: 5,
5347 cltv_expiry_delta: 0,
5348 htlc_minimum_msat: 0,
5349 htlc_maximum_msat: 200_000,
5351 fee_proportional_millionths: 0,
5352 excess_data: Vec::new()
5355 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5356 // Add 100 sats to the capacities of {12, 13}, because these channels
5357 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5358 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5359 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5360 short_channel_id: 12,
5363 cltv_expiry_delta: 0,
5364 htlc_minimum_msat: 0,
5365 htlc_maximum_msat: 200_000,
5367 fee_proportional_millionths: 0,
5368 excess_data: Vec::new()
5370 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5371 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5372 short_channel_id: 13,
5375 cltv_expiry_delta: 0,
5376 htlc_minimum_msat: 0,
5377 htlc_maximum_msat: 200_000,
5379 fee_proportional_millionths: 0,
5380 excess_data: Vec::new()
5383 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5384 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5385 short_channel_id: 6,
5388 cltv_expiry_delta: 0,
5389 htlc_minimum_msat: 0,
5390 htlc_maximum_msat: 100_000,
5392 fee_proportional_millionths: 0,
5393 excess_data: Vec::new()
5395 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5396 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5397 short_channel_id: 11,
5400 cltv_expiry_delta: 0,
5401 htlc_minimum_msat: 0,
5402 htlc_maximum_msat: 100_000,
5404 fee_proportional_millionths: 0,
5405 excess_data: Vec::new()
5408 // Path via {node7, node2} is channels {12, 13, 5}.
5409 // We already limited them to 200 sats (they are used twice for 100 sats).
5410 // Nothing to do here.
5413 // Attempt to route more than available results in a failure.
5414 let route_params = RouteParameters::from_payment_params_and_value(
5415 payment_params.clone(), 350_000);
5416 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5417 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5418 &scorer, &Default::default(), &random_seed_bytes) {
5419 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5420 } else { panic!(); }
5424 // Now, attempt to route 300 sats (exact amount we can route).
5425 // Our algorithm should provide us with these 3 paths, 100 sats each.
5426 let route_params = RouteParameters::from_payment_params_and_value(
5427 payment_params, 300_000);
5428 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5429 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5430 assert_eq!(route.paths.len(), 3);
5432 let mut total_amount_paid_msat = 0;
5433 for path in &route.paths {
5434 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5435 total_amount_paid_msat += path.final_value_msat();
5437 assert_eq!(total_amount_paid_msat, 300_000);
5443 fn mpp_cheaper_route_test() {
5444 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5445 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5446 let scorer = ln_test_utils::TestScorer::new();
5447 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5448 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5449 let config = UserConfig::default();
5450 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5451 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5454 // This test checks that if we have two cheaper paths and one more expensive path,
5455 // so that liquidity-wise any 2 of 3 combination is sufficient,
5456 // two cheaper paths will be taken.
5457 // These paths have equal available liquidity.
5459 // We need a combination of 3 paths:
5460 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5461 // Note that these paths overlap (channels 5, 12, 13).
5462 // Each path will have 100 sats capacity, those channels which
5463 // are used twice will have 200 sats capacity.
5465 // Disable other potential paths.
5466 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5467 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5468 short_channel_id: 2,
5471 cltv_expiry_delta: 0,
5472 htlc_minimum_msat: 0,
5473 htlc_maximum_msat: 100_000,
5475 fee_proportional_millionths: 0,
5476 excess_data: Vec::new()
5478 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5479 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5480 short_channel_id: 7,
5483 cltv_expiry_delta: 0,
5484 htlc_minimum_msat: 0,
5485 htlc_maximum_msat: 100_000,
5487 fee_proportional_millionths: 0,
5488 excess_data: Vec::new()
5491 // Path via {node0, node2} is channels {1, 3, 5}.
5492 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5493 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5494 short_channel_id: 1,
5497 cltv_expiry_delta: 0,
5498 htlc_minimum_msat: 0,
5499 htlc_maximum_msat: 100_000,
5501 fee_proportional_millionths: 0,
5502 excess_data: Vec::new()
5504 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5505 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5506 short_channel_id: 3,
5509 cltv_expiry_delta: 0,
5510 htlc_minimum_msat: 0,
5511 htlc_maximum_msat: 100_000,
5513 fee_proportional_millionths: 0,
5514 excess_data: Vec::new()
5517 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5518 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5519 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5520 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5521 short_channel_id: 5,
5524 cltv_expiry_delta: 0,
5525 htlc_minimum_msat: 0,
5526 htlc_maximum_msat: 200_000,
5528 fee_proportional_millionths: 0,
5529 excess_data: Vec::new()
5532 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5533 // Add 100 sats to the capacities of {12, 13}, because these channels
5534 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5535 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5536 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5537 short_channel_id: 12,
5540 cltv_expiry_delta: 0,
5541 htlc_minimum_msat: 0,
5542 htlc_maximum_msat: 200_000,
5544 fee_proportional_millionths: 0,
5545 excess_data: Vec::new()
5547 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5548 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5549 short_channel_id: 13,
5552 cltv_expiry_delta: 0,
5553 htlc_minimum_msat: 0,
5554 htlc_maximum_msat: 200_000,
5556 fee_proportional_millionths: 0,
5557 excess_data: Vec::new()
5560 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5561 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5562 short_channel_id: 6,
5565 cltv_expiry_delta: 0,
5566 htlc_minimum_msat: 0,
5567 htlc_maximum_msat: 100_000,
5568 fee_base_msat: 1_000,
5569 fee_proportional_millionths: 0,
5570 excess_data: Vec::new()
5572 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5573 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5574 short_channel_id: 11,
5577 cltv_expiry_delta: 0,
5578 htlc_minimum_msat: 0,
5579 htlc_maximum_msat: 100_000,
5581 fee_proportional_millionths: 0,
5582 excess_data: Vec::new()
5585 // Path via {node7, node2} is channels {12, 13, 5}.
5586 // We already limited them to 200 sats (they are used twice for 100 sats).
5587 // Nothing to do here.
5590 // Now, attempt to route 180 sats.
5591 // Our algorithm should provide us with these 2 paths.
5592 let route_params = RouteParameters::from_payment_params_and_value(
5593 payment_params, 180_000);
5594 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5595 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5596 assert_eq!(route.paths.len(), 2);
5598 let mut total_value_transferred_msat = 0;
5599 let mut total_paid_msat = 0;
5600 for path in &route.paths {
5601 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5602 total_value_transferred_msat += path.final_value_msat();
5603 for hop in &path.hops {
5604 total_paid_msat += hop.fee_msat;
5607 // If we paid fee, this would be higher.
5608 assert_eq!(total_value_transferred_msat, 180_000);
5609 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5610 assert_eq!(total_fees_paid, 0);
5615 fn fees_on_mpp_route_test() {
5616 // This test makes sure that MPP algorithm properly takes into account
5617 // fees charged on the channels, by making the fees impactful:
5618 // if the fee is not properly accounted for, the behavior is different.
5619 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5620 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5621 let scorer = ln_test_utils::TestScorer::new();
5622 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5623 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5624 let config = UserConfig::default();
5625 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5626 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5629 // We need a route consisting of 2 paths:
5630 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5631 // We will route 200 sats, Each path will have 100 sats capacity.
5633 // This test is not particularly stable: e.g.,
5634 // there's a way to route via {node0, node2, node4}.
5635 // It works while pathfinding is deterministic, but can be broken otherwise.
5636 // It's fine to ignore this concern for now.
5638 // Disable other potential paths.
5639 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5640 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5641 short_channel_id: 2,
5644 cltv_expiry_delta: 0,
5645 htlc_minimum_msat: 0,
5646 htlc_maximum_msat: 100_000,
5648 fee_proportional_millionths: 0,
5649 excess_data: Vec::new()
5652 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5653 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5654 short_channel_id: 7,
5657 cltv_expiry_delta: 0,
5658 htlc_minimum_msat: 0,
5659 htlc_maximum_msat: 100_000,
5661 fee_proportional_millionths: 0,
5662 excess_data: Vec::new()
5665 // Path via {node0, node2} is channels {1, 3, 5}.
5666 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5667 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5668 short_channel_id: 1,
5671 cltv_expiry_delta: 0,
5672 htlc_minimum_msat: 0,
5673 htlc_maximum_msat: 100_000,
5675 fee_proportional_millionths: 0,
5676 excess_data: Vec::new()
5678 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5679 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5680 short_channel_id: 3,
5683 cltv_expiry_delta: 0,
5684 htlc_minimum_msat: 0,
5685 htlc_maximum_msat: 100_000,
5687 fee_proportional_millionths: 0,
5688 excess_data: Vec::new()
5691 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5692 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5693 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5694 short_channel_id: 5,
5697 cltv_expiry_delta: 0,
5698 htlc_minimum_msat: 0,
5699 htlc_maximum_msat: 100_000,
5701 fee_proportional_millionths: 0,
5702 excess_data: Vec::new()
5705 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5706 // All channels should be 100 sats capacity. But for the fee experiment,
5707 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5708 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5709 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5710 // so no matter how large are other channels,
5711 // the whole path will be limited by 100 sats with just these 2 conditions:
5712 // - channel 12 capacity is 250 sats
5713 // - fee for channel 6 is 150 sats
5714 // Let's test this by enforcing these 2 conditions and removing other limits.
5715 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5716 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5717 short_channel_id: 12,
5720 cltv_expiry_delta: 0,
5721 htlc_minimum_msat: 0,
5722 htlc_maximum_msat: 250_000,
5724 fee_proportional_millionths: 0,
5725 excess_data: Vec::new()
5727 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5728 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5729 short_channel_id: 13,
5732 cltv_expiry_delta: 0,
5733 htlc_minimum_msat: 0,
5734 htlc_maximum_msat: MAX_VALUE_MSAT,
5736 fee_proportional_millionths: 0,
5737 excess_data: Vec::new()
5740 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5741 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5742 short_channel_id: 6,
5745 cltv_expiry_delta: 0,
5746 htlc_minimum_msat: 0,
5747 htlc_maximum_msat: MAX_VALUE_MSAT,
5748 fee_base_msat: 150_000,
5749 fee_proportional_millionths: 0,
5750 excess_data: Vec::new()
5752 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5753 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5754 short_channel_id: 11,
5757 cltv_expiry_delta: 0,
5758 htlc_minimum_msat: 0,
5759 htlc_maximum_msat: MAX_VALUE_MSAT,
5761 fee_proportional_millionths: 0,
5762 excess_data: Vec::new()
5766 // Attempt to route more than available results in a failure.
5767 let route_params = RouteParameters::from_payment_params_and_value(
5768 payment_params.clone(), 210_000);
5769 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5770 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5771 &scorer, &Default::default(), &random_seed_bytes) {
5772 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5773 } else { panic!(); }
5777 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5778 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5779 max_total_routing_fee_msat: Some(149_999) };
5780 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5781 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5782 &scorer, &Default::default(), &random_seed_bytes) {
5783 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5784 } else { panic!(); }
5788 // Now, attempt to route 200 sats (exact amount we can route).
5789 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5790 max_total_routing_fee_msat: Some(150_000) };
5791 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5792 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5793 assert_eq!(route.paths.len(), 2);
5795 let mut total_amount_paid_msat = 0;
5796 for path in &route.paths {
5797 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5798 total_amount_paid_msat += path.final_value_msat();
5800 assert_eq!(total_amount_paid_msat, 200_000);
5801 assert_eq!(route.get_total_fees(), 150_000);
5806 fn mpp_with_last_hops() {
5807 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5808 // via a single last-hop route hint, we'd fail to route if we first collected routes
5809 // totaling close but not quite enough to fund the full payment.
5811 // This was because we considered last-hop hints to have exactly the sought payment amount
5812 // instead of the amount we were trying to collect, needlessly limiting our path searching
5813 // at the very first hop.
5815 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5816 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5817 // to only have the remaining to-collect amount in available liquidity.
5819 // This bug appeared in production in some specific channel configurations.
5820 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5821 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5822 let scorer = ln_test_utils::TestScorer::new();
5823 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5824 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5825 let config = UserConfig::default();
5826 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5827 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5828 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5829 src_node_id: nodes[2],
5830 short_channel_id: 42,
5831 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5832 cltv_expiry_delta: 42,
5833 htlc_minimum_msat: None,
5834 htlc_maximum_msat: None,
5835 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5837 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5838 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5839 // would first use the no-fee route and then fail to find a path along the second route as
5840 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5841 // under 5% of our payment amount.
5842 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5843 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5844 short_channel_id: 1,
5847 cltv_expiry_delta: (5 << 4) | 5,
5848 htlc_minimum_msat: 0,
5849 htlc_maximum_msat: 99_000,
5850 fee_base_msat: u32::max_value(),
5851 fee_proportional_millionths: u32::max_value(),
5852 excess_data: Vec::new()
5854 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5855 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5856 short_channel_id: 2,
5859 cltv_expiry_delta: (5 << 4) | 3,
5860 htlc_minimum_msat: 0,
5861 htlc_maximum_msat: 99_000,
5862 fee_base_msat: u32::max_value(),
5863 fee_proportional_millionths: u32::max_value(),
5864 excess_data: Vec::new()
5866 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5867 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5868 short_channel_id: 4,
5871 cltv_expiry_delta: (4 << 4) | 1,
5872 htlc_minimum_msat: 0,
5873 htlc_maximum_msat: MAX_VALUE_MSAT,
5875 fee_proportional_millionths: 0,
5876 excess_data: Vec::new()
5878 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5879 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5880 short_channel_id: 13,
5882 flags: 0|2, // Channel disabled
5883 cltv_expiry_delta: (13 << 4) | 1,
5884 htlc_minimum_msat: 0,
5885 htlc_maximum_msat: MAX_VALUE_MSAT,
5887 fee_proportional_millionths: 2000000,
5888 excess_data: Vec::new()
5891 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5893 let route_params = RouteParameters::from_payment_params_and_value(
5894 payment_params, 100_000);
5895 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5896 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5897 assert_eq!(route.paths.len(), 2);
5898 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5899 // Paths are manually ordered ordered by SCID, so:
5900 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5901 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5902 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5903 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5904 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5905 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5906 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5907 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5908 assert_eq!(route.get_total_fees(), 1);
5909 assert_eq!(route.get_total_amount(), 100_000);
5913 fn drop_lowest_channel_mpp_route_test() {
5914 // This test checks that low-capacity channel is dropped when after
5915 // path finding we realize that we found more capacity than we need.
5916 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5917 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5918 let scorer = ln_test_utils::TestScorer::new();
5919 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5920 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5921 let config = UserConfig::default();
5922 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5923 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5925 .with_max_channel_saturation_power_of_half(0);
5927 // We need a route consisting of 3 paths:
5928 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5930 // The first and the second paths should be sufficient, but the third should be
5931 // cheaper, so that we select it but drop later.
5933 // First, we set limits on these (previously unlimited) channels.
5934 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5936 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5937 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5938 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5939 short_channel_id: 1,
5942 cltv_expiry_delta: 0,
5943 htlc_minimum_msat: 0,
5944 htlc_maximum_msat: 100_000,
5946 fee_proportional_millionths: 0,
5947 excess_data: Vec::new()
5949 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5950 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5951 short_channel_id: 3,
5954 cltv_expiry_delta: 0,
5955 htlc_minimum_msat: 0,
5956 htlc_maximum_msat: 50_000,
5958 fee_proportional_millionths: 0,
5959 excess_data: Vec::new()
5962 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5963 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5964 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5965 short_channel_id: 12,
5968 cltv_expiry_delta: 0,
5969 htlc_minimum_msat: 0,
5970 htlc_maximum_msat: 60_000,
5972 fee_proportional_millionths: 0,
5973 excess_data: Vec::new()
5975 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5976 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5977 short_channel_id: 13,
5980 cltv_expiry_delta: 0,
5981 htlc_minimum_msat: 0,
5982 htlc_maximum_msat: 60_000,
5984 fee_proportional_millionths: 0,
5985 excess_data: Vec::new()
5988 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5989 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5990 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5991 short_channel_id: 2,
5994 cltv_expiry_delta: 0,
5995 htlc_minimum_msat: 0,
5996 htlc_maximum_msat: 20_000,
5998 fee_proportional_millionths: 0,
5999 excess_data: Vec::new()
6001 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6002 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6003 short_channel_id: 4,
6006 cltv_expiry_delta: 0,
6007 htlc_minimum_msat: 0,
6008 htlc_maximum_msat: 20_000,
6010 fee_proportional_millionths: 0,
6011 excess_data: Vec::new()
6015 // Attempt to route more than available results in a failure.
6016 let route_params = RouteParameters::from_payment_params_and_value(
6017 payment_params.clone(), 150_000);
6018 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6019 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6020 &scorer, &Default::default(), &random_seed_bytes) {
6021 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6022 } else { panic!(); }
6026 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6027 // Our algorithm should provide us with these 3 paths.
6028 let route_params = RouteParameters::from_payment_params_and_value(
6029 payment_params.clone(), 125_000);
6030 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6031 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6032 assert_eq!(route.paths.len(), 3);
6033 let mut total_amount_paid_msat = 0;
6034 for path in &route.paths {
6035 assert_eq!(path.hops.len(), 2);
6036 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6037 total_amount_paid_msat += path.final_value_msat();
6039 assert_eq!(total_amount_paid_msat, 125_000);
6043 // Attempt to route without the last small cheap channel
6044 let route_params = RouteParameters::from_payment_params_and_value(
6045 payment_params, 90_000);
6046 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6047 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6048 assert_eq!(route.paths.len(), 2);
6049 let mut total_amount_paid_msat = 0;
6050 for path in &route.paths {
6051 assert_eq!(path.hops.len(), 2);
6052 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6053 total_amount_paid_msat += path.final_value_msat();
6055 assert_eq!(total_amount_paid_msat, 90_000);
6060 fn min_criteria_consistency() {
6061 // Test that we don't use an inconsistent metric between updating and walking nodes during
6062 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6063 // was updated with a different criterion from the heap sorting, resulting in loops in
6064 // calculated paths. We test for that specific case here.
6066 // We construct a network that looks like this:
6068 // node2 -1(3)2- node3
6072 // node1 -1(5)2- node4 -1(1)2- node6
6078 // We create a loop on the side of our real path - our destination is node 6, with a
6079 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6080 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6081 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6082 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6083 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6084 // "previous hop" being set to node 3, creating a loop in the path.
6085 let secp_ctx = Secp256k1::new();
6086 let logger = Arc::new(ln_test_utils::TestLogger::new());
6087 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6088 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6089 let (our_privkey, our_id, privkeys, 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[6], 42);
6095 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6096 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6097 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6098 short_channel_id: 6,
6101 cltv_expiry_delta: (6 << 4) | 0,
6102 htlc_minimum_msat: 0,
6103 htlc_maximum_msat: MAX_VALUE_MSAT,
6105 fee_proportional_millionths: 0,
6106 excess_data: Vec::new()
6108 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6110 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6111 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6112 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6113 short_channel_id: 5,
6116 cltv_expiry_delta: (5 << 4) | 0,
6117 htlc_minimum_msat: 0,
6118 htlc_maximum_msat: MAX_VALUE_MSAT,
6120 fee_proportional_millionths: 0,
6121 excess_data: Vec::new()
6123 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6125 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6126 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6127 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6128 short_channel_id: 4,
6131 cltv_expiry_delta: (4 << 4) | 0,
6132 htlc_minimum_msat: 0,
6133 htlc_maximum_msat: MAX_VALUE_MSAT,
6135 fee_proportional_millionths: 0,
6136 excess_data: Vec::new()
6138 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6140 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6141 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6142 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6143 short_channel_id: 3,
6146 cltv_expiry_delta: (3 << 4) | 0,
6147 htlc_minimum_msat: 0,
6148 htlc_maximum_msat: MAX_VALUE_MSAT,
6150 fee_proportional_millionths: 0,
6151 excess_data: Vec::new()
6153 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6155 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6156 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6157 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6158 short_channel_id: 2,
6161 cltv_expiry_delta: (2 << 4) | 0,
6162 htlc_minimum_msat: 0,
6163 htlc_maximum_msat: MAX_VALUE_MSAT,
6165 fee_proportional_millionths: 0,
6166 excess_data: Vec::new()
6169 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6170 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6171 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6172 short_channel_id: 1,
6175 cltv_expiry_delta: (1 << 4) | 0,
6176 htlc_minimum_msat: 100,
6177 htlc_maximum_msat: MAX_VALUE_MSAT,
6179 fee_proportional_millionths: 0,
6180 excess_data: Vec::new()
6182 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6185 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6186 let route_params = RouteParameters::from_payment_params_and_value(
6187 payment_params, 10_000);
6188 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6189 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6190 assert_eq!(route.paths.len(), 1);
6191 assert_eq!(route.paths[0].hops.len(), 3);
6193 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6194 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6195 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6196 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6197 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6198 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6200 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6201 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6202 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6203 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6204 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6205 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6207 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6208 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6209 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6210 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6211 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6212 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6218 fn exact_fee_liquidity_limit() {
6219 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6220 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6221 // we calculated fees on a higher value, resulting in us ignoring such paths.
6222 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6223 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6224 let scorer = ln_test_utils::TestScorer::new();
6225 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6226 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6227 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6229 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6231 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6232 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6233 short_channel_id: 2,
6236 cltv_expiry_delta: 0,
6237 htlc_minimum_msat: 0,
6238 htlc_maximum_msat: 85_000,
6240 fee_proportional_millionths: 0,
6241 excess_data: Vec::new()
6244 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6245 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6246 short_channel_id: 12,
6249 cltv_expiry_delta: (4 << 4) | 1,
6250 htlc_minimum_msat: 0,
6251 htlc_maximum_msat: 270_000,
6253 fee_proportional_millionths: 1000000,
6254 excess_data: Vec::new()
6258 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6259 // 200% fee charged channel 13 in the 1-to-2 direction.
6260 let mut route_params = RouteParameters::from_payment_params_and_value(
6261 payment_params, 90_000);
6262 route_params.max_total_routing_fee_msat = Some(90_000*2);
6263 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6264 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6265 assert_eq!(route.paths.len(), 1);
6266 assert_eq!(route.paths[0].hops.len(), 2);
6268 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6269 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6270 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6271 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6272 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6273 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6275 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6276 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6277 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6278 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6279 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6280 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6285 fn htlc_max_reduction_below_min() {
6286 // Test that if, while walking the graph, we reduce the value being sent to meet an
6287 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6288 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6289 // resulting in us thinking there is no possible path, even if other paths exist.
6290 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6291 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6292 let scorer = ln_test_utils::TestScorer::new();
6293 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6294 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6295 let config = UserConfig::default();
6296 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6297 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6300 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6301 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6302 // then try to send 90_000.
6303 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6304 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6305 short_channel_id: 2,
6308 cltv_expiry_delta: 0,
6309 htlc_minimum_msat: 0,
6310 htlc_maximum_msat: 80_000,
6312 fee_proportional_millionths: 0,
6313 excess_data: Vec::new()
6315 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6316 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6317 short_channel_id: 4,
6320 cltv_expiry_delta: (4 << 4) | 1,
6321 htlc_minimum_msat: 90_000,
6322 htlc_maximum_msat: MAX_VALUE_MSAT,
6324 fee_proportional_millionths: 0,
6325 excess_data: Vec::new()
6329 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6330 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6331 // expensive) channels 12-13 path.
6332 let mut route_params = RouteParameters::from_payment_params_and_value(
6333 payment_params, 90_000);
6334 route_params.max_total_routing_fee_msat = Some(90_000*2);
6335 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6336 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6337 assert_eq!(route.paths.len(), 1);
6338 assert_eq!(route.paths[0].hops.len(), 2);
6340 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6341 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6342 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6343 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6344 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6345 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6347 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6348 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6349 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6350 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6351 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6352 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6357 fn multiple_direct_first_hops() {
6358 // Previously we'd only ever considered one first hop path per counterparty.
6359 // However, as we don't restrict users to one channel per peer, we really need to support
6360 // looking at all first hop paths.
6361 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6362 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6363 // route over multiple channels with the same first hop.
6364 let secp_ctx = Secp256k1::new();
6365 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6366 let logger = Arc::new(ln_test_utils::TestLogger::new());
6367 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6368 let scorer = ln_test_utils::TestScorer::new();
6369 let config = UserConfig::default();
6370 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6371 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6373 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6374 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6377 let route_params = RouteParameters::from_payment_params_and_value(
6378 payment_params.clone(), 100_000);
6379 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6380 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6381 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6382 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6383 assert_eq!(route.paths.len(), 1);
6384 assert_eq!(route.paths[0].hops.len(), 1);
6386 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6387 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6388 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6391 let route_params = RouteParameters::from_payment_params_and_value(
6392 payment_params.clone(), 100_000);
6393 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6394 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6395 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6396 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6397 assert_eq!(route.paths.len(), 2);
6398 assert_eq!(route.paths[0].hops.len(), 1);
6399 assert_eq!(route.paths[1].hops.len(), 1);
6401 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6402 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6404 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6405 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6407 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6408 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6412 // If we have a bunch of outbound channels to the same node, where most are not
6413 // sufficient to pay the full payment, but one is, we should default to just using the
6414 // one single channel that has sufficient balance, avoiding MPP.
6416 // If we have several options above the 3xpayment value threshold, we should pick the
6417 // smallest of them, avoiding further fragmenting our available outbound balance to
6419 let route_params = RouteParameters::from_payment_params_and_value(
6420 payment_params, 100_000);
6421 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6422 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6423 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6424 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6425 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6426 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6427 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6428 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6429 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6430 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6431 assert_eq!(route.paths.len(), 1);
6432 assert_eq!(route.paths[0].hops.len(), 1);
6434 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6435 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6436 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6441 fn prefers_shorter_route_with_higher_fees() {
6442 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6443 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6444 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6446 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6447 let scorer = ln_test_utils::TestScorer::new();
6448 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6449 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6450 let route_params = RouteParameters::from_payment_params_and_value(
6451 payment_params.clone(), 100);
6452 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6453 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6454 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6456 assert_eq!(route.get_total_fees(), 100);
6457 assert_eq!(route.get_total_amount(), 100);
6458 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6460 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6461 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6462 let scorer = FixedPenaltyScorer::with_penalty(100);
6463 let route_params = RouteParameters::from_payment_params_and_value(
6464 payment_params, 100);
6465 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6466 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6467 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6469 assert_eq!(route.get_total_fees(), 300);
6470 assert_eq!(route.get_total_amount(), 100);
6471 assert_eq!(path, vec![2, 4, 7, 10]);
6474 struct BadChannelScorer {
6475 short_channel_id: u64,
6479 impl Writeable for BadChannelScorer {
6480 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6482 impl ScoreLookUp for BadChannelScorer {
6483 type ScoreParams = ();
6484 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6485 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6489 struct BadNodeScorer {
6494 impl Writeable for BadNodeScorer {
6495 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6498 impl ScoreLookUp for BadNodeScorer {
6499 type ScoreParams = ();
6500 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6501 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6506 fn avoids_routing_through_bad_channels_and_nodes() {
6507 let (secp_ctx, network, _, _, logger) = build_graph();
6508 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6509 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6510 let network_graph = network.read_only();
6512 // A path to nodes[6] exists when no penalties are applied to any channel.
6513 let scorer = ln_test_utils::TestScorer::new();
6514 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6515 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6516 let route_params = RouteParameters::from_payment_params_and_value(
6517 payment_params, 100);
6518 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6519 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6520 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6522 assert_eq!(route.get_total_fees(), 100);
6523 assert_eq!(route.get_total_amount(), 100);
6524 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6526 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6527 let scorer = BadChannelScorer { short_channel_id: 6 };
6528 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6529 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6530 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6532 assert_eq!(route.get_total_fees(), 300);
6533 assert_eq!(route.get_total_amount(), 100);
6534 assert_eq!(path, vec![2, 4, 7, 10]);
6536 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6537 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6538 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6539 &scorer, &Default::default(), &random_seed_bytes) {
6540 Err(LightningError { err, .. } ) => {
6541 assert_eq!(err, "Failed to find a path to the given destination");
6543 Ok(_) => panic!("Expected error"),
6548 fn total_fees_single_path() {
6550 paths: vec![Path { hops: vec![
6552 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6553 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6554 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6557 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6558 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6559 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6562 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6563 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6564 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6566 ], blinded_tail: None }],
6570 assert_eq!(route.get_total_fees(), 250);
6571 assert_eq!(route.get_total_amount(), 225);
6575 fn total_fees_multi_path() {
6577 paths: vec![Path { hops: vec![
6579 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6580 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6581 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6584 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6585 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6586 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6588 ], blinded_tail: None }, Path { hops: vec![
6590 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6591 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6592 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6595 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6596 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6597 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6599 ], blinded_tail: None }],
6603 assert_eq!(route.get_total_fees(), 200);
6604 assert_eq!(route.get_total_amount(), 300);
6608 fn total_empty_route_no_panic() {
6609 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6610 // would both panic if the route was completely empty. We test to ensure they return 0
6611 // here, even though its somewhat nonsensical as a route.
6612 let route = Route { paths: Vec::new(), route_params: None };
6614 assert_eq!(route.get_total_fees(), 0);
6615 assert_eq!(route.get_total_amount(), 0);
6619 fn limits_total_cltv_delta() {
6620 let (secp_ctx, network, _, _, logger) = build_graph();
6621 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6622 let network_graph = network.read_only();
6624 let scorer = ln_test_utils::TestScorer::new();
6626 // Make sure that generally there is at least one route available
6627 let feasible_max_total_cltv_delta = 1008;
6628 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6629 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6630 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6631 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6632 let route_params = RouteParameters::from_payment_params_and_value(
6633 feasible_payment_params, 100);
6634 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6635 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6636 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6637 assert_ne!(path.len(), 0);
6639 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6640 let fail_max_total_cltv_delta = 23;
6641 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6642 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6643 let route_params = RouteParameters::from_payment_params_and_value(
6644 fail_payment_params, 100);
6645 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6646 &Default::default(), &random_seed_bytes)
6648 Err(LightningError { err, .. } ) => {
6649 assert_eq!(err, "Failed to find a path to the given destination");
6651 Ok(_) => panic!("Expected error"),
6656 fn avoids_recently_failed_paths() {
6657 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6658 // randomly inserting channels into it until we can't find a route anymore.
6659 let (secp_ctx, network, _, _, logger) = build_graph();
6660 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6661 let network_graph = network.read_only();
6663 let scorer = ln_test_utils::TestScorer::new();
6664 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6665 .with_max_path_count(1);
6666 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6667 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6669 // We should be able to find a route initially, and then after we fail a few random
6670 // channels eventually we won't be able to any longer.
6671 let route_params = RouteParameters::from_payment_params_and_value(
6672 payment_params.clone(), 100);
6673 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6674 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6676 let route_params = RouteParameters::from_payment_params_and_value(
6677 payment_params.clone(), 100);
6678 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6679 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6681 for chan in route.paths[0].hops.iter() {
6682 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6684 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6685 % route.paths[0].hops.len();
6686 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6692 fn limits_path_length() {
6693 let (secp_ctx, network, _, _, logger) = build_line_graph();
6694 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6695 let network_graph = network.read_only();
6697 let scorer = ln_test_utils::TestScorer::new();
6698 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6699 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6701 // First check we can actually create a long route on this graph.
6702 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6703 let route_params = RouteParameters::from_payment_params_and_value(
6704 feasible_payment_params, 100);
6705 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6706 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6707 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6708 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6710 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6711 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6712 let route_params = RouteParameters::from_payment_params_and_value(
6713 fail_payment_params, 100);
6714 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6715 &Default::default(), &random_seed_bytes)
6717 Err(LightningError { err, .. } ) => {
6718 assert_eq!(err, "Failed to find a path to the given destination");
6720 Ok(_) => panic!("Expected error"),
6725 fn adds_and_limits_cltv_offset() {
6726 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6727 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6729 let scorer = ln_test_utils::TestScorer::new();
6731 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6732 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6733 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6734 let route_params = RouteParameters::from_payment_params_and_value(
6735 payment_params.clone(), 100);
6736 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6737 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6738 assert_eq!(route.paths.len(), 1);
6740 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6742 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6743 let mut route_default = route.clone();
6744 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6745 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6746 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6747 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6748 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6750 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6751 let mut route_limited = route.clone();
6752 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6753 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6754 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6755 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6756 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6760 fn adds_plausible_cltv_offset() {
6761 let (secp_ctx, network, _, _, logger) = build_graph();
6762 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6763 let network_graph = network.read_only();
6764 let network_nodes = network_graph.nodes();
6765 let network_channels = network_graph.channels();
6766 let scorer = ln_test_utils::TestScorer::new();
6767 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6768 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6769 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6771 let route_params = RouteParameters::from_payment_params_and_value(
6772 payment_params.clone(), 100);
6773 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6774 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6775 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6777 let mut path_plausibility = vec![];
6779 for p in route.paths {
6780 // 1. Select random observation point
6781 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6782 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6784 prng.process_in_place(&mut random_bytes);
6785 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6786 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6788 // 2. Calculate what CLTV expiry delta we would observe there
6789 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6791 // 3. Starting from the observation point, find candidate paths
6792 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6793 candidates.push_back((observation_point, vec![]));
6795 let mut found_plausible_candidate = false;
6797 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6798 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6799 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6800 found_plausible_candidate = true;
6801 break 'candidate_loop;
6805 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6806 for channel_id in &cur_node.channels {
6807 if let Some(channel_info) = network_channels.get(&channel_id) {
6808 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6809 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6810 if cur_path_cltv_deltas.iter().sum::<u32>()
6811 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6812 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6813 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6814 candidates.push_back((*next_id, new_path_cltv_deltas));
6822 path_plausibility.push(found_plausible_candidate);
6824 assert!(path_plausibility.iter().all(|x| *x));
6828 fn builds_correct_path_from_hops() {
6829 let (secp_ctx, network, _, _, logger) = build_graph();
6830 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6831 let network_graph = network.read_only();
6833 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6834 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6836 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6837 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6838 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6839 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6840 Arc::clone(&logger), &random_seed_bytes).unwrap();
6841 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6842 assert_eq!(hops.len(), route.paths[0].hops.len());
6843 for (idx, hop_pubkey) in hops.iter().enumerate() {
6844 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6849 fn avoids_saturating_channels() {
6850 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6851 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6852 let decay_params = ProbabilisticScoringDecayParameters::default();
6853 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6855 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6856 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6857 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6858 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6859 short_channel_id: 4,
6862 cltv_expiry_delta: (4 << 4) | 1,
6863 htlc_minimum_msat: 0,
6864 htlc_maximum_msat: 250_000_000,
6866 fee_proportional_millionths: 0,
6867 excess_data: Vec::new()
6869 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6870 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6871 short_channel_id: 13,
6874 cltv_expiry_delta: (13 << 4) | 1,
6875 htlc_minimum_msat: 0,
6876 htlc_maximum_msat: 250_000_000,
6878 fee_proportional_millionths: 0,
6879 excess_data: Vec::new()
6882 let config = UserConfig::default();
6883 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6884 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6886 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6887 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6888 // 100,000 sats is less than the available liquidity on each channel, set above.
6889 let route_params = RouteParameters::from_payment_params_and_value(
6890 payment_params, 100_000_000);
6891 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6892 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6893 assert_eq!(route.paths.len(), 2);
6894 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6895 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6898 #[cfg(not(feature = "no-std"))]
6899 pub(super) fn random_init_seed() -> u64 {
6900 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6901 use core::hash::{BuildHasher, Hasher};
6902 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6903 println!("Using seed of {}", seed);
6908 #[cfg(not(feature = "no-std"))]
6909 fn generate_routes() {
6910 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6912 let logger = ln_test_utils::TestLogger::new();
6913 let graph = match super::bench_utils::read_network_graph(&logger) {
6921 let params = ProbabilisticScoringFeeParameters::default();
6922 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6923 let features = super::Bolt11InvoiceFeatures::empty();
6925 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6929 #[cfg(not(feature = "no-std"))]
6930 fn generate_routes_mpp() {
6931 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6933 let logger = ln_test_utils::TestLogger::new();
6934 let graph = match super::bench_utils::read_network_graph(&logger) {
6942 let params = ProbabilisticScoringFeeParameters::default();
6943 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6944 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6946 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6950 #[cfg(not(feature = "no-std"))]
6951 fn generate_large_mpp_routes() {
6952 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6954 let logger = ln_test_utils::TestLogger::new();
6955 let graph = match super::bench_utils::read_network_graph(&logger) {
6963 let params = ProbabilisticScoringFeeParameters::default();
6964 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6965 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6967 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6971 fn honors_manual_penalties() {
6972 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6973 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6975 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6976 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6978 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6979 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6981 // First check set manual penalties are returned by the scorer.
6982 let usage = ChannelUsage {
6984 inflight_htlc_msat: 0,
6985 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6987 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6988 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6989 let network_graph = network_graph.read_only();
6990 let channels = network_graph.channels();
6991 let channel = channels.get(&5).unwrap();
6992 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
6993 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop {
6995 short_channel_id: 5,
6997 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
6999 // Then check we can get a normal route
7000 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7001 let route_params = RouteParameters::from_payment_params_and_value(
7002 payment_params, 100);
7003 let route = get_route(&our_id, &route_params, &network_graph, None,
7004 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7005 assert!(route.is_ok());
7007 // Then check that we can't get a route if we ban an intermediate node.
7008 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7009 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7010 assert!(route.is_err());
7012 // Finally make sure we can route again, when we remove the ban.
7013 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7014 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7015 assert!(route.is_ok());
7019 fn abide_by_route_hint_max_htlc() {
7020 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7021 // params in the final route.
7022 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7023 let netgraph = network_graph.read_only();
7024 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7025 let scorer = ln_test_utils::TestScorer::new();
7026 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7027 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7028 let config = UserConfig::default();
7030 let max_htlc_msat = 50_000;
7031 let route_hint_1 = RouteHint(vec![RouteHintHop {
7032 src_node_id: nodes[2],
7033 short_channel_id: 42,
7036 proportional_millionths: 0,
7038 cltv_expiry_delta: 10,
7039 htlc_minimum_msat: None,
7040 htlc_maximum_msat: Some(max_htlc_msat),
7042 let dest_node_id = ln_test_utils::pubkey(42);
7043 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7044 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7045 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7048 // Make sure we'll error if our route hints don't have enough liquidity according to their
7049 // htlc_maximum_msat.
7050 let mut route_params = RouteParameters::from_payment_params_and_value(
7051 payment_params, max_htlc_msat + 1);
7052 route_params.max_total_routing_fee_msat = None;
7053 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7054 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7057 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7058 } else { panic!(); }
7060 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7061 let mut route_hint_2 = route_hint_1.clone();
7062 route_hint_2.0[0].short_channel_id = 43;
7063 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7064 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7065 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7067 let mut route_params = RouteParameters::from_payment_params_and_value(
7068 payment_params, max_htlc_msat + 1);
7069 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7070 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7071 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7072 assert_eq!(route.paths.len(), 2);
7073 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7074 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7078 fn direct_channel_to_hints_with_max_htlc() {
7079 // Check that if we have a first hop channel peer that's connected to multiple provided route
7080 // hints, that we properly split the payment between the route hints if needed.
7081 let logger = Arc::new(ln_test_utils::TestLogger::new());
7082 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7083 let scorer = ln_test_utils::TestScorer::new();
7084 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7085 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7086 let config = UserConfig::default();
7088 let our_node_id = ln_test_utils::pubkey(42);
7089 let intermed_node_id = ln_test_utils::pubkey(43);
7090 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7092 let amt_msat = 900_000;
7093 let max_htlc_msat = 500_000;
7094 let route_hint_1 = RouteHint(vec![RouteHintHop {
7095 src_node_id: intermed_node_id,
7096 short_channel_id: 44,
7099 proportional_millionths: 0,
7101 cltv_expiry_delta: 10,
7102 htlc_minimum_msat: None,
7103 htlc_maximum_msat: Some(max_htlc_msat),
7105 src_node_id: intermed_node_id,
7106 short_channel_id: 45,
7109 proportional_millionths: 0,
7111 cltv_expiry_delta: 10,
7112 htlc_minimum_msat: None,
7113 // Check that later route hint max htlcs don't override earlier ones
7114 htlc_maximum_msat: Some(max_htlc_msat - 50),
7116 let mut route_hint_2 = route_hint_1.clone();
7117 route_hint_2.0[0].short_channel_id = 46;
7118 route_hint_2.0[1].short_channel_id = 47;
7119 let dest_node_id = ln_test_utils::pubkey(44);
7120 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7121 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7122 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7125 let route_params = RouteParameters::from_payment_params_and_value(
7126 payment_params, amt_msat);
7127 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7128 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7129 &Default::default(), &random_seed_bytes).unwrap();
7130 assert_eq!(route.paths.len(), 2);
7131 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7132 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7133 assert_eq!(route.get_total_amount(), amt_msat);
7135 // Re-run but with two first hop channels connected to the same route hint peers that must be
7137 let first_hops = vec![
7138 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7139 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7141 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7142 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7143 &Default::default(), &random_seed_bytes).unwrap();
7144 assert_eq!(route.paths.len(), 2);
7145 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7146 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7147 assert_eq!(route.get_total_amount(), amt_msat);
7149 // Make sure this works for blinded route hints.
7150 let blinded_path = BlindedPath {
7151 introduction_node_id: intermed_node_id,
7152 blinding_point: ln_test_utils::pubkey(42),
7154 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7155 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7158 let blinded_payinfo = BlindedPayInfo {
7160 fee_proportional_millionths: 0,
7161 htlc_minimum_msat: 1,
7162 htlc_maximum_msat: max_htlc_msat,
7163 cltv_expiry_delta: 10,
7164 features: BlindedHopFeatures::empty(),
7166 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7167 let payment_params = PaymentParameters::blinded(vec![
7168 (blinded_payinfo.clone(), blinded_path.clone()),
7169 (blinded_payinfo.clone(), blinded_path.clone())])
7170 .with_bolt12_features(bolt12_features).unwrap();
7171 let route_params = RouteParameters::from_payment_params_and_value(
7172 payment_params, amt_msat);
7173 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7174 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7175 &Default::default(), &random_seed_bytes).unwrap();
7176 assert_eq!(route.paths.len(), 2);
7177 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7178 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7179 assert_eq!(route.get_total_amount(), amt_msat);
7183 fn blinded_route_ser() {
7184 let blinded_path_1 = BlindedPath {
7185 introduction_node_id: ln_test_utils::pubkey(42),
7186 blinding_point: ln_test_utils::pubkey(43),
7188 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7189 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7192 let blinded_path_2 = BlindedPath {
7193 introduction_node_id: ln_test_utils::pubkey(46),
7194 blinding_point: ln_test_utils::pubkey(47),
7196 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7197 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7200 // (De)serialize a Route with 1 blinded path out of two total paths.
7201 let mut route = Route { paths: vec![Path {
7202 hops: vec![RouteHop {
7203 pubkey: ln_test_utils::pubkey(50),
7204 node_features: NodeFeatures::empty(),
7205 short_channel_id: 42,
7206 channel_features: ChannelFeatures::empty(),
7208 cltv_expiry_delta: 0,
7209 maybe_announced_channel: true,
7211 blinded_tail: Some(BlindedTail {
7212 hops: blinded_path_1.blinded_hops,
7213 blinding_point: blinded_path_1.blinding_point,
7214 excess_final_cltv_expiry_delta: 40,
7215 final_value_msat: 100,
7217 hops: vec![RouteHop {
7218 pubkey: ln_test_utils::pubkey(51),
7219 node_features: NodeFeatures::empty(),
7220 short_channel_id: 43,
7221 channel_features: ChannelFeatures::empty(),
7223 cltv_expiry_delta: 0,
7224 maybe_announced_channel: true,
7225 }], blinded_tail: None }],
7228 let encoded_route = route.encode();
7229 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7230 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7231 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7233 // (De)serialize a Route with two paths, each containing a blinded tail.
7234 route.paths[1].blinded_tail = Some(BlindedTail {
7235 hops: blinded_path_2.blinded_hops,
7236 blinding_point: blinded_path_2.blinding_point,
7237 excess_final_cltv_expiry_delta: 41,
7238 final_value_msat: 101,
7240 let encoded_route = route.encode();
7241 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7242 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7243 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7247 fn blinded_path_inflight_processing() {
7248 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7249 // account for the blinded tail's final amount_msat.
7250 let mut inflight_htlcs = InFlightHtlcs::new();
7251 let blinded_path = BlindedPath {
7252 introduction_node_id: ln_test_utils::pubkey(43),
7253 blinding_point: ln_test_utils::pubkey(48),
7254 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7257 hops: vec![RouteHop {
7258 pubkey: ln_test_utils::pubkey(42),
7259 node_features: NodeFeatures::empty(),
7260 short_channel_id: 42,
7261 channel_features: ChannelFeatures::empty(),
7263 cltv_expiry_delta: 0,
7264 maybe_announced_channel: false,
7267 pubkey: blinded_path.introduction_node_id,
7268 node_features: NodeFeatures::empty(),
7269 short_channel_id: 43,
7270 channel_features: ChannelFeatures::empty(),
7272 cltv_expiry_delta: 0,
7273 maybe_announced_channel: false,
7275 blinded_tail: Some(BlindedTail {
7276 hops: blinded_path.blinded_hops,
7277 blinding_point: blinded_path.blinding_point,
7278 excess_final_cltv_expiry_delta: 0,
7279 final_value_msat: 200,
7282 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7283 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7284 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7288 fn blinded_path_cltv_shadow_offset() {
7289 // Make sure we add a shadow offset when sending to blinded paths.
7290 let blinded_path = BlindedPath {
7291 introduction_node_id: ln_test_utils::pubkey(43),
7292 blinding_point: ln_test_utils::pubkey(44),
7294 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7295 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7298 let mut route = Route { paths: vec![Path {
7299 hops: vec![RouteHop {
7300 pubkey: ln_test_utils::pubkey(42),
7301 node_features: NodeFeatures::empty(),
7302 short_channel_id: 42,
7303 channel_features: ChannelFeatures::empty(),
7305 cltv_expiry_delta: 0,
7306 maybe_announced_channel: false,
7309 pubkey: blinded_path.introduction_node_id,
7310 node_features: NodeFeatures::empty(),
7311 short_channel_id: 43,
7312 channel_features: ChannelFeatures::empty(),
7314 cltv_expiry_delta: 0,
7315 maybe_announced_channel: false,
7318 blinded_tail: Some(BlindedTail {
7319 hops: blinded_path.blinded_hops,
7320 blinding_point: blinded_path.blinding_point,
7321 excess_final_cltv_expiry_delta: 0,
7322 final_value_msat: 200,
7324 }], route_params: None};
7326 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7327 let (_, network_graph, _, _, _) = build_line_graph();
7328 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7329 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7330 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7334 fn simple_blinded_route_hints() {
7335 do_simple_blinded_route_hints(1);
7336 do_simple_blinded_route_hints(2);
7337 do_simple_blinded_route_hints(3);
7340 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7341 // Check that we can generate a route to a blinded path with the expected hops.
7342 let (secp_ctx, network, _, _, logger) = build_graph();
7343 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7344 let network_graph = network.read_only();
7346 let scorer = ln_test_utils::TestScorer::new();
7347 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7348 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7350 let mut blinded_path = BlindedPath {
7351 introduction_node_id: nodes[2],
7352 blinding_point: ln_test_utils::pubkey(42),
7353 blinded_hops: Vec::with_capacity(num_blinded_hops),
7355 for i in 0..num_blinded_hops {
7356 blinded_path.blinded_hops.push(
7357 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7360 let blinded_payinfo = BlindedPayInfo {
7362 fee_proportional_millionths: 500,
7363 htlc_minimum_msat: 1000,
7364 htlc_maximum_msat: 100_000_000,
7365 cltv_expiry_delta: 15,
7366 features: BlindedHopFeatures::empty(),
7369 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7370 let route_params = RouteParameters::from_payment_params_and_value(
7371 payment_params, 1001);
7372 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7373 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7374 assert_eq!(route.paths.len(), 1);
7375 assert_eq!(route.paths[0].hops.len(), 2);
7377 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7378 assert_eq!(tail.hops, blinded_path.blinded_hops);
7379 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7380 assert_eq!(tail.final_value_msat, 1001);
7382 let final_hop = route.paths[0].hops.last().unwrap();
7383 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7384 if tail.hops.len() > 1 {
7385 assert_eq!(final_hop.fee_msat,
7386 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7387 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7389 assert_eq!(final_hop.fee_msat, 0);
7390 assert_eq!(final_hop.cltv_expiry_delta, 0);
7395 fn blinded_path_routing_errors() {
7396 // Check that we can generate a route to a blinded path with the expected hops.
7397 let (secp_ctx, network, _, _, logger) = build_graph();
7398 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7399 let network_graph = network.read_only();
7401 let scorer = ln_test_utils::TestScorer::new();
7402 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7403 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7405 let mut invalid_blinded_path = BlindedPath {
7406 introduction_node_id: nodes[2],
7407 blinding_point: ln_test_utils::pubkey(42),
7409 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7412 let blinded_payinfo = BlindedPayInfo {
7414 fee_proportional_millionths: 500,
7415 htlc_minimum_msat: 1000,
7416 htlc_maximum_msat: 100_000_000,
7417 cltv_expiry_delta: 15,
7418 features: BlindedHopFeatures::empty(),
7421 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7422 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7423 let payment_params = PaymentParameters::blinded(vec![
7424 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7425 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7426 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7427 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7428 &scorer, &Default::default(), &random_seed_bytes)
7430 Err(LightningError { err, .. }) => {
7431 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7433 _ => panic!("Expected error")
7436 invalid_blinded_path.introduction_node_id = our_id;
7437 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7438 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7439 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7440 &Default::default(), &random_seed_bytes)
7442 Err(LightningError { err, .. }) => {
7443 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7445 _ => panic!("Expected error")
7448 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7449 invalid_blinded_path.blinded_hops.clear();
7450 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7451 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7452 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7453 &Default::default(), &random_seed_bytes)
7455 Err(LightningError { err, .. }) => {
7456 assert_eq!(err, "0-hop blinded path provided");
7458 _ => panic!("Expected error")
7463 fn matching_intro_node_paths_provided() {
7464 // Check that if multiple blinded paths with the same intro node are provided in payment
7465 // parameters, we'll return the correct paths in the resulting MPP route.
7466 let (secp_ctx, network, _, _, logger) = build_graph();
7467 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7468 let network_graph = network.read_only();
7470 let scorer = ln_test_utils::TestScorer::new();
7471 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7472 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7473 let config = UserConfig::default();
7475 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7476 let blinded_path_1 = BlindedPath {
7477 introduction_node_id: nodes[2],
7478 blinding_point: ln_test_utils::pubkey(42),
7480 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7481 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7484 let blinded_payinfo_1 = BlindedPayInfo {
7486 fee_proportional_millionths: 0,
7487 htlc_minimum_msat: 0,
7488 htlc_maximum_msat: 30_000,
7489 cltv_expiry_delta: 0,
7490 features: BlindedHopFeatures::empty(),
7493 let mut blinded_path_2 = blinded_path_1.clone();
7494 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7495 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7496 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7498 let blinded_hints = vec![
7499 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7500 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7502 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7503 .with_bolt12_features(bolt12_features).unwrap();
7505 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7506 route_params.max_total_routing_fee_msat = Some(100_000);
7507 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7508 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7509 assert_eq!(route.paths.len(), 2);
7510 let mut total_amount_paid_msat = 0;
7511 for path in route.paths.into_iter() {
7512 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7513 if let Some(bt) = &path.blinded_tail {
7514 assert_eq!(bt.blinding_point,
7515 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7516 .map(|(_, bp)| bp.blinding_point).unwrap());
7517 } else { panic!(); }
7518 total_amount_paid_msat += path.final_value_msat();
7520 assert_eq!(total_amount_paid_msat, 100_000);
7524 fn direct_to_intro_node() {
7525 // This previously caused a debug panic in the router when asserting
7526 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7527 // direct channels we failed to account for the fee charged for use of the blinded path.
7530 // node0 -1(1)2 - node1
7531 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7532 // doesn't account for the blinded path fee.
7534 let secp_ctx = Secp256k1::new();
7535 let logger = Arc::new(ln_test_utils::TestLogger::new());
7536 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7537 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7538 let scorer = ln_test_utils::TestScorer::new();
7539 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7540 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7542 let amt_msat = 10_000_000;
7543 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7544 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7545 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7546 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7547 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7548 short_channel_id: 1,
7551 cltv_expiry_delta: 42,
7552 htlc_minimum_msat: 1_000,
7553 htlc_maximum_msat: 10_000_000,
7555 fee_proportional_millionths: 0,
7556 excess_data: Vec::new()
7558 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7559 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7560 short_channel_id: 1,
7563 cltv_expiry_delta: 42,
7564 htlc_minimum_msat: 1_000,
7565 htlc_maximum_msat: 10_000_000,
7567 fee_proportional_millionths: 0,
7568 excess_data: Vec::new()
7570 let first_hops = vec![
7571 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7573 let blinded_path = BlindedPath {
7574 introduction_node_id: nodes[1],
7575 blinding_point: ln_test_utils::pubkey(42),
7577 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7578 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7581 let blinded_payinfo = BlindedPayInfo {
7582 fee_base_msat: 1000,
7583 fee_proportional_millionths: 0,
7584 htlc_minimum_msat: 1000,
7585 htlc_maximum_msat: MAX_VALUE_MSAT,
7586 cltv_expiry_delta: 0,
7587 features: BlindedHopFeatures::empty(),
7589 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7591 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7593 let netgraph = network_graph.read_only();
7594 let route_params = RouteParameters::from_payment_params_and_value(
7595 payment_params.clone(), amt_msat);
7596 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7597 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7598 &Default::default(), &random_seed_bytes) {
7599 assert_eq!(err, "Failed to find a path to the given destination");
7600 } else { panic!("Expected error") }
7602 // Sending an exact amount accounting for the blinded path fee works.
7603 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7604 let route_params = RouteParameters::from_payment_params_and_value(
7605 payment_params, amt_minus_blinded_path_fee);
7606 let route = get_route(&nodes[0], &route_params, &netgraph,
7607 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7608 &Default::default(), &random_seed_bytes).unwrap();
7609 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7610 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7614 fn direct_to_matching_intro_nodes() {
7615 // This previously caused us to enter `unreachable` code in the following situation:
7616 // 1. We add a route candidate for intro_node contributing a high amount
7617 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7618 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7619 // amount, and update our route candidate for intro_node for the lower amount
7620 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7621 // lower contribution amount, but fail (this was previously caused by failure to account for
7622 // blinded path fees when adding first_hop<>intro_node candidates)
7623 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7624 // candidate still thinks its path is contributing the original higher amount. This caused us
7625 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7627 let secp_ctx = Secp256k1::new();
7628 let logger = Arc::new(ln_test_utils::TestLogger::new());
7629 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7630 let scorer = ln_test_utils::TestScorer::new();
7631 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7632 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7633 let config = UserConfig::default();
7635 // Values are taken from the fuzz input that uncovered this panic.
7636 let amt_msat = 21_7020_5185_1403_2640;
7637 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7638 let first_hops = vec![
7639 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7640 18446744073709551615)];
7642 let blinded_path = BlindedPath {
7643 introduction_node_id: nodes[1],
7644 blinding_point: ln_test_utils::pubkey(42),
7646 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7647 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7650 let blinded_payinfo = BlindedPayInfo {
7651 fee_base_msat: 5046_2720,
7652 fee_proportional_millionths: 0,
7653 htlc_minimum_msat: 4503_5996_2737_0496,
7654 htlc_maximum_msat: 45_0359_9627_3704_9600,
7655 cltv_expiry_delta: 0,
7656 features: BlindedHopFeatures::empty(),
7658 let mut blinded_hints = vec![
7659 (blinded_payinfo.clone(), blinded_path.clone()),
7660 (blinded_payinfo.clone(), blinded_path.clone()),
7662 blinded_hints[1].0.fee_base_msat = 419_4304;
7663 blinded_hints[1].0.fee_proportional_millionths = 257;
7664 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7665 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7666 blinded_hints[1].0.cltv_expiry_delta = 0;
7668 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7669 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7670 .with_bolt12_features(bolt12_features).unwrap();
7672 let netgraph = network_graph.read_only();
7673 let route_params = RouteParameters::from_payment_params_and_value(
7674 payment_params, amt_msat);
7675 let route = get_route(&nodes[0], &route_params, &netgraph,
7676 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7677 &Default::default(), &random_seed_bytes).unwrap();
7678 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7679 assert_eq!(route.get_total_amount(), amt_msat);
7683 fn we_are_intro_node_candidate_hops() {
7684 // This previously led to a panic in the router because we'd generate a Path with only a
7685 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7686 // where the origin node is the intro node. We now fully disallow considering candidate hops
7687 // where the origin node is the intro node.
7688 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7689 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7690 let scorer = ln_test_utils::TestScorer::new();
7691 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7692 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7693 let config = UserConfig::default();
7695 // Values are taken from the fuzz input that uncovered this panic.
7696 let amt_msat = 21_7020_5185_1423_0019;
7698 let blinded_path = BlindedPath {
7699 introduction_node_id: our_id,
7700 blinding_point: ln_test_utils::pubkey(42),
7702 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7703 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7706 let blinded_payinfo = BlindedPayInfo {
7707 fee_base_msat: 5052_9027,
7708 fee_proportional_millionths: 0,
7709 htlc_minimum_msat: 21_7020_5185_1423_0019,
7710 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7711 cltv_expiry_delta: 0,
7712 features: BlindedHopFeatures::empty(),
7714 let mut blinded_hints = vec![
7715 (blinded_payinfo.clone(), blinded_path.clone()),
7716 (blinded_payinfo.clone(), blinded_path.clone()),
7718 blinded_hints[1].1.introduction_node_id = nodes[6];
7720 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7721 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7722 .with_bolt12_features(bolt12_features.clone()).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, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7730 assert_eq!(err, "Failed to find a path to the given destination");
7735 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7736 // This previously led to a debug panic in the router because we'd find an invalid Path with
7737 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7738 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7739 // the payment, when it was intended to only include the final value of the payment.
7740 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7741 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7742 let scorer = ln_test_utils::TestScorer::new();
7743 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7744 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7745 let config = UserConfig::default();
7747 // Values are taken from the fuzz input that uncovered this panic.
7748 let amt_msat = 21_7020_5185_1423_0019;
7750 let blinded_path = BlindedPath {
7751 introduction_node_id: our_id,
7752 blinding_point: ln_test_utils::pubkey(42),
7754 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7755 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7758 let blinded_payinfo = BlindedPayInfo {
7759 fee_base_msat: 10_4425_1395,
7760 fee_proportional_millionths: 0,
7761 htlc_minimum_msat: 21_7301_9934_9094_0931,
7762 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7763 cltv_expiry_delta: 0,
7764 features: BlindedHopFeatures::empty(),
7766 let mut blinded_hints = vec![
7767 (blinded_payinfo.clone(), blinded_path.clone()),
7768 (blinded_payinfo.clone(), blinded_path.clone()),
7769 (blinded_payinfo.clone(), blinded_path.clone()),
7771 blinded_hints[1].0.fee_base_msat = 5052_9027;
7772 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7773 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7775 blinded_hints[2].1.introduction_node_id = nodes[6];
7777 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7778 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7779 .with_bolt12_features(bolt12_features.clone()).unwrap();
7781 let netgraph = network_graph.read_only();
7782 let route_params = RouteParameters::from_payment_params_and_value(
7783 payment_params, amt_msat);
7784 if let Err(LightningError { err, .. }) = get_route(
7785 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7787 assert_eq!(err, "Failed to find a path to the given destination");
7792 fn min_htlc_overpay_violates_max_htlc() {
7793 do_min_htlc_overpay_violates_max_htlc(true);
7794 do_min_htlc_overpay_violates_max_htlc(false);
7796 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7797 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7798 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7799 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7800 // that the used liquidity for a hop was less than its available liquidity limit.
7801 let secp_ctx = Secp256k1::new();
7802 let logger = Arc::new(ln_test_utils::TestLogger::new());
7803 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7804 let scorer = ln_test_utils::TestScorer::new();
7805 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7806 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7807 let config = UserConfig::default();
7809 // Values are taken from the fuzz input that uncovered this panic.
7810 let amt_msat = 7_4009_8048;
7811 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7812 let first_hop_outbound_capacity = 2_7345_2000;
7813 let first_hops = vec![get_channel_details(
7814 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7815 first_hop_outbound_capacity
7818 let base_fee = 1_6778_3453;
7819 let htlc_min = 2_5165_8240;
7820 let payment_params = if blinded_payee {
7821 let blinded_path = BlindedPath {
7822 introduction_node_id: nodes[0],
7823 blinding_point: ln_test_utils::pubkey(42),
7825 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7826 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7829 let blinded_payinfo = BlindedPayInfo {
7830 fee_base_msat: base_fee,
7831 fee_proportional_millionths: 0,
7832 htlc_minimum_msat: htlc_min,
7833 htlc_maximum_msat: htlc_min * 1000,
7834 cltv_expiry_delta: 0,
7835 features: BlindedHopFeatures::empty(),
7837 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7838 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7839 .with_bolt12_features(bolt12_features.clone()).unwrap()
7841 let route_hint = RouteHint(vec![RouteHintHop {
7842 src_node_id: nodes[0],
7843 short_channel_id: 42,
7845 base_msat: base_fee,
7846 proportional_millionths: 0,
7848 cltv_expiry_delta: 10,
7849 htlc_minimum_msat: Some(htlc_min),
7850 htlc_maximum_msat: None,
7853 PaymentParameters::from_node_id(nodes[1], 42)
7854 .with_route_hints(vec![route_hint]).unwrap()
7855 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7858 let netgraph = network_graph.read_only();
7859 let route_params = RouteParameters::from_payment_params_and_value(
7860 payment_params, amt_msat);
7861 if let Err(LightningError { err, .. }) = get_route(
7862 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7863 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7865 assert_eq!(err, "Failed to find a path to the given destination");
7870 fn previously_used_liquidity_violates_max_htlc() {
7871 do_previously_used_liquidity_violates_max_htlc(true);
7872 do_previously_used_liquidity_violates_max_htlc(false);
7875 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7876 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7877 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7878 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7879 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7880 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7881 let secp_ctx = Secp256k1::new();
7882 let logger = Arc::new(ln_test_utils::TestLogger::new());
7883 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7884 let scorer = ln_test_utils::TestScorer::new();
7885 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7886 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7887 let config = UserConfig::default();
7889 // Values are taken from the fuzz input that uncovered this panic.
7890 let amt_msat = 52_4288;
7891 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7892 let first_hops = vec![get_channel_details(
7893 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7894 ), get_channel_details(
7895 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7898 let base_fees = [0, 425_9840, 0, 0];
7899 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7900 let payment_params = if blinded_payee {
7901 let blinded_path = BlindedPath {
7902 introduction_node_id: nodes[0],
7903 blinding_point: ln_test_utils::pubkey(42),
7905 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7906 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7909 let mut blinded_hints = Vec::new();
7910 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7911 blinded_hints.push((BlindedPayInfo {
7912 fee_base_msat: *base_fee,
7913 fee_proportional_millionths: 0,
7914 htlc_minimum_msat: *htlc_min,
7915 htlc_maximum_msat: htlc_min * 100,
7916 cltv_expiry_delta: 10,
7917 features: BlindedHopFeatures::empty(),
7918 }, blinded_path.clone()));
7920 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7921 PaymentParameters::blinded(blinded_hints.clone())
7922 .with_bolt12_features(bolt12_features.clone()).unwrap()
7924 let mut route_hints = Vec::new();
7925 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7926 route_hints.push(RouteHint(vec![RouteHintHop {
7927 src_node_id: nodes[0],
7928 short_channel_id: 42 + idx as u64,
7930 base_msat: *base_fee,
7931 proportional_millionths: 0,
7933 cltv_expiry_delta: 10,
7934 htlc_minimum_msat: Some(*htlc_min),
7935 htlc_maximum_msat: Some(htlc_min * 100),
7938 PaymentParameters::from_node_id(nodes[1], 42)
7939 .with_route_hints(route_hints).unwrap()
7940 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7943 let netgraph = network_graph.read_only();
7944 let route_params = RouteParameters::from_payment_params_and_value(
7945 payment_params, amt_msat);
7947 let route = get_route(
7948 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7949 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7951 assert_eq!(route.paths.len(), 1);
7952 assert_eq!(route.get_total_amount(), amt_msat);
7956 fn candidate_path_min() {
7957 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7958 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7959 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7960 // would add a connecting first_hop node that did not have enough contribution amount, leading
7961 // to a debug panic upon invalid path construction.
7962 let secp_ctx = Secp256k1::new();
7963 let logger = Arc::new(ln_test_utils::TestLogger::new());
7964 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7965 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7966 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7967 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7968 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7969 let config = UserConfig::default();
7971 // Values are taken from the fuzz input that uncovered this panic.
7972 let amt_msat = 7_4009_8048;
7973 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7974 let first_hops = vec![get_channel_details(
7975 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7978 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7979 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7980 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7981 short_channel_id: 6,
7984 cltv_expiry_delta: (6 << 4) | 0,
7985 htlc_minimum_msat: 0,
7986 htlc_maximum_msat: MAX_VALUE_MSAT,
7988 fee_proportional_millionths: 0,
7989 excess_data: Vec::new()
7991 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
7993 let htlc_min = 2_5165_8240;
7994 let blinded_hints = vec![
7996 fee_base_msat: 1_6778_3453,
7997 fee_proportional_millionths: 0,
7998 htlc_minimum_msat: htlc_min,
7999 htlc_maximum_msat: htlc_min * 100,
8000 cltv_expiry_delta: 10,
8001 features: BlindedHopFeatures::empty(),
8003 introduction_node_id: nodes[0],
8004 blinding_point: ln_test_utils::pubkey(42),
8006 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8007 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8011 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8012 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8013 .with_bolt12_features(bolt12_features.clone()).unwrap();
8014 let route_params = RouteParameters::from_payment_params_and_value(
8015 payment_params, amt_msat);
8016 let netgraph = network_graph.read_only();
8018 if let Err(LightningError { err, .. }) = get_route(
8019 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8020 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8023 assert_eq!(err, "Failed to find a path to the given destination");
8028 fn path_contribution_includes_min_htlc_overpay() {
8029 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8030 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8031 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8032 // selection, both tested here.
8033 let secp_ctx = Secp256k1::new();
8034 let logger = Arc::new(ln_test_utils::TestLogger::new());
8035 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8036 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8037 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8038 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8039 let config = UserConfig::default();
8041 // Values are taken from the fuzz input that uncovered this panic.
8042 let amt_msat = 562_0000;
8043 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8044 let first_hops = vec![
8045 get_channel_details(
8046 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8050 let htlc_mins = [49_0000, 1125_0000];
8051 let payment_params = {
8052 let blinded_path = BlindedPath {
8053 introduction_node_id: nodes[0],
8054 blinding_point: ln_test_utils::pubkey(42),
8056 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8057 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8060 let mut blinded_hints = Vec::new();
8061 for htlc_min in htlc_mins.iter() {
8062 blinded_hints.push((BlindedPayInfo {
8064 fee_proportional_millionths: 0,
8065 htlc_minimum_msat: *htlc_min,
8066 htlc_maximum_msat: *htlc_min * 100,
8067 cltv_expiry_delta: 10,
8068 features: BlindedHopFeatures::empty(),
8069 }, blinded_path.clone()));
8071 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8072 PaymentParameters::blinded(blinded_hints.clone())
8073 .with_bolt12_features(bolt12_features.clone()).unwrap()
8076 let netgraph = network_graph.read_only();
8077 let route_params = RouteParameters::from_payment_params_and_value(
8078 payment_params, amt_msat);
8079 let route = get_route(
8080 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8081 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8084 assert_eq!(route.paths.len(), 1);
8085 assert_eq!(route.get_total_amount(), amt_msat);
8089 fn first_hop_preferred_over_hint() {
8090 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8091 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8092 let secp_ctx = Secp256k1::new();
8093 let logger = Arc::new(ln_test_utils::TestLogger::new());
8094 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8095 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8096 let scorer = ln_test_utils::TestScorer::new();
8097 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8098 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8099 let config = UserConfig::default();
8101 let amt_msat = 1_000_000;
8102 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8104 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8105 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8106 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8107 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8108 short_channel_id: 1,
8111 cltv_expiry_delta: 42,
8112 htlc_minimum_msat: 1_000,
8113 htlc_maximum_msat: 10_000_000,
8115 fee_proportional_millionths: 0,
8116 excess_data: Vec::new()
8118 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8119 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8120 short_channel_id: 1,
8123 cltv_expiry_delta: 42,
8124 htlc_minimum_msat: 1_000,
8125 htlc_maximum_msat: 10_000_000,
8127 fee_proportional_millionths: 0,
8128 excess_data: Vec::new()
8131 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8132 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8133 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8134 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8135 short_channel_id: 2,
8138 cltv_expiry_delta: 42,
8139 htlc_minimum_msat: 1_000,
8140 htlc_maximum_msat: 10_000_000,
8142 fee_proportional_millionths: 0,
8143 excess_data: Vec::new()
8145 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8146 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8147 short_channel_id: 2,
8150 cltv_expiry_delta: 42,
8151 htlc_minimum_msat: 1_000,
8152 htlc_maximum_msat: 10_000_000,
8154 fee_proportional_millionths: 0,
8155 excess_data: Vec::new()
8158 let dest_node_id = nodes[2];
8160 let route_hint = RouteHint(vec![RouteHintHop {
8161 src_node_id: our_node_id,
8162 short_channel_id: 44,
8165 proportional_millionths: 0,
8167 cltv_expiry_delta: 10,
8168 htlc_minimum_msat: None,
8169 htlc_maximum_msat: Some(5_000_000),
8172 src_node_id: nodes[0],
8173 short_channel_id: 45,
8176 proportional_millionths: 0,
8178 cltv_expiry_delta: 10,
8179 htlc_minimum_msat: None,
8180 htlc_maximum_msat: None,
8183 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8184 .with_route_hints(vec![route_hint]).unwrap()
8185 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8186 let route_params = RouteParameters::from_payment_params_and_value(
8187 payment_params, amt_msat);
8189 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8191 let first_hop = get_channel_details(Some(1), nodes[0],
8192 channelmanager::provided_init_features(&config), 999_999);
8193 let first_hops = vec![first_hop];
8195 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8196 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8197 &Default::default(), &random_seed_bytes).unwrap();
8198 assert_eq!(route.paths.len(), 1);
8199 assert_eq!(route.get_total_amount(), amt_msat);
8200 assert_eq!(route.paths[0].hops.len(), 2);
8201 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8202 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8203 assert_eq!(route.get_total_fees(), 123);
8205 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8206 // for a first hop channel.
8207 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8208 first_hop.outbound_scid_alias = Some(44);
8209 let first_hops = vec![first_hop];
8211 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8212 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8213 &Default::default(), &random_seed_bytes);
8214 assert!(route_res.is_err());
8216 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8217 // use the cheaper second hop of the route hint.
8218 let mut first_hop = get_channel_details(Some(1), nodes[0],
8219 channelmanager::provided_init_features(&config), 10_000_000);
8220 first_hop.outbound_scid_alias = Some(44);
8221 let first_hops = vec![first_hop];
8223 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8224 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8225 &Default::default(), &random_seed_bytes).unwrap();
8226 assert_eq!(route.paths.len(), 1);
8227 assert_eq!(route.get_total_amount(), amt_msat);
8228 assert_eq!(route.paths[0].hops.len(), 2);
8229 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8230 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8231 assert_eq!(route.get_total_fees(), 123);
8235 fn allow_us_being_first_hint() {
8236 // Check that we consider a route hint even if we are the src of the first hop.
8237 let secp_ctx = Secp256k1::new();
8238 let logger = Arc::new(ln_test_utils::TestLogger::new());
8239 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8240 let scorer = ln_test_utils::TestScorer::new();
8241 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8242 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8243 let config = UserConfig::default();
8245 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8247 let amt_msat = 1_000_000;
8248 let dest_node_id = nodes[1];
8250 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8251 let first_hops = vec![first_hop];
8253 let route_hint = RouteHint(vec![RouteHintHop {
8254 src_node_id: our_node_id,
8255 short_channel_id: 44,
8258 proportional_millionths: 0,
8260 cltv_expiry_delta: 10,
8261 htlc_minimum_msat: None,
8262 htlc_maximum_msat: None,
8265 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8266 .with_route_hints(vec![route_hint]).unwrap()
8267 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8269 let route_params = RouteParameters::from_payment_params_and_value(
8270 payment_params, amt_msat);
8273 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8274 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8275 &Default::default(), &random_seed_bytes).unwrap();
8277 assert_eq!(route.paths.len(), 1);
8278 assert_eq!(route.get_total_amount(), amt_msat);
8279 assert_eq!(route.get_total_fees(), 0);
8280 assert_eq!(route.paths[0].hops.len(), 1);
8282 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8286 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8287 pub(crate) mod bench_utils {
8290 use std::time::Duration;
8292 use bitcoin::hashes::Hash;
8293 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8295 use crate::chain::transaction::OutPoint;
8296 use crate::routing::scoring::ScoreUpdate;
8297 use crate::sign::{EntropySource, KeysManager};
8298 use crate::ln::ChannelId;
8299 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8300 use crate::ln::features::Bolt11InvoiceFeatures;
8301 use crate::routing::gossip::NetworkGraph;
8302 use crate::util::config::UserConfig;
8303 use crate::util::ser::ReadableArgs;
8304 use crate::util::test_utils::TestLogger;
8306 /// Tries to open a network graph file, or panics with a URL to fetch it.
8307 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8308 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8309 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8310 .or_else(|_| { // Fall back to guessing based on the binary location
8311 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8312 let mut path = std::env::current_exe().unwrap();
8313 path.pop(); // lightning-...
8315 path.pop(); // debug
8316 path.pop(); // target
8317 path.push("lightning");
8318 path.push("net_graph-2023-01-18.bin");
8321 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8322 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8323 let mut path = std::env::current_exe().unwrap();
8324 path.pop(); // bench...
8326 path.pop(); // debug
8327 path.pop(); // target
8328 path.pop(); // bench
8329 path.push("lightning");
8330 path.push("net_graph-2023-01-18.bin");
8333 .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");
8334 #[cfg(require_route_graph_test)]
8335 return Ok(res.unwrap());
8336 #[cfg(not(require_route_graph_test))]
8340 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8341 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8344 pub(crate) fn payer_pubkey() -> PublicKey {
8345 let secp_ctx = Secp256k1::new();
8346 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8350 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8352 channel_id: ChannelId::new_zero(),
8353 counterparty: ChannelCounterparty {
8354 features: channelmanager::provided_init_features(&UserConfig::default()),
8356 unspendable_punishment_reserve: 0,
8357 forwarding_info: None,
8358 outbound_htlc_minimum_msat: None,
8359 outbound_htlc_maximum_msat: None,
8361 funding_txo: Some(OutPoint {
8362 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8365 short_channel_id: Some(1),
8366 inbound_scid_alias: None,
8367 outbound_scid_alias: None,
8368 channel_value_satoshis: 10_000_000_000,
8370 balance_msat: 10_000_000_000,
8371 outbound_capacity_msat: 10_000_000_000,
8372 next_outbound_htlc_minimum_msat: 0,
8373 next_outbound_htlc_limit_msat: 10_000_000_000,
8374 inbound_capacity_msat: 0,
8375 unspendable_punishment_reserve: None,
8376 confirmations_required: None,
8377 confirmations: None,
8378 force_close_spend_delay: None,
8380 is_channel_ready: true,
8383 inbound_htlc_minimum_msat: None,
8384 inbound_htlc_maximum_msat: None,
8386 feerate_sat_per_1000_weight: None,
8387 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8391 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8392 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8393 starting_amount: u64, route_count: usize,
8394 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8395 let payer = payer_pubkey();
8396 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8397 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8399 let nodes = graph.read_only().nodes().clone();
8400 let mut route_endpoints = Vec::new();
8401 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8402 // with some routes we picked being un-routable.
8403 for _ in 0..route_count * 3 / 2 {
8405 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8406 let src = PublicKey::from_slice(nodes.unordered_keys()
8407 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8408 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8409 let dst = PublicKey::from_slice(nodes.unordered_keys()
8410 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8411 let params = PaymentParameters::from_node_id(dst, 42)
8412 .with_bolt11_features(features.clone()).unwrap();
8413 let first_hop = first_hop(src);
8414 let amt_msat = starting_amount + seed % 1_000_000;
8415 let route_params = RouteParameters::from_payment_params_and_value(
8416 params.clone(), amt_msat);
8418 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8419 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8421 // ...and seed the scorer with success and failure data...
8422 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8423 let mut score_amt = seed % 1_000_000_000;
8425 // Generate fail/success paths for a wider range of potential amounts with
8426 // MPP enabled to give us a chance to apply penalties for more potential
8428 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8429 let params = PaymentParameters::from_node_id(dst, 42)
8430 .with_bolt11_features(mpp_features).unwrap();
8431 let route_params = RouteParameters::from_payment_params_and_value(
8432 params.clone(), score_amt);
8433 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8434 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8435 &random_seed_bytes);
8436 if let Ok(route) = route_res {
8437 for path in route.paths {
8438 if seed & 0x80 == 0 {
8439 scorer.payment_path_successful(&path, Duration::ZERO);
8441 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8442 scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8444 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8448 // If we couldn't find a path with a higer amount, reduce and try again.
8452 route_endpoints.push((first_hop, params, amt_msat));
8458 // Because we've changed channel scores, it's possible we'll take different routes to the
8459 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8460 // requires a too-high CLTV delta.
8461 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8462 let route_params = RouteParameters::from_payment_params_and_value(
8463 params.clone(), *amt_msat);
8464 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8465 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8467 route_endpoints.truncate(route_count);
8468 assert_eq!(route_endpoints.len(), route_count);
8476 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8477 use crate::sign::{EntropySource, KeysManager};
8478 use crate::ln::channelmanager;
8479 use crate::ln::features::Bolt11InvoiceFeatures;
8480 use crate::routing::gossip::NetworkGraph;
8481 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8482 use crate::util::config::UserConfig;
8483 use crate::util::logger::{Logger, Record};
8484 use crate::util::test_utils::TestLogger;
8486 use criterion::Criterion;
8488 struct DummyLogger {}
8489 impl Logger for DummyLogger {
8490 fn log(&self, _record: Record) {}
8493 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8494 let logger = TestLogger::new();
8495 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8496 let scorer = FixedPenaltyScorer::with_penalty(0);
8497 generate_routes(bench, &network_graph, scorer, &Default::default(),
8498 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8501 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8502 let logger = TestLogger::new();
8503 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8504 let scorer = FixedPenaltyScorer::with_penalty(0);
8505 generate_routes(bench, &network_graph, scorer, &Default::default(),
8506 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8507 "generate_mpp_routes_with_zero_penalty_scorer");
8510 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8511 let logger = TestLogger::new();
8512 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8513 let params = ProbabilisticScoringFeeParameters::default();
8514 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8515 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8516 "generate_routes_with_probabilistic_scorer");
8519 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8520 let logger = TestLogger::new();
8521 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8522 let params = ProbabilisticScoringFeeParameters::default();
8523 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8524 generate_routes(bench, &network_graph, scorer, ¶ms,
8525 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8526 "generate_mpp_routes_with_probabilistic_scorer");
8529 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8530 let logger = TestLogger::new();
8531 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8532 let params = ProbabilisticScoringFeeParameters::default();
8533 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8534 generate_routes(bench, &network_graph, scorer, ¶ms,
8535 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8536 "generate_large_mpp_routes_with_probabilistic_scorer");
8539 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8540 let logger = TestLogger::new();
8541 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8542 let mut params = ProbabilisticScoringFeeParameters::default();
8543 params.linear_success_probability = false;
8544 let scorer = ProbabilisticScorer::new(
8545 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8546 generate_routes(bench, &network_graph, scorer, ¶ms,
8547 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8548 "generate_routes_with_nonlinear_probabilistic_scorer");
8551 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8552 let logger = TestLogger::new();
8553 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8554 let mut params = ProbabilisticScoringFeeParameters::default();
8555 params.linear_success_probability = false;
8556 let scorer = ProbabilisticScorer::new(
8557 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8558 generate_routes(bench, &network_graph, scorer, ¶ms,
8559 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8560 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8563 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8564 let logger = TestLogger::new();
8565 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8566 let mut params = ProbabilisticScoringFeeParameters::default();
8567 params.linear_success_probability = false;
8568 let scorer = ProbabilisticScorer::new(
8569 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8570 generate_routes(bench, &network_graph, scorer, ¶ms,
8571 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8572 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8575 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8576 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8577 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8578 bench_name: &'static str,
8580 let payer = bench_utils::payer_pubkey();
8581 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8582 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8584 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8585 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8587 // ...then benchmark finding paths between the nodes we learned.
8589 bench.bench_function(bench_name, |b| b.iter(|| {
8590 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8591 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8592 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8593 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());