1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
29 use crate::prelude::*;
30 use crate::sync::Mutex;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
51 /// Creates a new router.
52 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
53 let random_seed_bytes = Mutex::new(random_seed_bytes);
54 Self { network_graph, logger, random_seed_bytes, scorer, score_params }
58 impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
65 params: &RouteParameters,
66 first_hops: Option<&[&ChannelDetails]>,
67 inflight_htlcs: InFlightHtlcs
68 ) -> Result<Route, LightningError> {
69 let random_seed_bytes = {
70 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
71 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).to_byte_array();
72 *locked_random_seed_bytes
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
83 /// A trait defining behavior for routing a payment.
85 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
87 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
88 /// and [`RouteParameters::final_value_msat`], respectively.
90 &self, payer: &PublicKey, route_params: &RouteParameters,
91 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
92 ) -> Result<Route, LightningError>;
94 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
96 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
97 /// and [`RouteParameters::final_value_msat`], respectively.
99 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
101 fn find_route_with_id(
102 &self, payer: &PublicKey, route_params: &RouteParameters,
103 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
104 _payment_hash: PaymentHash, _payment_id: PaymentId
105 ) -> Result<Route, LightningError> {
106 self.find_route(payer, route_params, first_hops, inflight_htlcs)
110 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
112 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
115 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
116 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
118 // Maps a channel's short channel id and its direction to the liquidity used up.
119 inflight_htlcs: &'a InFlightHtlcs,
121 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
122 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
123 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
124 ScorerAccountingForInFlightHtlcs {
131 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
132 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
133 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
134 let target = match candidate.target() {
135 Some(target) => target,
136 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
138 let short_channel_id = match candidate.short_channel_id() {
139 Some(short_channel_id) => short_channel_id,
140 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
142 let source = candidate.source();
143 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
144 &source, &target, short_channel_id
146 let usage = ChannelUsage {
147 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
151 self.scorer.channel_penalty_msat(candidate, usage, score_params)
153 self.scorer.channel_penalty_msat(candidate, usage, score_params)
158 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
159 /// in-use channel liquidity.
161 pub struct InFlightHtlcs(
162 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
163 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
164 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
166 HashMap<(u64, bool), u64>
170 /// Constructs an empty `InFlightHtlcs`.
171 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
173 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
174 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
175 if path.hops.is_empty() { return };
177 let mut cumulative_msat = 0;
178 if let Some(tail) = &path.blinded_tail {
179 cumulative_msat += tail.final_value_msat;
182 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
183 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
184 // the router excludes the payer node. In the following lines, the payer's information is
185 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
186 // in our sliding window of two.
187 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
188 .map(|hop| hop.pubkey)
189 .chain(core::iter::once(payer_node_id));
191 // Taking the reversed vector from above, we zip it with just the reversed hops list to
192 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
193 // the total amount sent.
194 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
195 cumulative_msat += next_hop.fee_msat;
197 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
198 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
199 .or_insert(cumulative_msat);
203 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
205 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
207 .entry((channel_scid, source < target))
208 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
209 .or_insert(used_msat);
212 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
214 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
215 self.0.get(&(channel_scid, source < target)).map(|v| *v)
219 impl Writeable for InFlightHtlcs {
220 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
223 impl Readable for InFlightHtlcs {
224 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
225 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
226 Ok(Self(infight_map))
230 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
231 /// that leads to it.
232 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
233 pub struct RouteHop {
234 /// The node_id of the node at this hop.
235 pub pubkey: PublicKey,
236 /// The node_announcement features of the node at this hop. For the last hop, these may be
237 /// amended to match the features present in the invoice this node generated.
238 pub node_features: NodeFeatures,
239 /// The channel that should be used from the previous hop to reach this node.
240 pub short_channel_id: u64,
241 /// The channel_announcement features of the channel that should be used from the previous hop
242 /// to reach this node.
243 pub channel_features: ChannelFeatures,
244 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
245 /// If this is the last hop in [`Path::hops`]:
246 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
247 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
249 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
251 /// The CLTV delta added for this hop.
252 /// If this is the last hop in [`Path::hops`]:
253 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
254 /// * otherwise, this is the CLTV delta expected at the destination
256 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
257 pub cltv_expiry_delta: u32,
258 /// Indicates whether this hop is possibly announced in the public network graph.
260 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
261 /// either know for sure it's announced in the public graph, or if any public channels exist
262 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
263 /// the channel to be unannounced.
265 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
266 pub maybe_announced_channel: bool,
269 impl_writeable_tlv_based!(RouteHop, {
270 (0, pubkey, required),
271 (1, maybe_announced_channel, (default_value, true)),
272 (2, node_features, required),
273 (4, short_channel_id, required),
274 (6, channel_features, required),
275 (8, fee_msat, required),
276 (10, cltv_expiry_delta, required),
279 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
280 /// their [`Bolt12Invoice`].
282 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
283 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
284 pub struct BlindedTail {
285 /// The hops of the [`BlindedPath`] provided by the recipient.
287 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
288 pub hops: Vec<BlindedHop>,
289 /// The blinding point of the [`BlindedPath`] provided by the recipient.
291 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
292 pub blinding_point: PublicKey,
293 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
294 /// inferring the destination. May be 0.
295 pub excess_final_cltv_expiry_delta: u32,
296 /// The total amount paid on this [`Path`], excluding the fees.
297 pub final_value_msat: u64,
300 impl_writeable_tlv_based!(BlindedTail, {
301 (0, hops, required_vec),
302 (2, blinding_point, required),
303 (4, excess_final_cltv_expiry_delta, required),
304 (6, final_value_msat, required),
307 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
308 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
309 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
311 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
312 pub hops: Vec<RouteHop>,
313 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
314 pub blinded_tail: Option<BlindedTail>,
318 /// Gets the fees for a given path, excluding any excess paid to the recipient.
319 pub fn fee_msat(&self) -> u64 {
320 match &self.blinded_tail {
321 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
323 // Do not count last hop of each path since that's the full value of the payment
324 self.hops.split_last().map_or(0,
325 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
330 /// Gets the total amount paid on this [`Path`], excluding the fees.
331 pub fn final_value_msat(&self) -> u64 {
332 match &self.blinded_tail {
333 Some(blinded_tail) => blinded_tail.final_value_msat,
334 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
338 /// Gets the final hop's CLTV expiry delta.
339 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
340 match &self.blinded_tail {
342 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
347 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
348 /// it can take multiple paths. Each path is composed of one or more hops through the network.
349 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
351 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
352 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
354 pub paths: Vec<Path>,
355 /// The `route_params` parameter passed to [`find_route`].
357 /// This is used by `ChannelManager` to track information which may be required for retries.
359 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
360 pub route_params: Option<RouteParameters>,
364 /// Returns the total amount of fees paid on this [`Route`].
366 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
367 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
368 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
370 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
371 pub fn get_total_fees(&self) -> u64 {
372 let overpaid_value_msat = self.route_params.as_ref()
373 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
374 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
377 /// Returns the total amount paid on this [`Route`], excluding the fees.
379 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
380 /// we had to reach the [`htlc_minimum_msat`] limits.
382 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
383 pub fn get_total_amount(&self) -> u64 {
384 self.paths.iter().map(|path| path.final_value_msat()).sum()
388 impl fmt::Display for Route {
389 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
390 log_route!(self).fmt(f)
394 const SERIALIZATION_VERSION: u8 = 1;
395 const MIN_SERIALIZATION_VERSION: u8 = 1;
397 impl Writeable for Route {
398 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
399 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
400 (self.paths.len() as u64).write(writer)?;
401 let mut blinded_tails = Vec::new();
402 for path in self.paths.iter() {
403 (path.hops.len() as u8).write(writer)?;
404 for (idx, hop) in path.hops.iter().enumerate() {
406 if let Some(blinded_tail) = &path.blinded_tail {
407 if blinded_tails.is_empty() {
408 blinded_tails = Vec::with_capacity(path.hops.len());
410 blinded_tails.push(None);
413 blinded_tails.push(Some(blinded_tail));
414 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
417 write_tlv_fields!(writer, {
418 // For compatibility with LDK versions prior to 0.0.117, we take the individual
419 // RouteParameters' fields and reconstruct them on read.
420 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
421 (2, blinded_tails, optional_vec),
422 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
423 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
429 impl Readable for Route {
430 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
431 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
432 let path_count: u64 = Readable::read(reader)?;
433 if path_count == 0 { return Err(DecodeError::InvalidValue); }
434 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
435 let mut min_final_cltv_expiry_delta = u32::max_value();
436 for _ in 0..path_count {
437 let hop_count: u8 = Readable::read(reader)?;
438 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
439 for _ in 0..hop_count {
440 hops.push(Readable::read(reader)?);
442 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
443 min_final_cltv_expiry_delta =
444 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
445 paths.push(Path { hops, blinded_tail: None });
447 _init_and_read_len_prefixed_tlv_fields!(reader, {
448 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
449 (2, blinded_tails, optional_vec),
450 (3, final_value_msat, option),
451 (5, max_total_routing_fee_msat, option)
453 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
454 if blinded_tails.len() != 0 {
455 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
456 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
457 path.blinded_tail = blinded_tail_opt;
461 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
462 let route_params = match (payment_params, final_value_msat) {
463 (Some(payment_params), Some(final_value_msat)) => {
464 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
469 Ok(Route { paths, route_params })
473 /// Parameters needed to find a [`Route`].
475 /// Passed to [`find_route`] and [`build_route_from_hops`].
476 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
477 pub struct RouteParameters {
478 /// The parameters of the failed payment path.
479 pub payment_params: PaymentParameters,
481 /// The amount in msats sent on the failed payment path.
482 pub final_value_msat: u64,
484 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
486 /// This limit also applies to the total fees that may arise while retrying failed payment
489 /// Note that values below a few sats may result in some paths being spuriously ignored.
490 pub max_total_routing_fee_msat: Option<u64>,
493 impl RouteParameters {
494 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
496 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
497 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
498 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
502 impl Writeable for RouteParameters {
503 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
504 write_tlv_fields!(writer, {
505 (0, self.payment_params, required),
506 (1, self.max_total_routing_fee_msat, option),
507 (2, self.final_value_msat, required),
508 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
509 // `RouteParameters` directly. For compatibility, we write it here.
510 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
516 impl Readable for RouteParameters {
517 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
518 _init_and_read_len_prefixed_tlv_fields!(reader, {
519 (0, payment_params, (required: ReadableArgs, 0)),
520 (1, max_total_routing_fee_msat, option),
521 (2, final_value_msat, required),
522 (4, final_cltv_delta, option),
524 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
525 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
526 if final_cltv_expiry_delta == &0 {
527 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
532 final_value_msat: final_value_msat.0.unwrap(),
533 max_total_routing_fee_msat,
538 /// Maximum total CTLV difference we allow for a full payment path.
539 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
541 /// Maximum number of paths we allow an (MPP) payment to have.
542 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
543 // limits, but for now more than 10 paths likely carries too much one-path failure.
544 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
546 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
548 // The median hop CLTV expiry delta currently seen in the network.
549 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
551 // During routing, we only consider paths shorter than our maximum length estimate.
552 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
553 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
554 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
556 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
557 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
558 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
559 // (payment_secret and total_msat) = 93 bytes for the final hop.
560 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
561 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
562 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
564 /// Information used to route a payment.
565 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
566 pub struct PaymentParameters {
567 /// Information about the payee, such as their features and route hints for their channels.
570 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
571 pub expiry_time: Option<u64>,
573 /// The maximum total CLTV delta we accept for the route.
574 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
575 pub max_total_cltv_expiry_delta: u32,
577 /// The maximum number of paths that may be used by (MPP) payments.
578 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
579 pub max_path_count: u8,
581 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
582 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
583 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
584 /// increasing failure probability for those paths.
586 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
587 /// restriction have been found. While paths which meet this criteria will be searched for, it
588 /// is ultimately up to the scorer to select them over other paths.
590 /// A value of 0 will allow payments up to and including a channel's total announced usable
591 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
594 pub max_channel_saturation_power_of_half: u8,
596 /// A list of SCIDs which this payment was previously attempted over and which caused the
597 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
599 pub previously_failed_channels: Vec<u64>,
602 impl Writeable for PaymentParameters {
603 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
604 let mut clear_hints = &vec![];
605 let mut blinded_hints = &vec![];
607 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
608 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
610 write_tlv_fields!(writer, {
611 (0, self.payee.node_id(), option),
612 (1, self.max_total_cltv_expiry_delta, required),
613 (2, self.payee.features(), option),
614 (3, self.max_path_count, required),
615 (4, *clear_hints, required_vec),
616 (5, self.max_channel_saturation_power_of_half, required),
617 (6, self.expiry_time, option),
618 (7, self.previously_failed_channels, required_vec),
619 (8, *blinded_hints, optional_vec),
620 (9, self.payee.final_cltv_expiry_delta(), option),
626 impl ReadableArgs<u32> for PaymentParameters {
627 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
628 _init_and_read_len_prefixed_tlv_fields!(reader, {
629 (0, payee_pubkey, option),
630 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
631 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
632 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
633 (4, clear_route_hints, required_vec),
634 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
635 (6, expiry_time, option),
636 (7, previously_failed_channels, optional_vec),
637 (8, blinded_route_hints, optional_vec),
638 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
640 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
641 let payee = if blinded_route_hints.len() != 0 {
642 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
644 route_hints: blinded_route_hints,
645 features: features.and_then(|f: Features| f.bolt12()),
649 route_hints: clear_route_hints,
650 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
651 features: features.and_then(|f| f.bolt11()),
652 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
656 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
657 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
659 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
661 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
667 impl PaymentParameters {
668 /// Creates a payee with the node id of the given `pubkey`.
670 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
672 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
674 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
676 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
677 max_path_count: DEFAULT_MAX_PATH_COUNT,
678 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
679 previously_failed_channels: Vec::new(),
683 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
685 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
688 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
689 /// whether your router will be allowed to find a multi-part route for this payment. If you
690 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
691 /// [`RecipientOnionFields::secret_only`].
693 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
694 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
695 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
696 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
697 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
700 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
701 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
702 /// [`PaymentParameters::expiry_time`].
703 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
704 Self::blinded(invoice.payment_paths().to_vec())
705 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
706 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
709 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
710 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
712 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
714 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
715 max_path_count: DEFAULT_MAX_PATH_COUNT,
716 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
717 previously_failed_channels: Vec::new(),
721 /// Includes the payee's features. Errors if the parameters were not initialized with
722 /// [`PaymentParameters::from_bolt12_invoice`].
724 /// This is not exported to bindings users since bindings don't support move semantics
725 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
727 Payee::Clear { .. } => Err(()),
728 Payee::Blinded { route_hints, .. } =>
729 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
733 /// Includes the payee's features. Errors if the parameters were initialized with
734 /// [`PaymentParameters::from_bolt12_invoice`].
736 /// This is not exported to bindings users since bindings don't support move semantics
737 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
739 Payee::Blinded { .. } => Err(()),
740 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
742 payee: Payee::Clear {
743 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
749 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
750 /// [`PaymentParameters::from_bolt12_invoice`].
752 /// This is not exported to bindings users since bindings don't support move semantics
753 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
755 Payee::Blinded { .. } => Err(()),
756 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
758 payee: Payee::Clear {
759 route_hints, node_id, features, final_cltv_expiry_delta,
765 /// Includes a payment expiration in seconds relative to the UNIX epoch.
767 /// This is not exported to bindings users since bindings don't support move semantics
768 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
769 Self { expiry_time: Some(expiry_time), ..self }
772 /// Includes a limit for the total CLTV expiry delta which is considered during routing
774 /// This is not exported to bindings users since bindings don't support move semantics
775 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
776 Self { max_total_cltv_expiry_delta, ..self }
779 /// Includes a limit for the maximum number of payment paths that may be used.
781 /// This is not exported to bindings users since bindings don't support move semantics
782 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
783 Self { max_path_count, ..self }
786 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
787 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
789 /// This is not exported to bindings users since bindings don't support move semantics
790 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
791 Self { max_channel_saturation_power_of_half, ..self }
795 /// The recipient of a payment, differing based on whether they've hidden their identity with route
797 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
799 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
800 /// will be included in the final [`Route`].
802 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
804 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
805 /// Features supported by the payee.
807 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
809 features: Option<Bolt12InvoiceFeatures>,
811 /// The recipient included these route hints in their BOLT11 invoice.
813 /// The node id of the payee.
815 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
816 route_hints: Vec<RouteHint>,
817 /// Features supported by the payee.
819 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
820 /// does not contain any features.
822 /// [`for_keysend`]: PaymentParameters::for_keysend
823 features: Option<Bolt11InvoiceFeatures>,
824 /// The minimum CLTV delta at the end of the route. This value must not be zero.
825 final_cltv_expiry_delta: u32,
830 fn node_id(&self) -> Option<PublicKey> {
832 Self::Clear { node_id, .. } => Some(*node_id),
836 fn node_features(&self) -> Option<NodeFeatures> {
838 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
839 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
842 fn supports_basic_mpp(&self) -> bool {
844 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
845 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
848 fn features(&self) -> Option<FeaturesRef> {
850 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
851 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
854 fn final_cltv_expiry_delta(&self) -> Option<u32> {
856 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
860 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
862 Self::Blinded { route_hints, .. } => &route_hints[..],
863 Self::Clear { .. } => &[]
867 fn unblinded_route_hints(&self) -> &[RouteHint] {
869 Self::Blinded { .. } => &[],
870 Self::Clear { route_hints, .. } => &route_hints[..]
875 enum FeaturesRef<'a> {
876 Bolt11(&'a Bolt11InvoiceFeatures),
877 Bolt12(&'a Bolt12InvoiceFeatures),
880 Bolt11(Bolt11InvoiceFeatures),
881 Bolt12(Bolt12InvoiceFeatures),
885 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
887 Self::Bolt12(f) => Some(f),
891 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
893 Self::Bolt11(f) => Some(f),
899 impl<'a> Writeable for FeaturesRef<'a> {
900 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
902 Self::Bolt11(f) => Ok(f.write(w)?),
903 Self::Bolt12(f) => Ok(f.write(w)?),
908 impl ReadableArgs<bool> for Features {
909 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
910 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
911 Ok(Self::Bolt12(Readable::read(reader)?))
915 /// A list of hops along a payment path terminating with a channel to the recipient.
916 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
917 pub struct RouteHint(pub Vec<RouteHintHop>);
919 impl Writeable for RouteHint {
920 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
921 (self.0.len() as u64).write(writer)?;
922 for hop in self.0.iter() {
929 impl Readable for RouteHint {
930 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
931 let hop_count: u64 = Readable::read(reader)?;
932 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
933 for _ in 0..hop_count {
934 hops.push(Readable::read(reader)?);
940 /// A channel descriptor for a hop along a payment path.
942 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
943 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
944 /// fields not supported in BOLT 11 will be stripped.
945 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
946 pub struct RouteHintHop {
947 /// The node_id of the non-target end of the route
948 pub src_node_id: PublicKey,
949 /// The short_channel_id of this channel
950 pub short_channel_id: u64,
951 /// The fees which must be paid to use this channel
952 pub fees: RoutingFees,
953 /// The difference in CLTV values between this node and the next node.
954 pub cltv_expiry_delta: u16,
955 /// The minimum value, in msat, which must be relayed to the next hop.
956 pub htlc_minimum_msat: Option<u64>,
957 /// The maximum value in msat available for routing with a single HTLC.
958 pub htlc_maximum_msat: Option<u64>,
961 impl_writeable_tlv_based!(RouteHintHop, {
962 (0, src_node_id, required),
963 (1, htlc_minimum_msat, option),
964 (2, short_channel_id, required),
965 (3, htlc_maximum_msat, option),
967 (6, cltv_expiry_delta, required),
970 #[derive(Eq, PartialEq)]
971 struct RouteGraphNode {
973 lowest_fee_to_node: u64,
974 total_cltv_delta: u32,
975 // The maximum value a yet-to-be-constructed payment path might flow through this node.
976 // This value is upper-bounded by us by:
977 // - how much is needed for a path being constructed
978 // - how much value can channels following this node (up to the destination) can contribute,
979 // considering their capacity and fees
980 value_contribution_msat: u64,
981 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
982 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
983 path_htlc_minimum_msat: u64,
984 /// All penalties incurred from this hop on the way to the destination, as calculated using
986 path_penalty_msat: u64,
987 /// The number of hops walked up to this node.
988 path_length_to_node: u8,
991 impl cmp::Ord for RouteGraphNode {
992 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
993 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
994 .saturating_add(other.path_penalty_msat);
995 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
996 .saturating_add(self.path_penalty_msat);
997 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
1001 impl cmp::PartialOrd for RouteGraphNode {
1002 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1003 Some(self.cmp(other))
1007 /// A wrapper around the various hop representations.
1009 /// Can be used to examine the properties of a hop,
1010 /// potentially to decide whether to include it in a route.
1011 #[derive(Clone, Debug)]
1012 pub enum CandidateRouteHop<'a> {
1013 /// A hop from the payer, where the outbound liquidity is known.
1015 /// Channel details of the first hop
1017 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1018 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1020 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1021 details: &'a ChannelDetails,
1022 /// The node id of the payer, which is also the source side of this candidate route hop.
1025 /// A hop found in the [`ReadOnlyNetworkGraph`].
1027 /// Information about the channel, including potentially its capacity and
1028 /// direction-specific information.
1029 info: DirectedChannelInfo<'a>,
1030 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1032 short_channel_id: u64,
1034 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1036 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1037 /// terminate at the payee.
1039 /// Information about the private hop communicated via BOLT 11.
1040 hint: &'a RouteHintHop,
1041 /// Node id of the next hop in BOLT 11 route hint.
1042 target_node_id: NodeId
1044 /// A blinded path which starts with an introduction point and ultimately terminates with the
1047 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1048 /// `None` in this state.
1050 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1051 /// path, the full path is treated as a single [`CandidateRouteHop`].
1053 /// Information about the blinded path including the fee, HTLC amount limits, and
1054 /// cryptographic material required to build an HTLC through the given path.
1055 hint: &'a (BlindedPayInfo, BlindedPath),
1056 /// Index of the hint in the original list of blinded hints.
1058 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1059 /// a short channel ID for this hop.
1062 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1064 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1065 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1066 /// payee's identity - it's the introduction point!
1068 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1069 /// to the hops *between* the introduction node and the destination.
1071 /// This primarily exists to track that we need to included a blinded path at the end of our
1072 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1074 /// Information about the blinded path including the fee, HTLC amount limits, and
1075 /// cryptographic material required to build an HTLC terminating with the given path.
1077 /// Note that the [`BlindedPayInfo`] is ignored here.
1078 hint: &'a (BlindedPayInfo, BlindedPath),
1079 /// Index of the hint in the original list of blinded hints.
1081 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1082 /// a short channel ID for this hop.
1087 impl<'a> CandidateRouteHop<'a> {
1088 /// Returns the short channel ID for this hop, if one is known.
1090 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1091 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1093 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1094 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1095 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1096 /// (which is always true for channels which are funded and ready for use).
1098 /// In other words, this should always return `Some` as long as the candidate hop is not a
1099 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1101 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1102 /// define a global namespace.
1104 fn short_channel_id(&self) -> Option<u64> {
1106 CandidateRouteHop::FirstHop { details, .. } => details.get_outbound_payment_scid(),
1107 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1108 CandidateRouteHop::PrivateHop { hint, .. } => Some(hint.short_channel_id),
1109 CandidateRouteHop::Blinded { .. } => None,
1110 CandidateRouteHop::OneHopBlinded { .. } => None,
1114 /// Returns the globally unique short channel ID for this hop, if one is known.
1116 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1117 /// from the public network graph), and thus the short channel ID we have for this channel is
1118 /// globally unique and identifies this channel in a global namespace.
1120 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1122 CandidateRouteHop::FirstHop { details, .. } => if details.is_public { details.short_channel_id } else { None },
1123 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1124 CandidateRouteHop::PrivateHop { .. } => None,
1125 CandidateRouteHop::Blinded { .. } => None,
1126 CandidateRouteHop::OneHopBlinded { .. } => None,
1130 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1131 fn features(&self) -> ChannelFeatures {
1133 CandidateRouteHop::FirstHop { details, .. } => details.counterparty.features.to_context(),
1134 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1135 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1136 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1137 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1141 /// Returns cltv_expiry_delta for this hop.
1143 pub fn cltv_expiry_delta(&self) -> u32 {
1145 CandidateRouteHop::FirstHop { .. } => 0,
1146 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1147 CandidateRouteHop::PrivateHop { hint, .. } => hint.cltv_expiry_delta as u32,
1148 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1149 CandidateRouteHop::OneHopBlinded { .. } => 0,
1153 /// Returns the htlc_minimum_msat for this hop.
1155 pub fn htlc_minimum_msat(&self) -> u64 {
1157 CandidateRouteHop::FirstHop { details, .. } => details.next_outbound_htlc_minimum_msat,
1158 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1159 CandidateRouteHop::PrivateHop { hint, .. } => hint.htlc_minimum_msat.unwrap_or(0),
1160 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1161 CandidateRouteHop::OneHopBlinded { .. } => 0,
1165 /// Returns the fees for this hop.
1167 pub fn fees(&self) -> RoutingFees {
1169 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1170 base_msat: 0, proportional_millionths: 0,
1172 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1173 CandidateRouteHop::PrivateHop { hint, .. } => hint.fees,
1174 CandidateRouteHop::Blinded { hint, .. } => {
1176 base_msat: hint.0.fee_base_msat,
1177 proportional_millionths: hint.0.fee_proportional_millionths
1180 CandidateRouteHop::OneHopBlinded { .. } =>
1181 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1185 fn effective_capacity(&self) -> EffectiveCapacity {
1187 CandidateRouteHop::FirstHop { details, .. } => EffectiveCapacity::ExactLiquidity {
1188 liquidity_msat: details.next_outbound_htlc_limit_msat,
1190 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1191 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. } =>
1192 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1193 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. } =>
1194 EffectiveCapacity::Infinite,
1195 CandidateRouteHop::Blinded { hint, .. } =>
1196 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1197 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1201 /// Returns an ID describing the given hop.
1203 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1205 fn id(&self) -> CandidateHopId {
1207 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1208 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1209 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1212 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1214 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1220 /// Returns the source node id of current hop.
1222 /// Source node id refers to the hop forwarding the payment.
1224 /// For `FirstHop` we return payer's node id.
1226 pub fn source(&self) -> NodeId {
1228 CandidateRouteHop::FirstHop { node_id, .. } => *node_id,
1229 CandidateRouteHop::PublicHop { info, .. } => *info.source(),
1230 CandidateRouteHop::PrivateHop { hint, .. } => hint.src_node_id.into(),
1231 CandidateRouteHop::Blinded { hint, .. } => hint.1.introduction_node_id.into(),
1232 CandidateRouteHop::OneHopBlinded { hint, .. } => hint.1.introduction_node_id.into(),
1235 /// Returns the target node id of this hop, if known.
1237 /// Target node id refers to the hop receiving the payment.
1239 /// For `Blinded` and `OneHopBlinded` we return `None` because next hop is blinded.
1241 pub fn target(&self) -> Option<NodeId> {
1243 CandidateRouteHop::FirstHop { details, .. } => Some(details.counterparty.node_id.into()),
1244 CandidateRouteHop::PublicHop { info, .. } => Some(*info.target()),
1245 CandidateRouteHop::PrivateHop { target_node_id, .. } => Some(*target_node_id),
1246 CandidateRouteHop::Blinded { .. } => None,
1247 CandidateRouteHop::OneHopBlinded { .. } => None,
1252 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1254 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1256 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1257 /// isn't guaranteed to be unique at all.
1259 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1260 /// difficult-to-use API.
1261 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1262 enum CandidateHopId {
1263 /// Contains (scid, src_node_id < target_node_id)
1265 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1270 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1271 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1273 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1274 EffectiveCapacity::Infinite => u64::max_value(),
1275 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1276 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1277 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1278 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1279 // expected to have been generated from up-to-date capacity information.
1280 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1281 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1282 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1286 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1287 -> bool where I1::Item: PartialEq<I2::Item> {
1289 let a = iter_a.next();
1290 let b = iter_b.next();
1291 if a.is_none() && b.is_none() { return true; }
1292 if a.is_none() || b.is_none() { return false; }
1293 if a.unwrap().ne(&b.unwrap()) { return false; }
1297 /// It's useful to keep track of the hops associated with the fees required to use them,
1298 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1299 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1300 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1302 struct PathBuildingHop<'a> {
1303 candidate: CandidateRouteHop<'a>,
1306 /// All the fees paid *after* this channel on the way to the destination
1307 next_hops_fee_msat: u64,
1308 /// Fee paid for the use of the current channel (see candidate.fees()).
1309 /// The value will be actually deducted from the counterparty balance on the previous link.
1310 hop_use_fee_msat: u64,
1311 /// Used to compare channels when choosing the for routing.
1312 /// Includes paying for the use of a hop and the following hops, as well as
1313 /// an estimated cost of reaching this hop.
1314 /// Might get stale when fees are recomputed. Primarily for internal use.
1315 total_fee_msat: u64,
1316 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1317 /// walk and may be invalid thereafter.
1318 path_htlc_minimum_msat: u64,
1319 /// All penalties incurred from this channel on the way to the destination, as calculated using
1320 /// channel scoring.
1321 path_penalty_msat: u64,
1322 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1323 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1324 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1325 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1326 /// avoid processing them again.
1327 was_processed: bool,
1328 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1329 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1330 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1331 // value_contribution_msat, which requires tracking it here. See comments below where it is
1332 // used for more info.
1333 value_contribution_msat: u64,
1336 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1337 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1338 let mut debug_struct = f.debug_struct("PathBuildingHop");
1340 .field("node_id", &self.candidate.target())
1341 .field("short_channel_id", &self.candidate.short_channel_id())
1342 .field("total_fee_msat", &self.total_fee_msat)
1343 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1344 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1345 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
1346 .field("path_penalty_msat", &self.path_penalty_msat)
1347 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1348 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1349 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1350 let debug_struct = debug_struct
1351 .field("value_contribution_msat", &self.value_contribution_msat);
1352 debug_struct.finish()
1356 // Instantiated with a list of hops with correct data in them collected during path finding,
1357 // an instance of this struct should be further modified only via given methods.
1359 struct PaymentPath<'a> {
1360 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1363 impl<'a> PaymentPath<'a> {
1364 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1365 fn get_value_msat(&self) -> u64 {
1366 self.hops.last().unwrap().0.fee_msat
1369 fn get_path_penalty_msat(&self) -> u64 {
1370 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1373 fn get_total_fee_paid_msat(&self) -> u64 {
1374 if self.hops.len() < 1 {
1378 // Can't use next_hops_fee_msat because it gets outdated.
1379 for (i, (hop, _)) in self.hops.iter().enumerate() {
1380 if i != self.hops.len() - 1 {
1381 result += hop.fee_msat;
1387 fn get_cost_msat(&self) -> u64 {
1388 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1391 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1392 // to change fees may result in an inconsistency.
1394 // Sometimes we call this function right after constructing a path which is inconsistent in
1395 // that it the value being transferred has decreased while we were doing path finding, leading
1396 // to the fees being paid not lining up with the actual limits.
1398 // Note that this function is not aware of the available_liquidity limit, and thus does not
1399 // support increasing the value being transferred beyond what was selected during the initial
1402 // Returns the amount that this path contributes to the total payment value, which may be greater
1403 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1404 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1405 let mut extra_contribution_msat = 0;
1406 let mut total_fee_paid_msat = 0 as u64;
1407 for i in (0..self.hops.len()).rev() {
1408 let last_hop = i == self.hops.len() - 1;
1410 // For non-last-hop, this value will represent the fees paid on the current hop. It
1411 // will consist of the fees for the use of the next hop, and extra fees to match
1412 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1413 let mut cur_hop_fees_msat = 0;
1415 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1418 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1419 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1420 cur_hop.path_penalty_msat += extra_contribution_msat;
1421 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1422 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1423 // set it too high just to maliciously take more fees by exploiting this
1424 // match htlc_minimum_msat logic.
1425 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1426 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1427 // Note that there is a risk that *previous hops* (those closer to us, as we go
1428 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1430 // This might make us end up with a broken route, although this should be super-rare
1431 // in practice, both because of how healthy channels look like, and how we pick
1432 // channels in add_entry.
1433 // Also, this can't be exploited more heavily than *announce a free path and fail
1435 cur_hop_transferred_amount_msat += extra_fees_msat;
1437 // We remember and return the extra fees on the final hop to allow accounting for
1438 // them in the path's value contribution.
1440 extra_contribution_msat = extra_fees_msat;
1442 total_fee_paid_msat += extra_fees_msat;
1443 cur_hop_fees_msat += extra_fees_msat;
1448 // Final hop is a special case: it usually has just value_msat (by design), but also
1449 // it still could overpay for the htlc_minimum_msat.
1450 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1452 // Propagate updated fees for the use of the channels to one hop back, where they
1453 // will be actually paid (fee_msat). The last hop is handled above separately.
1454 cur_hop.fee_msat = cur_hop_fees_msat;
1457 // Fee for the use of the current hop which will be deducted on the previous hop.
1458 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1459 // this channel is free for us.
1461 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1462 cur_hop.hop_use_fee_msat = new_fee;
1463 total_fee_paid_msat += new_fee;
1465 // It should not be possible because this function is called only to reduce the
1466 // value. In that case, compute_fee was already called with the same fees for
1467 // larger amount and there was no overflow.
1472 value_msat + extra_contribution_msat
1477 /// Calculate the fees required to route the given amount over a channel with the given fees.
1478 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1479 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1480 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1484 /// Calculate the fees required to route the given amount over a channel with the given fees,
1485 /// saturating to [`u64::max_value`].
1486 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1487 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1488 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1489 .saturating_add(channel_fees.base_msat as u64)
1492 /// The default `features` we assume for a node in a route, when no `features` are known about that
1495 /// Default features are:
1496 /// * variable_length_onion_optional
1497 fn default_node_features() -> NodeFeatures {
1498 let mut features = NodeFeatures::empty();
1499 features.set_variable_length_onion_optional();
1503 struct LoggedPayeePubkey(Option<PublicKey>);
1504 impl fmt::Display for LoggedPayeePubkey {
1505 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1508 "payee node id ".fmt(f)?;
1512 "blinded payee".fmt(f)
1518 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1519 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1520 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1522 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1523 "blinded route hint with introduction node id ".fmt(f)?;
1524 hint.1.introduction_node_id.fmt(f)?;
1525 " and blinding point ".fmt(f)?;
1526 hint.1.blinding_point.fmt(f)
1528 CandidateRouteHop::FirstHop { .. } => {
1529 "first hop with SCID ".fmt(f)?;
1530 self.0.short_channel_id().unwrap().fmt(f)
1532 CandidateRouteHop::PrivateHop { .. } => {
1533 "route hint with SCID ".fmt(f)?;
1534 self.0.short_channel_id().unwrap().fmt(f)
1538 self.0.short_channel_id().unwrap().fmt(f)
1545 fn sort_first_hop_channels(
1546 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1547 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1549 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1550 // most like to use.
1552 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1553 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1556 // Second, because simply always sorting in descending order would always use our largest
1557 // available outbound capacity, needlessly fragmenting our available channel capacities,
1558 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1559 // which have enough, but not too much, capacity for the payment.
1561 // Available outbound balances factor in liquidity already reserved for previously found paths.
1562 channels.sort_unstable_by(|chan_a, chan_b| {
1563 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1564 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1565 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1566 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1567 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1568 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1569 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1570 // Sort in descending order
1571 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1573 // Sort in ascending order
1574 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1579 /// Finds a route from us (payer) to the given target node (payee).
1581 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1582 /// in the given [`RouteParameters::payment_params`].
1583 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1585 /// Private routing paths between a public node and the target may be included in the `payee` field
1586 /// of [`RouteParameters::payment_params`].
1588 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1589 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1590 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1592 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1593 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1594 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1598 /// Panics if first_hops contains channels without `short_channel_id`s;
1599 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1601 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1602 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1603 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1604 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1605 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1606 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1607 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1608 ) -> Result<Route, LightningError>
1609 where L::Target: Logger, GL::Target: Logger {
1610 let graph_lock = network_graph.read_only();
1611 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1612 scorer, score_params, random_seed_bytes)?;
1613 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1617 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1618 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1619 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1620 _random_seed_bytes: &[u8; 32]
1621 ) -> Result<Route, LightningError>
1622 where L::Target: Logger {
1624 let payment_params = &route_params.payment_params;
1625 let final_value_msat = route_params.final_value_msat;
1626 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1627 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1628 // so use a dummy id for this in the blinded case.
1629 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1630 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1631 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1632 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1633 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1635 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1636 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1638 if our_node_id == maybe_dummy_payee_node_id {
1639 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1642 if final_value_msat > MAX_VALUE_MSAT {
1643 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1646 if final_value_msat == 0 {
1647 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1650 match &payment_params.payee {
1651 Payee::Clear { route_hints, node_id, .. } => {
1652 for route in route_hints.iter() {
1653 for hop in &route.0 {
1654 if hop.src_node_id == *node_id {
1655 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1660 Payee::Blinded { route_hints, .. } => {
1661 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1662 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});
1664 for (_, blinded_path) in route_hints.iter() {
1665 if blinded_path.blinded_hops.len() == 0 {
1666 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1667 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1668 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1669 } else if blinded_path.blinded_hops.len() == 1 &&
1670 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1671 && p.introduction_node_id != blinded_path.introduction_node_id)
1673 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1678 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1679 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1680 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});
1683 // The general routing idea is the following:
1684 // 1. Fill first/last hops communicated by the caller.
1685 // 2. Attempt to construct a path from payer to payee for transferring
1686 // any ~sufficient (described later) value.
1687 // If succeed, remember which channels were used and how much liquidity they have available,
1688 // so that future paths don't rely on the same liquidity.
1689 // 3. Proceed to the next step if:
1690 // - we hit the recommended target value;
1691 // - OR if we could not construct a new path. Any next attempt will fail too.
1692 // Otherwise, repeat step 2.
1693 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1694 // (not recommended value).
1695 // 5. If yes, proceed. If not, fail routing.
1696 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1697 // transferred up to the transfer target value.
1698 // 7. Reduce the value of the last path until we are sending only the target value.
1699 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1700 // them so that we're not sending two HTLCs along the same path.
1702 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1703 // distance from the payee
1705 // We are not a faithful Dijkstra's implementation because we can change values which impact
1706 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1707 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1708 // the value we are currently attempting to send over a path, we simply reduce the value being
1709 // sent along the path for any hops after that channel. This may imply that later fees (which
1710 // we've already tabulated) are lower because a smaller value is passing through the channels
1711 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1712 // channels which were selected earlier (and which may still be used for other paths without a
1713 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1716 // One potentially problematic case for this algorithm would be if there are many
1717 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1718 // graph walking), we may never find a path which is not liquidity-limited and has lower
1719 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1720 // Because we only consider paths with at least 5% of the total value being sent, the damage
1721 // from such a case should be limited, however this could be further reduced in the future by
1722 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1723 // limits for the purposes of fee calculation.
1725 // Alternatively, we could store more detailed path information in the heap (targets, below)
1726 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1727 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1728 // and practically (as we would need to store dynamically-allocated path information in heap
1729 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1730 // results of such an algorithm would likely be biased towards lower-value paths.
1732 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1733 // outside of our current search value, running a path search more times to gather candidate
1734 // paths at different values. While this may be acceptable, further path searches may increase
1735 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1736 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1737 // the same time, remaining generic across different payment values.
1739 let network_channels = network_graph.channels();
1740 let network_nodes = network_graph.nodes();
1742 if payment_params.max_path_count == 0 {
1743 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1746 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1747 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1749 let allow_mpp = if payment_params.max_path_count == 1 {
1751 } else if payment_params.payee.supports_basic_mpp() {
1753 } else if let Some(payee) = payee_node_id_opt {
1754 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1755 |info| info.features.supports_basic_mpp()))
1758 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1760 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1761 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1762 if allow_mpp { "with" } else { "without" },
1763 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1764 max_total_routing_fee_msat);
1767 // Prepare the data we'll use for payee-to-payer search by
1768 // inserting first hops suggested by the caller as targets.
1769 // Our search will then attempt to reach them while traversing from the payee node.
1770 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1771 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1772 if let Some(hops) = first_hops {
1774 if chan.get_outbound_payment_scid().is_none() {
1775 panic!("first_hops should be filled in with usable channels, not pending ones");
1777 if chan.counterparty.node_id == *our_node_pubkey {
1778 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1781 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1782 .or_insert(Vec::new())
1785 if first_hop_targets.is_empty() {
1786 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1790 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1791 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1792 // adding duplicate entries when we find a better path to a given node.
1793 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1795 // Map from node_id to information about the best current path to that node, including feerate
1797 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1799 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1800 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1801 // htlc_minimum with extra fees while still finding a cheaper path.
1802 let mut hit_minimum_limit;
1804 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1805 // We start with a path_value of the exact amount we want, and if that generates a route we may
1806 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1807 // amount we want in total across paths, selecting the best subset at the end.
1808 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1809 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1810 let mut path_value_msat = final_value_msat;
1812 // Routing Fragmentation Mitigation heuristic:
1814 // Routing fragmentation across many payment paths increases the overall routing
1815 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1816 // Taking too many smaller paths also increases the chance of payment failure.
1817 // Thus to avoid this effect, we require from our collected links to provide
1818 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1819 // This requirement is currently set to be 1/max_path_count of the payment
1820 // value to ensure we only ever return routes that do not violate this limit.
1821 let minimal_value_contribution_msat: u64 = if allow_mpp {
1822 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1827 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1828 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1829 // drop the requirement by setting this to 0.
1830 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1832 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1833 // determine if the channel can be used by additional MPP paths or to inform path finding
1834 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1835 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1837 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1838 HashMap::with_capacity(network_nodes.len());
1840 // Keeping track of how much value we already collected across other paths. Helps to decide
1841 // when we want to stop looking for new paths.
1842 let mut already_collected_value_msat = 0;
1844 for (_, channels) in first_hop_targets.iter_mut() {
1845 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1849 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1850 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1852 // Remember how many candidates we ignored to allow for some logging afterwards.
1853 let mut num_ignored_value_contribution: u32 = 0;
1854 let mut num_ignored_path_length_limit: u32 = 0;
1855 let mut num_ignored_cltv_delta_limit: u32 = 0;
1856 let mut num_ignored_previously_failed: u32 = 0;
1857 let mut num_ignored_total_fee_limit: u32 = 0;
1858 let mut num_ignored_avoid_overpayment: u32 = 0;
1859 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
1861 macro_rules! add_entry {
1862 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
1863 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1864 // since that value has to be transferred over this channel.
1865 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
1866 ( $candidate: expr, $next_hops_fee_msat: expr,
1867 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1868 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1869 // We "return" whether we updated the path at the end, and how much we can route via
1870 // this channel, via this:
1871 let mut hop_contribution_amt_msat = None;
1872 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1873 // practice these cases should be caught earlier:
1874 // - for regular channels at channel announcement (TODO)
1875 // - for first and last hops early in get_route
1876 let src_node_id = $candidate.source();
1877 if Some(src_node_id) != $candidate.target() {
1878 let scid_opt = $candidate.short_channel_id();
1879 let effective_capacity = $candidate.effective_capacity();
1880 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1882 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1883 // It may be misleading because we might later choose to reduce the value transferred
1884 // over these channels, and the channel which was insufficient might become sufficient.
1885 // Worst case: we drop a good channel here because it can't cover the high following
1886 // fees caused by one expensive channel, but then this channel could have been used
1887 // if the amount being transferred over this path is lower.
1888 // We do this for now, but this is a subject for removal.
1889 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1890 let used_liquidity_msat = used_liquidities
1891 .get(&$candidate.id())
1892 .map_or(0, |used_liquidity_msat| {
1893 available_value_contribution_msat = available_value_contribution_msat
1894 .saturating_sub(*used_liquidity_msat);
1895 *used_liquidity_msat
1898 // Verify the liquidity offered by this channel complies to the minimal contribution.
1899 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1900 // Do not consider candidate hops that would exceed the maximum path length.
1901 let path_length_to_node = $next_hops_path_length + 1;
1902 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1904 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1905 // In order to already account for some of the privacy enhancing random CLTV
1906 // expiry delta offset we add on top later, we subtract a rough estimate
1907 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1908 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1909 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1910 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1911 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1912 .saturating_add($candidate.cltv_expiry_delta());
1913 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1915 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1916 // Includes paying fees for the use of the following channels.
1917 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1918 Some(result) => result,
1919 // Can't overflow due to how the values were computed right above.
1920 None => unreachable!(),
1922 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1923 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1924 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1926 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1927 let may_overpay_to_meet_path_minimum_msat =
1928 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1929 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
1930 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1931 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
1933 let payment_failed_on_this_channel = scid_opt.map_or(false,
1934 |scid| payment_params.previously_failed_channels.contains(&scid));
1936 let (should_log_candidate, first_hop_details) = match $candidate {
1937 CandidateRouteHop::FirstHop { details, .. } => (true, Some(details)),
1938 CandidateRouteHop::PrivateHop { .. } => (true, None),
1939 CandidateRouteHop::Blinded { .. } => (true, None),
1940 CandidateRouteHop::OneHopBlinded { .. } => (true, None),
1944 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1945 // bother considering this channel. If retrying with recommended_value_msat may
1946 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1947 // around again with a higher amount.
1948 if !contributes_sufficient_value {
1949 if should_log_candidate {
1950 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1952 if let Some(details) = first_hop_details {
1954 "First hop candidate next_outbound_htlc_limit_msat: {}",
1955 details.next_outbound_htlc_limit_msat,
1959 num_ignored_value_contribution += 1;
1960 } else if exceeds_max_path_length {
1961 if should_log_candidate {
1962 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1964 num_ignored_path_length_limit += 1;
1965 } else if exceeds_cltv_delta_limit {
1966 if should_log_candidate {
1967 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1969 if let Some(_) = first_hop_details {
1971 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
1972 hop_total_cltv_delta,
1973 max_total_cltv_expiry_delta,
1977 num_ignored_cltv_delta_limit += 1;
1978 } else if payment_failed_on_this_channel {
1979 if should_log_candidate {
1980 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1982 num_ignored_previously_failed += 1;
1983 } else if may_overpay_to_meet_path_minimum_msat {
1984 if should_log_candidate {
1986 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
1987 LoggedCandidateHop(&$candidate));
1989 if let Some(details) = first_hop_details {
1991 "First hop candidate next_outbound_htlc_minimum_msat: {}",
1992 details.next_outbound_htlc_minimum_msat,
1996 num_ignored_avoid_overpayment += 1;
1997 hit_minimum_limit = true;
1998 } else if over_path_minimum_msat {
1999 // Note that low contribution here (limited by available_liquidity_msat)
2000 // might violate htlc_minimum_msat on the hops which are next along the
2001 // payment path (upstream to the payee). To avoid that, we recompute
2002 // path fees knowing the final path contribution after constructing it.
2003 let curr_min = cmp::max(
2004 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2006 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2007 .saturating_add(curr_min);
2008 let hm_entry = dist.entry(src_node_id);
2009 let old_entry = hm_entry.or_insert_with(|| {
2010 // If there was previously no known way to access the source node
2011 // (recall it goes payee-to-payer) of short_channel_id, first add a
2012 // semi-dummy record just to compute the fees to reach the source node.
2013 // This will affect our decision on selecting short_channel_id
2014 // as a way to reach the $candidate.target() node.
2016 candidate: $candidate.clone(),
2018 next_hops_fee_msat: u64::max_value(),
2019 hop_use_fee_msat: u64::max_value(),
2020 total_fee_msat: u64::max_value(),
2021 path_htlc_minimum_msat,
2022 path_penalty_msat: u64::max_value(),
2023 was_processed: false,
2024 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2025 value_contribution_msat,
2029 #[allow(unused_mut)] // We only use the mut in cfg(test)
2030 let mut should_process = !old_entry.was_processed;
2031 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2033 // In test/fuzzing builds, we do extra checks to make sure the skipping
2034 // of already-seen nodes only happens in cases we expect (see below).
2035 if !should_process { should_process = true; }
2039 let mut hop_use_fee_msat = 0;
2040 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2042 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2043 // will have the same effective-fee
2044 if src_node_id != our_node_id {
2045 // Note that `u64::max_value` means we'll always fail the
2046 // `old_entry.total_fee_msat > total_fee_msat` check below
2047 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2048 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2051 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2052 if total_fee_msat > max_total_routing_fee_msat {
2053 if should_log_candidate {
2054 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2056 if let Some(_) = first_hop_details {
2058 "First hop candidate routing fee: {}. Limit: {}",
2060 max_total_routing_fee_msat,
2064 num_ignored_total_fee_limit += 1;
2066 let channel_usage = ChannelUsage {
2067 amount_msat: amount_to_transfer_over_msat,
2068 inflight_htlc_msat: used_liquidity_msat,
2071 let channel_penalty_msat =
2072 scorer.channel_penalty_msat($candidate,
2075 let path_penalty_msat = $next_hops_path_penalty_msat
2076 .saturating_add(channel_penalty_msat);
2077 let new_graph_node = RouteGraphNode {
2078 node_id: src_node_id,
2079 lowest_fee_to_node: total_fee_msat,
2080 total_cltv_delta: hop_total_cltv_delta,
2081 value_contribution_msat,
2082 path_htlc_minimum_msat,
2084 path_length_to_node,
2087 // Update the way of reaching $candidate.source()
2088 // with the given short_channel_id (from $candidate.target()),
2089 // if this way is cheaper than the already known
2090 // (considering the cost to "reach" this channel from the route destination,
2091 // the cost of using this channel,
2092 // and the cost of routing to the source node of this channel).
2093 // Also, consider that htlc_minimum_msat_difference, because we might end up
2094 // paying it. Consider the following exploit:
2095 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2096 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2097 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2098 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2100 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2101 // but it may require additional tracking - we don't want to double-count
2102 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2103 // can't use something that may decrease on future hops.
2104 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2105 .saturating_add(old_entry.path_penalty_msat);
2106 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2107 .saturating_add(path_penalty_msat);
2109 if !old_entry.was_processed && new_cost < old_cost {
2110 targets.push(new_graph_node);
2111 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2112 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2113 old_entry.total_fee_msat = total_fee_msat;
2114 old_entry.candidate = $candidate.clone();
2115 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2116 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2117 old_entry.path_penalty_msat = path_penalty_msat;
2118 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2120 old_entry.value_contribution_msat = value_contribution_msat;
2122 hop_contribution_amt_msat = Some(value_contribution_msat);
2123 } else if old_entry.was_processed && new_cost < old_cost {
2124 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2126 // If we're skipping processing a node which was previously
2127 // processed even though we found another path to it with a
2128 // cheaper fee, check that it was because the second path we
2129 // found (which we are processing now) has a lower value
2130 // contribution due to an HTLC minimum limit.
2132 // e.g. take a graph with two paths from node 1 to node 2, one
2133 // through channel A, and one through channel B. Channel A and
2134 // B are both in the to-process heap, with their scores set by
2135 // a higher htlc_minimum than fee.
2136 // Channel A is processed first, and the channels onwards from
2137 // node 1 are added to the to-process heap. Thereafter, we pop
2138 // Channel B off of the heap, note that it has a much more
2139 // restrictive htlc_maximum_msat, and recalculate the fees for
2140 // all of node 1's channels using the new, reduced, amount.
2142 // This would be bogus - we'd be selecting a higher-fee path
2143 // with a lower htlc_maximum_msat instead of the one we'd
2144 // already decided to use.
2145 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2147 value_contribution_msat + path_penalty_msat <
2148 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2155 if should_log_candidate {
2157 "Ignoring {} due to its htlc_minimum_msat limit.",
2158 LoggedCandidateHop(&$candidate));
2160 if let Some(details) = first_hop_details {
2162 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2163 details.next_outbound_htlc_minimum_msat,
2167 num_ignored_htlc_minimum_msat_limit += 1;
2171 hop_contribution_amt_msat
2175 let default_node_features = default_node_features();
2177 // Find ways (channels with destination) to reach a given node and store them
2178 // in the corresponding data structures (routing graph etc).
2179 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2180 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2181 // This data can later be helpful to optimize routing (pay lower fees).
2182 macro_rules! add_entries_to_cheapest_to_target_node {
2183 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
2184 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
2185 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2186 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2187 let was_processed = elem.was_processed;
2188 elem.was_processed = true;
2191 // Entries are added to dist in add_entry!() when there is a channel from a node.
2192 // Because there are no channels from payee, it will not have a dist entry at this point.
2193 // If we're processing any other node, it is always be the result of a channel from it.
2194 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2199 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2200 for details in first_channels {
2201 let candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id };
2202 add_entry!(&candidate, $fee_to_target_msat,
2203 $next_hops_value_contribution,
2204 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
2205 $next_hops_cltv_delta, $next_hops_path_length);
2209 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2212 &default_node_features
2215 if !features.requires_unknown_bits() {
2216 for chan_id in $node.channels.iter() {
2217 let chan = network_channels.get(chan_id).unwrap();
2218 if !chan.features.requires_unknown_bits() {
2219 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2220 if first_hops.is_none() || *source != our_node_id {
2221 if directed_channel.direction().enabled {
2222 let candidate = CandidateRouteHop::PublicHop {
2223 info: directed_channel,
2224 short_channel_id: *chan_id,
2226 add_entry!(&candidate,
2227 $fee_to_target_msat,
2228 $next_hops_value_contribution,
2229 $next_hops_path_htlc_minimum_msat,
2230 $next_hops_path_penalty_msat,
2231 $next_hops_cltv_delta, $next_hops_path_length);
2242 let mut payment_paths = Vec::<PaymentPath>::new();
2244 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2245 'paths_collection: loop {
2246 // For every new path, start from scratch, except for used_liquidities, which
2247 // helps to avoid reusing previously selected paths in future iterations.
2250 hit_minimum_limit = false;
2252 // If first hop is a private channel and the only way to reach the payee, this is the only
2253 // place where it could be added.
2254 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2255 for details in first_channels {
2256 let candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id };
2257 let added = add_entry!(&candidate, 0, path_value_msat,
2258 0, 0u64, 0, 0).is_some();
2259 log_trace!(logger, "{} direct route to payee via {}",
2260 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2264 // Add the payee as a target, so that the payee-to-payer
2265 // search algorithm knows what to start with.
2266 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2267 // The payee is not in our network graph, so nothing to add here.
2268 // There is still a chance of reaching them via last_hops though,
2269 // so don't yet fail the payment here.
2270 // If not, targets.pop() will not even let us enter the loop in step 2.
2273 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2278 // If a caller provided us with last hops, add them to routing targets. Since this happens
2279 // earlier than general path finding, they will be somewhat prioritized, although currently
2280 // it matters only if the fees are exactly the same.
2281 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2282 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2283 let have_intro_node_in_graph =
2284 // Only add the hops in this route to our candidate set if either
2285 // we have a direct channel to the first hop or the first hop is
2286 // in the regular network graph.
2287 first_hop_targets.get(&intro_node_id).is_some() ||
2288 network_nodes.get(&intro_node_id).is_some();
2289 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2290 let candidate = if hint.1.blinded_hops.len() == 1 {
2291 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2292 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2293 let mut path_contribution_msat = path_value_msat;
2294 if let Some(hop_used_msat) = add_entry!(&candidate,
2295 0, path_contribution_msat, 0, 0_u64, 0, 0)
2297 path_contribution_msat = hop_used_msat;
2299 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2300 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2302 for details in first_channels {
2303 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2304 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2308 let path_min = candidate.htlc_minimum_msat().saturating_add(
2309 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2310 add_entry!(&first_hop_candidate, blinded_path_fee,
2311 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2312 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2316 for route in payment_params.payee.unblinded_route_hints().iter()
2317 .filter(|route| !route.0.is_empty())
2319 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2320 let first_hop_src_is_reachable =
2321 // Only add the hops in this route to our candidate set if either we are part of
2322 // the first hop, we have a direct channel to the first hop, or the first hop is in
2323 // the regular network graph.
2324 our_node_id == first_hop_src_id ||
2325 first_hop_targets.get(&first_hop_src_id).is_some() ||
2326 network_nodes.get(&first_hop_src_id).is_some();
2327 if first_hop_src_is_reachable {
2328 // We start building the path from reverse, i.e., from payee
2329 // to the first RouteHintHop in the path.
2330 let hop_iter = route.0.iter().rev();
2331 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2332 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2333 let mut hop_used = true;
2334 let mut aggregate_next_hops_fee_msat: u64 = 0;
2335 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2336 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2337 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2338 let mut aggregate_next_hops_path_length: u8 = 0;
2339 let mut aggregate_path_contribution_msat = path_value_msat;
2341 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2342 let source = NodeId::from_pubkey(&hop.src_node_id);
2343 let target = NodeId::from_pubkey(&prev_hop_id);
2345 if let Some(first_channels) = first_hop_targets.get(&target) {
2346 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2347 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2348 hop.short_channel_id);
2353 let candidate = network_channels
2354 .get(&hop.short_channel_id)
2355 .and_then(|channel| channel.as_directed_to(&target))
2356 .map(|(info, _)| CandidateRouteHop::PublicHop {
2358 short_channel_id: hop.short_channel_id,
2360 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop, target_node_id: target });
2362 if let Some(hop_used_msat) = add_entry!(&candidate,
2363 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2364 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2365 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2367 aggregate_path_contribution_msat = hop_used_msat;
2369 // If this hop was not used then there is no use checking the preceding
2370 // hops in the RouteHint. We can break by just searching for a direct
2371 // channel between last checked hop and first_hop_targets.
2375 let used_liquidity_msat = used_liquidities
2376 .get(&candidate.id()).copied()
2378 let channel_usage = ChannelUsage {
2379 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2380 inflight_htlc_msat: used_liquidity_msat,
2381 effective_capacity: candidate.effective_capacity(),
2383 let channel_penalty_msat = scorer.channel_penalty_msat(
2384 &candidate, channel_usage, score_params
2386 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2387 .saturating_add(channel_penalty_msat);
2389 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2390 .saturating_add(hop.cltv_expiry_delta as u32);
2392 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2395 // Searching for a direct channel between last checked hop and first_hop_targets
2396 if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2397 sort_first_hop_channels(first_channels, &used_liquidities,
2398 recommended_value_msat, our_node_pubkey);
2399 for details in first_channels {
2400 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2401 add_entry!(&first_hop_candidate,
2402 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2403 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2404 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2412 // In the next values of the iterator, the aggregate fees already reflects
2413 // the sum of value sent from payer (final_value_msat) and routing fees
2414 // for the last node in the RouteHint. We need to just add the fees to
2415 // route through the current node so that the preceding node (next iteration)
2417 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2418 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2419 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2421 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2422 // this route hint's source node to forward said min over this channel.
2423 aggregate_next_hops_path_htlc_minimum_msat = {
2424 let curr_htlc_min = cmp::max(
2425 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2427 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2428 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2431 if idx == route.0.len() - 1 {
2432 // The last hop in this iterator is the first hop in
2433 // overall RouteHint.
2434 // If this hop connects to a node with which we have a direct channel,
2435 // ignore the network graph and, if the last hop was added, add our
2436 // direct channel to the candidate set.
2438 // Note that we *must* check if the last hop was added as `add_entry`
2439 // always assumes that the third argument is a node to which we have a
2441 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2442 sort_first_hop_channels(first_channels, &used_liquidities,
2443 recommended_value_msat, our_node_pubkey);
2444 for details in first_channels {
2445 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2446 add_entry!(&first_hop_candidate,
2447 aggregate_next_hops_fee_msat,
2448 aggregate_path_contribution_msat,
2449 aggregate_next_hops_path_htlc_minimum_msat,
2450 aggregate_next_hops_path_penalty_msat,
2451 aggregate_next_hops_cltv_delta,
2452 aggregate_next_hops_path_length);
2460 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2462 // At this point, targets are filled with the data from first and
2463 // last hops communicated by the caller, and the payment receiver.
2464 let mut found_new_path = false;
2467 // If this loop terminates due the exhaustion of targets, two situations are possible:
2468 // - not enough outgoing liquidity:
2469 // 0 < already_collected_value_msat < final_value_msat
2470 // - enough outgoing liquidity:
2471 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2472 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2473 // paths_collection will be stopped because found_new_path==false.
2474 // This is not necessarily a routing failure.
2475 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, mut value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, path_length_to_node, .. }) = targets.pop() {
2477 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2478 // traversing the graph and arrange the path out of what we found.
2479 if node_id == our_node_id {
2480 let mut new_entry = dist.remove(&our_node_id).unwrap();
2481 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2484 let mut features_set = false;
2485 let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2486 if let Some(first_channels) = first_hop_targets.get(&target) {
2487 for details in first_channels {
2488 if let CandidateRouteHop::FirstHop { details: last_hop_details, .. }
2489 = ordered_hops.last().unwrap().0.candidate
2491 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2492 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2493 features_set = true;
2500 if let Some(node) = network_nodes.get(&target) {
2501 if let Some(node_info) = node.announcement_info.as_ref() {
2502 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2504 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2507 // We can fill in features for everything except hops which were
2508 // provided via the invoice we're paying. We could guess based on the
2509 // recipient's features but for now we simply avoid guessing at all.
2513 // Means we succesfully traversed from the payer to the payee, now
2514 // save this path for the payment route. Also, update the liquidity
2515 // remaining on the used hops, so that we take them into account
2516 // while looking for more paths.
2517 if target == maybe_dummy_payee_node_id {
2521 new_entry = match dist.remove(&target) {
2522 Some(payment_hop) => payment_hop,
2523 // We can't arrive at None because, if we ever add an entry to targets,
2524 // we also fill in the entry in dist (see add_entry!).
2525 None => unreachable!(),
2527 // We "propagate" the fees one hop backward (topologically) here,
2528 // so that fees paid for a HTLC forwarding on the current channel are
2529 // associated with the previous channel (where they will be subtracted).
2530 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2531 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2533 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2534 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2536 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2537 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2539 let mut payment_path = PaymentPath {hops: ordered_hops};
2541 // We could have possibly constructed a slightly inconsistent path: since we reduce
2542 // value being transferred along the way, we could have violated htlc_minimum_msat
2543 // on some channels we already passed (assuming dest->source direction). Here, we
2544 // recompute the fees again, so that if that's the case, we match the currently
2545 // underpaid htlc_minimum_msat with fees.
2546 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2547 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2548 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2550 // Since a path allows to transfer as much value as
2551 // the smallest channel it has ("bottleneck"), we should recompute
2552 // the fees so sender HTLC don't overpay fees when traversing
2553 // larger channels than the bottleneck. This may happen because
2554 // when we were selecting those channels we were not aware how much value
2555 // this path will transfer, and the relative fee for them
2556 // might have been computed considering a larger value.
2557 // Remember that we used these channels so that we don't rely
2558 // on the same liquidity in future paths.
2559 let mut prevented_redundant_path_selection = false;
2560 for (hop, _) in payment_path.hops.iter() {
2561 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2562 let used_liquidity_msat = used_liquidities
2563 .entry(hop.candidate.id())
2564 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2565 .or_insert(spent_on_hop_msat);
2566 let hop_capacity = hop.candidate.effective_capacity();
2567 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2568 if *used_liquidity_msat == hop_max_msat {
2569 // If this path used all of this channel's available liquidity, we know
2570 // this path will not be selected again in the next loop iteration.
2571 prevented_redundant_path_selection = true;
2573 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2575 if !prevented_redundant_path_selection {
2576 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2577 // we'll probably end up picking the same path again on the next iteration.
2578 // Decrease the available liquidity of a hop in the middle of the path.
2579 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2580 let exhausted = u64::max_value();
2582 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2583 LoggedCandidateHop(victim_candidate));
2584 if let Some(scid) = victim_candidate.short_channel_id() {
2585 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2586 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2590 // Track the total amount all our collected paths allow to send so that we know
2591 // when to stop looking for more paths
2592 already_collected_value_msat += value_contribution_msat;
2594 payment_paths.push(payment_path);
2595 found_new_path = true;
2596 break 'path_construction;
2599 // If we found a path back to the payee, we shouldn't try to process it again. This is
2600 // the equivalent of the `elem.was_processed` check in
2601 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2602 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2604 // Otherwise, since the current target node is not us,
2605 // keep "unrolling" the payment graph from payee to payer by
2606 // finding a way to reach the current target from the payer side.
2607 match network_nodes.get(&node_id) {
2610 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2611 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2612 total_cltv_delta, path_length_to_node);
2618 if !found_new_path && channel_saturation_pow_half != 0 {
2619 channel_saturation_pow_half = 0;
2620 continue 'paths_collection;
2622 // If we don't support MPP, no use trying to gather more value ever.
2623 break 'paths_collection;
2627 // Stop either when the recommended value is reached or if no new path was found in this
2629 // In the latter case, making another path finding attempt won't help,
2630 // because we deterministically terminated the search due to low liquidity.
2631 if !found_new_path && channel_saturation_pow_half != 0 {
2632 channel_saturation_pow_half = 0;
2633 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2634 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2635 path_value_msat = recommended_value_msat;
2636 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2637 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2638 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2639 break 'paths_collection;
2640 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2641 // Further, if this was our first walk of the graph, and we weren't limited by an
2642 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2643 // limited by an htlc_minimum_msat value, find another path with a higher value,
2644 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2645 // still keeping a lower total fee than this path.
2646 if !hit_minimum_limit {
2647 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2648 break 'paths_collection;
2650 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.");
2651 path_value_msat = recommended_value_msat;
2655 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2656 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2657 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2658 num_ignored_total_fee_limit;
2659 if num_ignored_total > 0 {
2661 "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.",
2662 num_ignored_value_contribution, num_ignored_path_length_limit,
2663 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2664 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2665 num_ignored_total_fee_limit, num_ignored_total);
2669 if payment_paths.len() == 0 {
2670 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2673 if already_collected_value_msat < final_value_msat {
2674 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2678 let mut selected_route = payment_paths;
2680 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2681 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2683 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2684 // the value they contribute towards the payment amount.
2685 // We sort in descending order as we will remove from the front in `retain`, next.
2686 selected_route.sort_unstable_by(|a, b|
2687 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2688 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2691 // We should make sure that at least 1 path left.
2692 let mut paths_left = selected_route.len();
2693 selected_route.retain(|path| {
2694 if paths_left == 1 {
2697 let path_value_msat = path.get_value_msat();
2698 if path_value_msat <= overpaid_value_msat {
2699 overpaid_value_msat -= path_value_msat;
2705 debug_assert!(selected_route.len() > 0);
2707 if overpaid_value_msat != 0 {
2709 // Now, subtract the remaining overpaid value from the most-expensive path.
2710 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2711 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2712 selected_route.sort_unstable_by(|a, b| {
2713 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2714 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2715 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2717 let expensive_payment_path = selected_route.first_mut().unwrap();
2719 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2720 // can't go negative.
2721 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2722 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2726 // Sort by the path itself and combine redundant paths.
2727 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2728 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2730 selected_route.sort_unstable_by_key(|path| {
2731 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2732 debug_assert!(path.hops.len() <= key.len());
2733 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2738 for idx in 0..(selected_route.len() - 1) {
2739 if idx + 1 >= selected_route.len() { break; }
2740 if iter_equal(selected_route[idx].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2741 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2742 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2743 selected_route[idx].update_value_and_recompute_fees(new_value);
2744 selected_route.remove(idx + 1);
2748 let mut paths = Vec::new();
2749 for payment_path in selected_route {
2750 let mut hops = Vec::with_capacity(payment_path.hops.len());
2751 for (hop, node_features) in payment_path.hops.iter()
2752 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2754 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2755 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2756 // If we sourced the hop from the graph we're sure the target node is announced.
2758 } else if let CandidateRouteHop::FirstHop { details, .. } = hop.candidate {
2759 // If this is a first hop we also know if it's announced.
2762 // If we sourced it any other way, we double-check the network graph to see if
2763 // there are announced channels between the endpoints. If so, the hop might be
2764 // referring to any of the announced channels, as its `short_channel_id` might be
2765 // an alias, in which case we don't take any chances here.
2766 network_graph.node(&target).map_or(false, |hop_node|
2767 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2768 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
2772 hops.push(RouteHop {
2773 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2774 node_features: node_features.clone(),
2775 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2776 channel_features: hop.candidate.features(),
2777 fee_msat: hop.fee_msat,
2778 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2779 maybe_announced_channel,
2782 let mut final_cltv_delta = final_cltv_expiry_delta;
2783 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2784 if let Some(blinded_path) = h.candidate.blinded_path() {
2785 final_cltv_delta = h.candidate.cltv_expiry_delta();
2787 hops: blinded_path.blinded_hops.clone(),
2788 blinding_point: blinded_path.blinding_point,
2789 excess_final_cltv_expiry_delta: 0,
2790 final_value_msat: h.fee_msat,
2794 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2795 // applicable for the previous hop.
2796 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2797 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2800 paths.push(Path { hops, blinded_tail });
2802 // Make sure we would never create a route with more paths than we allow.
2803 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2805 if let Some(node_features) = payment_params.payee.node_features() {
2806 for path in paths.iter_mut() {
2807 path.hops.last_mut().unwrap().node_features = node_features.clone();
2811 let route = Route { paths, route_params: Some(route_params.clone()) };
2813 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2814 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2815 if route.get_total_fees() > max_total_routing_fee_msat {
2816 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2817 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2821 log_info!(logger, "Got route: {}", log_route!(route));
2825 // When an adversarial intermediary node observes a payment, it may be able to infer its
2826 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2827 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2828 // payment path by adding a randomized 'shadow route' offset to the final hop.
2829 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2830 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2832 let network_channels = network_graph.channels();
2833 let network_nodes = network_graph.nodes();
2835 for path in route.paths.iter_mut() {
2836 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2838 // Remember the last three nodes of the random walk and avoid looping back on them.
2839 // Init with the last three nodes from the actual path, if possible.
2840 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2841 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2842 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2844 // Choose the last publicly known node as the starting point for the random walk.
2845 let mut cur_hop: Option<NodeId> = None;
2846 let mut path_nonce = [0u8; 12];
2847 if let Some(starting_hop) = path.hops.iter().rev()
2848 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2849 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2850 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2853 // Init PRNG with the path-dependant nonce, which is static for private paths.
2854 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2855 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2857 // Pick a random path length in [1 .. 3]
2858 prng.process_in_place(&mut random_path_bytes);
2859 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2861 for random_hop in 0..random_walk_length {
2862 // If we don't find a suitable offset in the public network graph, we default to
2863 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2864 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2866 if let Some(cur_node_id) = cur_hop {
2867 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2868 // Randomly choose the next unvisited hop.
2869 prng.process_in_place(&mut random_path_bytes);
2870 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2871 .checked_rem(cur_node.channels.len())
2872 .and_then(|index| cur_node.channels.get(index))
2873 .and_then(|id| network_channels.get(id)) {
2874 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2875 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2876 nodes_to_avoid[random_hop] = *next_id;
2877 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2878 cur_hop = Some(*next_id);
2885 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2886 .checked_add(random_hop_offset)
2887 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2890 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2891 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2892 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2894 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2895 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2896 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2897 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2898 max_path_offset = cmp::max(
2899 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2900 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2901 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2903 // Add 'shadow' CLTV offset to the final hop
2904 if let Some(tail) = path.blinded_tail.as_mut() {
2905 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2906 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2908 if let Some(last_hop) = path.hops.last_mut() {
2909 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2910 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2915 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2916 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2918 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2919 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2920 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2921 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2922 ) -> Result<Route, LightningError>
2923 where L::Target: Logger, GL::Target: Logger {
2924 let graph_lock = network_graph.read_only();
2925 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2926 &graph_lock, logger, random_seed_bytes)?;
2927 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2931 fn build_route_from_hops_internal<L: Deref>(
2932 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2933 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2934 ) -> Result<Route, LightningError> where L::Target: Logger {
2937 our_node_id: NodeId,
2938 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2941 impl ScoreLookUp for HopScorer {
2942 type ScoreParams = ();
2943 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
2944 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2946 let mut cur_id = self.our_node_id;
2947 for i in 0..self.hop_ids.len() {
2948 if let Some(next_id) = self.hop_ids[i] {
2949 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
2961 impl<'a> Writeable for HopScorer {
2963 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2968 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2969 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2972 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2973 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2974 for i in 0..hops.len() {
2975 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2978 let scorer = HopScorer { our_node_id, hop_ids };
2980 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2985 use crate::blinded_path::{BlindedHop, BlindedPath};
2986 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2987 use crate::routing::utxo::UtxoResult;
2988 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2989 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2990 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop};
2991 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2992 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2993 use crate::chain::transaction::OutPoint;
2994 use crate::sign::EntropySource;
2995 use crate::ln::ChannelId;
2996 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2997 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2998 use crate::ln::channelmanager;
2999 use crate::offers::invoice::BlindedPayInfo;
3000 use crate::util::config::UserConfig;
3001 use crate::util::test_utils as ln_test_utils;
3002 use crate::util::chacha20::ChaCha20;
3003 use crate::util::ser::{Readable, Writeable};
3005 use crate::util::ser::Writer;
3007 use bitcoin::hashes::Hash;
3008 use bitcoin::network::constants::Network;
3009 use bitcoin::blockdata::constants::ChainHash;
3010 use bitcoin::blockdata::script::Builder;
3011 use bitcoin::blockdata::opcodes;
3012 use bitcoin::blockdata::transaction::TxOut;
3013 use bitcoin::hashes::hex::FromHex;
3014 use bitcoin::secp256k1::{PublicKey,SecretKey};
3015 use bitcoin::secp256k1::Secp256k1;
3017 use crate::io::Cursor;
3018 use crate::prelude::*;
3019 use crate::sync::Arc;
3021 use core::convert::TryInto;
3023 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3024 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3025 channelmanager::ChannelDetails {
3026 channel_id: ChannelId::new_zero(),
3027 counterparty: channelmanager::ChannelCounterparty {
3030 unspendable_punishment_reserve: 0,
3031 forwarding_info: None,
3032 outbound_htlc_minimum_msat: None,
3033 outbound_htlc_maximum_msat: None,
3035 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3038 outbound_scid_alias: None,
3039 inbound_scid_alias: None,
3040 channel_value_satoshis: 0,
3043 outbound_capacity_msat,
3044 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3045 next_outbound_htlc_minimum_msat: 0,
3046 inbound_capacity_msat: 42,
3047 unspendable_punishment_reserve: None,
3048 confirmations_required: None,
3049 confirmations: None,
3050 force_close_spend_delay: None,
3051 is_outbound: true, is_channel_ready: true,
3052 is_usable: true, is_public: true,
3053 inbound_htlc_minimum_msat: None,
3054 inbound_htlc_maximum_msat: None,
3056 feerate_sat_per_1000_weight: None,
3057 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3062 fn simple_route_test() {
3063 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3064 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3065 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3066 let scorer = ln_test_utils::TestScorer::new();
3067 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3068 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3070 // Simple route to 2 via 1
3072 let route_params = RouteParameters::from_payment_params_and_value(
3073 payment_params.clone(), 0);
3074 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3075 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3076 &Default::default(), &random_seed_bytes) {
3077 assert_eq!(err, "Cannot send a payment of 0 msat");
3078 } else { panic!(); }
3080 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3081 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3082 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3083 assert_eq!(route.paths[0].hops.len(), 2);
3085 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3086 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3087 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3088 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3089 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3090 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3092 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3093 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3094 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3095 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3096 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3097 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3101 fn invalid_first_hop_test() {
3102 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3103 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3104 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3105 let scorer = ln_test_utils::TestScorer::new();
3106 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3107 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3109 // Simple route to 2 via 1
3111 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3113 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3114 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3115 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3116 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3117 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3118 } else { panic!(); }
3120 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3121 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3122 assert_eq!(route.paths[0].hops.len(), 2);
3126 fn htlc_minimum_test() {
3127 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3128 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3129 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3130 let scorer = ln_test_utils::TestScorer::new();
3131 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3132 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3134 // Simple route to 2 via 1
3136 // Disable other paths
3137 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3138 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3139 short_channel_id: 12,
3141 flags: 2, // to disable
3142 cltv_expiry_delta: 0,
3143 htlc_minimum_msat: 0,
3144 htlc_maximum_msat: MAX_VALUE_MSAT,
3146 fee_proportional_millionths: 0,
3147 excess_data: Vec::new()
3149 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3150 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3151 short_channel_id: 3,
3153 flags: 2, // to disable
3154 cltv_expiry_delta: 0,
3155 htlc_minimum_msat: 0,
3156 htlc_maximum_msat: MAX_VALUE_MSAT,
3158 fee_proportional_millionths: 0,
3159 excess_data: Vec::new()
3161 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3162 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3163 short_channel_id: 13,
3165 flags: 2, // to disable
3166 cltv_expiry_delta: 0,
3167 htlc_minimum_msat: 0,
3168 htlc_maximum_msat: MAX_VALUE_MSAT,
3170 fee_proportional_millionths: 0,
3171 excess_data: Vec::new()
3173 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3174 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3175 short_channel_id: 6,
3177 flags: 2, // to disable
3178 cltv_expiry_delta: 0,
3179 htlc_minimum_msat: 0,
3180 htlc_maximum_msat: MAX_VALUE_MSAT,
3182 fee_proportional_millionths: 0,
3183 excess_data: Vec::new()
3185 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3186 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3187 short_channel_id: 7,
3189 flags: 2, // to disable
3190 cltv_expiry_delta: 0,
3191 htlc_minimum_msat: 0,
3192 htlc_maximum_msat: MAX_VALUE_MSAT,
3194 fee_proportional_millionths: 0,
3195 excess_data: Vec::new()
3198 // Check against amount_to_transfer_over_msat.
3199 // Set minimal HTLC of 200_000_000 msat.
3200 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3201 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3202 short_channel_id: 2,
3205 cltv_expiry_delta: 0,
3206 htlc_minimum_msat: 200_000_000,
3207 htlc_maximum_msat: MAX_VALUE_MSAT,
3209 fee_proportional_millionths: 0,
3210 excess_data: Vec::new()
3213 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3215 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3216 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3217 short_channel_id: 4,
3220 cltv_expiry_delta: 0,
3221 htlc_minimum_msat: 0,
3222 htlc_maximum_msat: 199_999_999,
3224 fee_proportional_millionths: 0,
3225 excess_data: Vec::new()
3228 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3229 let route_params = RouteParameters::from_payment_params_and_value(
3230 payment_params, 199_999_999);
3231 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3232 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3233 &Default::default(), &random_seed_bytes) {
3234 assert_eq!(err, "Failed to find a path to the given destination");
3235 } else { panic!(); }
3237 // Lift the restriction on the first hop.
3238 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3239 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3240 short_channel_id: 2,
3243 cltv_expiry_delta: 0,
3244 htlc_minimum_msat: 0,
3245 htlc_maximum_msat: MAX_VALUE_MSAT,
3247 fee_proportional_millionths: 0,
3248 excess_data: Vec::new()
3251 // A payment above the minimum should pass
3252 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3253 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3254 assert_eq!(route.paths[0].hops.len(), 2);
3258 fn htlc_minimum_overpay_test() {
3259 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3260 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3261 let config = UserConfig::default();
3262 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3263 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3265 let scorer = ln_test_utils::TestScorer::new();
3266 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3267 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3269 // A route to node#2 via two paths.
3270 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3271 // Thus, they can't send 60 without overpaying.
3272 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3273 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3274 short_channel_id: 2,
3277 cltv_expiry_delta: 0,
3278 htlc_minimum_msat: 35_000,
3279 htlc_maximum_msat: 40_000,
3281 fee_proportional_millionths: 0,
3282 excess_data: Vec::new()
3284 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3285 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3286 short_channel_id: 12,
3289 cltv_expiry_delta: 0,
3290 htlc_minimum_msat: 35_000,
3291 htlc_maximum_msat: 40_000,
3293 fee_proportional_millionths: 0,
3294 excess_data: Vec::new()
3298 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3299 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3300 short_channel_id: 13,
3303 cltv_expiry_delta: 0,
3304 htlc_minimum_msat: 0,
3305 htlc_maximum_msat: MAX_VALUE_MSAT,
3307 fee_proportional_millionths: 0,
3308 excess_data: Vec::new()
3310 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3311 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3312 short_channel_id: 4,
3315 cltv_expiry_delta: 0,
3316 htlc_minimum_msat: 0,
3317 htlc_maximum_msat: MAX_VALUE_MSAT,
3319 fee_proportional_millionths: 0,
3320 excess_data: Vec::new()
3323 // Disable other paths
3324 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3325 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3326 short_channel_id: 1,
3328 flags: 2, // to disable
3329 cltv_expiry_delta: 0,
3330 htlc_minimum_msat: 0,
3331 htlc_maximum_msat: MAX_VALUE_MSAT,
3333 fee_proportional_millionths: 0,
3334 excess_data: Vec::new()
3337 let mut route_params = RouteParameters::from_payment_params_and_value(
3338 payment_params.clone(), 60_000);
3339 route_params.max_total_routing_fee_msat = Some(15_000);
3340 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3341 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3342 // Overpay fees to hit htlc_minimum_msat.
3343 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3344 // TODO: this could be better balanced to overpay 10k and not 15k.
3345 assert_eq!(overpaid_fees, 15_000);
3347 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3348 // while taking even more fee to match htlc_minimum_msat.
3349 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3350 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3351 short_channel_id: 12,
3354 cltv_expiry_delta: 0,
3355 htlc_minimum_msat: 65_000,
3356 htlc_maximum_msat: 80_000,
3358 fee_proportional_millionths: 0,
3359 excess_data: Vec::new()
3361 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3362 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3363 short_channel_id: 2,
3366 cltv_expiry_delta: 0,
3367 htlc_minimum_msat: 0,
3368 htlc_maximum_msat: MAX_VALUE_MSAT,
3370 fee_proportional_millionths: 0,
3371 excess_data: Vec::new()
3373 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3374 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3375 short_channel_id: 4,
3378 cltv_expiry_delta: 0,
3379 htlc_minimum_msat: 0,
3380 htlc_maximum_msat: MAX_VALUE_MSAT,
3382 fee_proportional_millionths: 100_000,
3383 excess_data: Vec::new()
3386 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3387 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3388 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3389 assert_eq!(route.paths.len(), 1);
3390 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3391 let fees = route.paths[0].hops[0].fee_msat;
3392 assert_eq!(fees, 5_000);
3394 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3395 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3396 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3397 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3398 // the other channel.
3399 assert_eq!(route.paths.len(), 1);
3400 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3401 let fees = route.paths[0].hops[0].fee_msat;
3402 assert_eq!(fees, 5_000);
3406 fn htlc_minimum_recipient_overpay_test() {
3407 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3408 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3409 let config = UserConfig::default();
3410 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3411 let scorer = ln_test_utils::TestScorer::new();
3412 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3413 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3415 // Route to node2 over a single path which requires overpaying the recipient themselves.
3417 // First disable all paths except the us -> node1 -> node2 path
3418 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3419 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3420 short_channel_id: 13,
3423 cltv_expiry_delta: 0,
3424 htlc_minimum_msat: 0,
3425 htlc_maximum_msat: 0,
3427 fee_proportional_millionths: 0,
3428 excess_data: Vec::new()
3431 // Set channel 4 to free but with a high htlc_minimum_msat
3432 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3433 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3434 short_channel_id: 4,
3437 cltv_expiry_delta: 0,
3438 htlc_minimum_msat: 15_000,
3439 htlc_maximum_msat: MAX_VALUE_MSAT,
3441 fee_proportional_millionths: 0,
3442 excess_data: Vec::new()
3445 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3446 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3447 // what we try to find a route for, so this test only just happens to work out to exactly
3449 let mut route_params = RouteParameters::from_payment_params_and_value(
3450 payment_params.clone(), 5_000);
3451 route_params.max_total_routing_fee_msat = Some(9_999);
3452 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3453 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3454 &Default::default(), &random_seed_bytes) {
3455 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3456 } else { panic!(); }
3458 let mut route_params = RouteParameters::from_payment_params_and_value(
3459 payment_params.clone(), 5_000);
3460 route_params.max_total_routing_fee_msat = Some(10_000);
3461 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3462 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3463 assert_eq!(route.get_total_fees(), 10_000);
3467 fn disable_channels_test() {
3468 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3469 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3470 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3471 let scorer = ln_test_utils::TestScorer::new();
3472 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3473 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3475 // // Disable channels 4 and 12 by flags=2
3476 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3477 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3478 short_channel_id: 4,
3480 flags: 2, // to disable
3481 cltv_expiry_delta: 0,
3482 htlc_minimum_msat: 0,
3483 htlc_maximum_msat: MAX_VALUE_MSAT,
3485 fee_proportional_millionths: 0,
3486 excess_data: Vec::new()
3488 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3489 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3490 short_channel_id: 12,
3492 flags: 2, // to disable
3493 cltv_expiry_delta: 0,
3494 htlc_minimum_msat: 0,
3495 htlc_maximum_msat: MAX_VALUE_MSAT,
3497 fee_proportional_millionths: 0,
3498 excess_data: Vec::new()
3501 // If all the channels require some features we don't understand, route should fail
3502 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3503 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3504 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3505 &Default::default(), &random_seed_bytes) {
3506 assert_eq!(err, "Failed to find a path to the given destination");
3507 } else { panic!(); }
3509 // If we specify a channel to node7, that overrides our local channel view and that gets used
3510 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3511 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3512 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3513 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3514 &Default::default(), &random_seed_bytes).unwrap();
3515 assert_eq!(route.paths[0].hops.len(), 2);
3517 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3518 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3519 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3520 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3521 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3522 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3524 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3525 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3526 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3527 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3528 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3529 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3533 fn disable_node_test() {
3534 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3535 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3536 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3537 let scorer = ln_test_utils::TestScorer::new();
3538 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3539 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3541 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3542 let mut unknown_features = NodeFeatures::empty();
3543 unknown_features.set_unknown_feature_required();
3544 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3545 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3546 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3548 // If all nodes require some features we don't understand, route should fail
3549 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3550 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3551 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3552 &Default::default(), &random_seed_bytes) {
3553 assert_eq!(err, "Failed to find a path to the given destination");
3554 } else { panic!(); }
3556 // If we specify a channel to node7, that overrides our local channel view and that gets used
3557 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3558 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3559 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3560 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3561 &Default::default(), &random_seed_bytes).unwrap();
3562 assert_eq!(route.paths[0].hops.len(), 2);
3564 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3565 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3566 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3567 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3568 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3569 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3571 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3572 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3573 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3574 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3575 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3576 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3578 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3579 // naively) assume that the user checked the feature bits on the invoice, which override
3580 // the node_announcement.
3584 fn our_chans_test() {
3585 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3586 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3587 let scorer = ln_test_utils::TestScorer::new();
3588 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3589 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3591 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3592 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3593 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3594 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3595 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3596 assert_eq!(route.paths[0].hops.len(), 3);
3598 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3599 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3600 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3601 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3602 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3603 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3605 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3606 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3607 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3608 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3609 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3610 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3612 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3613 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3614 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3615 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3616 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3617 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3619 // If we specify a channel to node7, that overrides our local channel view and that gets used
3620 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3621 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3622 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3623 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3624 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3625 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3626 &Default::default(), &random_seed_bytes).unwrap();
3627 assert_eq!(route.paths[0].hops.len(), 2);
3629 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3630 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3631 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3632 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3633 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3634 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3636 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3637 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3638 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3639 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3640 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3641 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3644 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3645 let zero_fees = RoutingFees {
3647 proportional_millionths: 0,
3649 vec![RouteHint(vec![RouteHintHop {
3650 src_node_id: nodes[3],
3651 short_channel_id: 8,
3653 cltv_expiry_delta: (8 << 4) | 1,
3654 htlc_minimum_msat: None,
3655 htlc_maximum_msat: None,
3657 ]), RouteHint(vec![RouteHintHop {
3658 src_node_id: nodes[4],
3659 short_channel_id: 9,
3662 proportional_millionths: 0,
3664 cltv_expiry_delta: (9 << 4) | 1,
3665 htlc_minimum_msat: None,
3666 htlc_maximum_msat: None,
3667 }]), RouteHint(vec![RouteHintHop {
3668 src_node_id: nodes[5],
3669 short_channel_id: 10,
3671 cltv_expiry_delta: (10 << 4) | 1,
3672 htlc_minimum_msat: None,
3673 htlc_maximum_msat: None,
3677 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3678 let zero_fees = RoutingFees {
3680 proportional_millionths: 0,
3682 vec![RouteHint(vec![RouteHintHop {
3683 src_node_id: nodes[2],
3684 short_channel_id: 5,
3687 proportional_millionths: 0,
3689 cltv_expiry_delta: (5 << 4) | 1,
3690 htlc_minimum_msat: None,
3691 htlc_maximum_msat: None,
3693 src_node_id: nodes[3],
3694 short_channel_id: 8,
3696 cltv_expiry_delta: (8 << 4) | 1,
3697 htlc_minimum_msat: None,
3698 htlc_maximum_msat: None,
3700 ]), RouteHint(vec![RouteHintHop {
3701 src_node_id: nodes[4],
3702 short_channel_id: 9,
3705 proportional_millionths: 0,
3707 cltv_expiry_delta: (9 << 4) | 1,
3708 htlc_minimum_msat: None,
3709 htlc_maximum_msat: None,
3710 }]), RouteHint(vec![RouteHintHop {
3711 src_node_id: nodes[5],
3712 short_channel_id: 10,
3714 cltv_expiry_delta: (10 << 4) | 1,
3715 htlc_minimum_msat: None,
3716 htlc_maximum_msat: None,
3721 fn partial_route_hint_test() {
3722 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3723 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3724 let scorer = ln_test_utils::TestScorer::new();
3725 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3726 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3728 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3729 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3730 // RouteHint may be partially used by the algo to build the best path.
3732 // First check that last hop can't have its source as the payee.
3733 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3734 src_node_id: nodes[6],
3735 short_channel_id: 8,
3738 proportional_millionths: 0,
3740 cltv_expiry_delta: (8 << 4) | 1,
3741 htlc_minimum_msat: None,
3742 htlc_maximum_msat: None,
3745 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3746 invalid_last_hops.push(invalid_last_hop);
3748 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3749 .with_route_hints(invalid_last_hops).unwrap();
3750 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3751 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3752 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3753 &Default::default(), &random_seed_bytes) {
3754 assert_eq!(err, "Route hint cannot have the payee as the source.");
3755 } else { panic!(); }
3758 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3759 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3760 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3761 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3762 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3763 assert_eq!(route.paths[0].hops.len(), 5);
3765 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3766 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3767 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3768 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3769 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3770 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3772 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3773 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3774 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3775 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3776 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3777 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3779 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3780 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3781 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3782 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3783 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3784 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3786 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3787 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3788 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3789 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3790 // If we have a peer in the node map, we'll use their features here since we don't have
3791 // a way of figuring out their features from the invoice:
3792 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3793 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3795 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3796 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3797 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3798 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3799 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3800 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3803 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3804 let zero_fees = RoutingFees {
3806 proportional_millionths: 0,
3808 vec![RouteHint(vec![RouteHintHop {
3809 src_node_id: nodes[3],
3810 short_channel_id: 8,
3812 cltv_expiry_delta: (8 << 4) | 1,
3813 htlc_minimum_msat: None,
3814 htlc_maximum_msat: None,
3815 }]), RouteHint(vec![
3817 ]), RouteHint(vec![RouteHintHop {
3818 src_node_id: nodes[5],
3819 short_channel_id: 10,
3821 cltv_expiry_delta: (10 << 4) | 1,
3822 htlc_minimum_msat: None,
3823 htlc_maximum_msat: None,
3828 fn ignores_empty_last_hops_test() {
3829 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3830 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3831 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3832 let scorer = ln_test_utils::TestScorer::new();
3833 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3834 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3836 // Test handling of an empty RouteHint passed in Invoice.
3837 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3838 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3839 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3840 assert_eq!(route.paths[0].hops.len(), 5);
3842 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3843 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3844 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3845 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3846 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3847 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3849 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3850 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3851 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3852 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3853 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3854 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3856 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3857 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3858 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3859 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3860 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3861 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3863 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3864 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3865 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3866 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3867 // If we have a peer in the node map, we'll use their features here since we don't have
3868 // a way of figuring out their features from the invoice:
3869 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3870 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3872 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3873 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3874 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3875 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3876 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3877 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3880 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3882 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3883 let zero_fees = RoutingFees {
3885 proportional_millionths: 0,
3887 vec![RouteHint(vec![RouteHintHop {
3888 src_node_id: hint_hops[0],
3889 short_channel_id: 0xff00,
3892 proportional_millionths: 0,
3894 cltv_expiry_delta: (5 << 4) | 1,
3895 htlc_minimum_msat: None,
3896 htlc_maximum_msat: None,
3898 src_node_id: hint_hops[1],
3899 short_channel_id: 0xff01,
3901 cltv_expiry_delta: (8 << 4) | 1,
3902 htlc_minimum_msat: None,
3903 htlc_maximum_msat: None,
3908 fn multi_hint_last_hops_test() {
3909 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3910 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3911 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3912 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
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();
3916 // Test through channels 2, 3, 0xff00, 0xff01.
3917 // Test shows that multiple hop hints are considered.
3919 // Disabling channels 6 & 7 by flags=2
3920 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3921 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3922 short_channel_id: 6,
3924 flags: 2, // to disable
3925 cltv_expiry_delta: 0,
3926 htlc_minimum_msat: 0,
3927 htlc_maximum_msat: MAX_VALUE_MSAT,
3929 fee_proportional_millionths: 0,
3930 excess_data: Vec::new()
3932 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3933 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3934 short_channel_id: 7,
3936 flags: 2, // to disable
3937 cltv_expiry_delta: 0,
3938 htlc_minimum_msat: 0,
3939 htlc_maximum_msat: MAX_VALUE_MSAT,
3941 fee_proportional_millionths: 0,
3942 excess_data: Vec::new()
3945 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3946 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3947 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3948 assert_eq!(route.paths[0].hops.len(), 4);
3950 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3951 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3952 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3953 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3954 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3955 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3957 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3958 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3959 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3960 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3961 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3962 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3964 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3965 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3966 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3967 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3968 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3969 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3971 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3972 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3973 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3974 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3975 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3976 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3980 fn private_multi_hint_last_hops_test() {
3981 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3982 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3984 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3985 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3987 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3988 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3989 let scorer = ln_test_utils::TestScorer::new();
3990 // Test through channels 2, 3, 0xff00, 0xff01.
3991 // Test shows that multiple hop hints are considered.
3993 // Disabling channels 6 & 7 by flags=2
3994 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3995 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3996 short_channel_id: 6,
3998 flags: 2, // to disable
3999 cltv_expiry_delta: 0,
4000 htlc_minimum_msat: 0,
4001 htlc_maximum_msat: MAX_VALUE_MSAT,
4003 fee_proportional_millionths: 0,
4004 excess_data: Vec::new()
4006 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4007 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4008 short_channel_id: 7,
4010 flags: 2, // to disable
4011 cltv_expiry_delta: 0,
4012 htlc_minimum_msat: 0,
4013 htlc_maximum_msat: MAX_VALUE_MSAT,
4015 fee_proportional_millionths: 0,
4016 excess_data: Vec::new()
4019 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4020 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4021 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4022 assert_eq!(route.paths[0].hops.len(), 4);
4024 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4025 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4026 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4027 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4028 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4029 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4031 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4032 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4033 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4034 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4035 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4036 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4038 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4039 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4040 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4041 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4042 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4043 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4045 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4046 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4047 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4048 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4049 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4050 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4053 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4054 let zero_fees = RoutingFees {
4056 proportional_millionths: 0,
4058 vec![RouteHint(vec![RouteHintHop {
4059 src_node_id: nodes[4],
4060 short_channel_id: 11,
4062 cltv_expiry_delta: (11 << 4) | 1,
4063 htlc_minimum_msat: None,
4064 htlc_maximum_msat: None,
4066 src_node_id: nodes[3],
4067 short_channel_id: 8,
4069 cltv_expiry_delta: (8 << 4) | 1,
4070 htlc_minimum_msat: None,
4071 htlc_maximum_msat: None,
4072 }]), RouteHint(vec![RouteHintHop {
4073 src_node_id: nodes[4],
4074 short_channel_id: 9,
4077 proportional_millionths: 0,
4079 cltv_expiry_delta: (9 << 4) | 1,
4080 htlc_minimum_msat: None,
4081 htlc_maximum_msat: None,
4082 }]), RouteHint(vec![RouteHintHop {
4083 src_node_id: nodes[5],
4084 short_channel_id: 10,
4086 cltv_expiry_delta: (10 << 4) | 1,
4087 htlc_minimum_msat: None,
4088 htlc_maximum_msat: None,
4093 fn last_hops_with_public_channel_test() {
4094 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4095 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4096 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4097 let scorer = ln_test_utils::TestScorer::new();
4098 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4099 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4100 // This test shows that public routes can be present in the invoice
4101 // which would be handled in the same manner.
4103 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4104 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4105 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4106 assert_eq!(route.paths[0].hops.len(), 5);
4108 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4109 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4110 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4111 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4112 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4113 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4115 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4116 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4117 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4118 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4119 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4120 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4122 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4123 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4124 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4125 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4126 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4127 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4129 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4130 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4131 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4132 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4133 // If we have a peer in the node map, we'll use their features here since we don't have
4134 // a way of figuring out their features from the invoice:
4135 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4136 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4138 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4139 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4140 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4141 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4142 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4143 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4147 fn our_chans_last_hop_connect_test() {
4148 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4149 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4150 let scorer = ln_test_utils::TestScorer::new();
4151 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4152 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4154 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4155 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4156 let mut last_hops = last_hops(&nodes);
4157 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4158 .with_route_hints(last_hops.clone()).unwrap();
4159 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4160 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4161 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4162 &Default::default(), &random_seed_bytes).unwrap();
4163 assert_eq!(route.paths[0].hops.len(), 2);
4165 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4166 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4167 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4168 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4169 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4170 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4172 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4173 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4174 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4175 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4176 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4177 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4179 last_hops[0].0[0].fees.base_msat = 1000;
4181 // Revert to via 6 as the fee on 8 goes up
4182 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4183 .with_route_hints(last_hops).unwrap();
4184 let route_params = RouteParameters::from_payment_params_and_value(
4185 payment_params.clone(), 100);
4186 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4187 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4188 assert_eq!(route.paths[0].hops.len(), 4);
4190 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4191 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4192 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4193 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4194 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4195 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4197 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4198 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4199 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4200 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4201 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4202 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4204 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4205 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4206 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4207 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4208 // If we have a peer in the node map, we'll use their features here since we don't have
4209 // a way of figuring out their features from the invoice:
4210 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4211 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4213 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4214 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4215 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4216 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4217 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4218 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4220 // ...but still use 8 for larger payments as 6 has a variable feerate
4221 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4222 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4223 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4224 assert_eq!(route.paths[0].hops.len(), 5);
4226 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4227 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4228 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4229 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4230 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4231 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4233 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4234 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4235 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4236 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4237 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4238 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4240 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4241 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4242 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4243 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4244 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4245 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4247 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4248 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4249 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4250 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4251 // If we have a peer in the node map, we'll use their features here since we don't have
4252 // a way of figuring out their features from the invoice:
4253 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4254 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4256 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4257 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4258 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4259 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4260 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4261 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4264 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> {
4265 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4266 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4267 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4269 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4270 let last_hops = RouteHint(vec![RouteHintHop {
4271 src_node_id: middle_node_id,
4272 short_channel_id: 8,
4275 proportional_millionths: last_hop_fee_prop,
4277 cltv_expiry_delta: (8 << 4) | 1,
4278 htlc_minimum_msat: None,
4279 htlc_maximum_msat: last_hop_htlc_max,
4281 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4282 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4283 let scorer = ln_test_utils::TestScorer::new();
4284 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4285 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4286 let logger = ln_test_utils::TestLogger::new();
4287 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4288 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4289 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4290 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4291 &random_seed_bytes);
4296 fn unannounced_path_test() {
4297 // We should be able to send a payment to a destination without any help of a routing graph
4298 // if we have a channel with a common counterparty that appears in the first and last hop
4300 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4302 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4303 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4304 assert_eq!(route.paths[0].hops.len(), 2);
4306 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4307 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4308 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4309 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4310 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4311 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4313 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4314 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4315 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4316 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4317 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4318 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4322 fn overflow_unannounced_path_test_liquidity_underflow() {
4323 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4324 // the last-hop had a fee which overflowed a u64, we'd panic.
4325 // This was due to us adding the first-hop from us unconditionally, causing us to think
4326 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4327 // In this test, we previously hit a subtraction underflow due to having less available
4328 // liquidity at the last hop than 0.
4329 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());
4333 fn overflow_unannounced_path_test_feerate_overflow() {
4334 // This tests for the same case as above, except instead of hitting a subtraction
4335 // underflow, we hit a case where the fee charged at a hop overflowed.
4336 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());
4340 fn available_amount_while_routing_test() {
4341 // Tests whether we choose the correct available channel amount while routing.
4343 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4344 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4345 let scorer = ln_test_utils::TestScorer::new();
4346 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4347 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4348 let config = UserConfig::default();
4349 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4350 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4353 // We will use a simple single-path route from
4354 // our node to node2 via node0: channels {1, 3}.
4356 // First disable all other paths.
4357 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4358 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4359 short_channel_id: 2,
4362 cltv_expiry_delta: 0,
4363 htlc_minimum_msat: 0,
4364 htlc_maximum_msat: 100_000,
4366 fee_proportional_millionths: 0,
4367 excess_data: Vec::new()
4369 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4370 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4371 short_channel_id: 12,
4374 cltv_expiry_delta: 0,
4375 htlc_minimum_msat: 0,
4376 htlc_maximum_msat: 100_000,
4378 fee_proportional_millionths: 0,
4379 excess_data: Vec::new()
4382 // Make the first channel (#1) very permissive,
4383 // and we will be testing all limits on the second channel.
4384 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4385 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4386 short_channel_id: 1,
4389 cltv_expiry_delta: 0,
4390 htlc_minimum_msat: 0,
4391 htlc_maximum_msat: 1_000_000_000,
4393 fee_proportional_millionths: 0,
4394 excess_data: Vec::new()
4397 // First, let's see if routing works if we have absolutely no idea about the available amount.
4398 // In this case, it should be set to 250_000 sats.
4399 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4400 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4401 short_channel_id: 3,
4404 cltv_expiry_delta: 0,
4405 htlc_minimum_msat: 0,
4406 htlc_maximum_msat: 250_000_000,
4408 fee_proportional_millionths: 0,
4409 excess_data: Vec::new()
4413 // Attempt to route more than available results in a failure.
4414 let route_params = RouteParameters::from_payment_params_and_value(
4415 payment_params.clone(), 250_000_001);
4416 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4417 &our_id, &route_params, &network_graph.read_only(), None,
4418 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4419 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4420 } else { panic!(); }
4424 // Now, attempt to route an exact amount we have should be fine.
4425 let route_params = RouteParameters::from_payment_params_and_value(
4426 payment_params.clone(), 250_000_000);
4427 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4428 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4429 assert_eq!(route.paths.len(), 1);
4430 let path = route.paths.last().unwrap();
4431 assert_eq!(path.hops.len(), 2);
4432 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4433 assert_eq!(path.final_value_msat(), 250_000_000);
4436 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4437 // Disable channel #1 and use another first hop.
4438 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4439 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4440 short_channel_id: 1,
4443 cltv_expiry_delta: 0,
4444 htlc_minimum_msat: 0,
4445 htlc_maximum_msat: 1_000_000_000,
4447 fee_proportional_millionths: 0,
4448 excess_data: Vec::new()
4451 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4452 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4455 // Attempt to route more than available results in a failure.
4456 let route_params = RouteParameters::from_payment_params_and_value(
4457 payment_params.clone(), 200_000_001);
4458 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4459 &our_id, &route_params, &network_graph.read_only(),
4460 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4461 &Default::default(), &random_seed_bytes) {
4462 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4463 } else { panic!(); }
4467 // Now, attempt to route an exact amount we have should be fine.
4468 let route_params = RouteParameters::from_payment_params_and_value(
4469 payment_params.clone(), 200_000_000);
4470 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4471 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4472 &Default::default(), &random_seed_bytes).unwrap();
4473 assert_eq!(route.paths.len(), 1);
4474 let path = route.paths.last().unwrap();
4475 assert_eq!(path.hops.len(), 2);
4476 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4477 assert_eq!(path.final_value_msat(), 200_000_000);
4480 // Enable channel #1 back.
4481 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4482 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4483 short_channel_id: 1,
4486 cltv_expiry_delta: 0,
4487 htlc_minimum_msat: 0,
4488 htlc_maximum_msat: 1_000_000_000,
4490 fee_proportional_millionths: 0,
4491 excess_data: Vec::new()
4495 // Now let's see if routing works if we know only htlc_maximum_msat.
4496 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4497 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4498 short_channel_id: 3,
4501 cltv_expiry_delta: 0,
4502 htlc_minimum_msat: 0,
4503 htlc_maximum_msat: 15_000,
4505 fee_proportional_millionths: 0,
4506 excess_data: Vec::new()
4510 // Attempt to route more than available results in a failure.
4511 let route_params = RouteParameters::from_payment_params_and_value(
4512 payment_params.clone(), 15_001);
4513 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4514 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4515 &scorer, &Default::default(), &random_seed_bytes) {
4516 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4517 } else { panic!(); }
4521 // Now, attempt to route an exact amount we have should be fine.
4522 let route_params = RouteParameters::from_payment_params_and_value(
4523 payment_params.clone(), 15_000);
4524 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4525 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4526 assert_eq!(route.paths.len(), 1);
4527 let path = route.paths.last().unwrap();
4528 assert_eq!(path.hops.len(), 2);
4529 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4530 assert_eq!(path.final_value_msat(), 15_000);
4533 // Now let's see if routing works if we know only capacity from the UTXO.
4535 // We can't change UTXO capacity on the fly, so we'll disable
4536 // the existing channel and add another one with the capacity we need.
4537 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4538 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4539 short_channel_id: 3,
4542 cltv_expiry_delta: 0,
4543 htlc_minimum_msat: 0,
4544 htlc_maximum_msat: MAX_VALUE_MSAT,
4546 fee_proportional_millionths: 0,
4547 excess_data: Vec::new()
4550 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4551 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4552 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4553 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4554 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4556 *chain_monitor.utxo_ret.lock().unwrap() =
4557 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4558 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4560 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4561 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4562 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4563 short_channel_id: 333,
4566 cltv_expiry_delta: (3 << 4) | 1,
4567 htlc_minimum_msat: 0,
4568 htlc_maximum_msat: 15_000,
4570 fee_proportional_millionths: 0,
4571 excess_data: Vec::new()
4573 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4574 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4575 short_channel_id: 333,
4578 cltv_expiry_delta: (3 << 4) | 2,
4579 htlc_minimum_msat: 0,
4580 htlc_maximum_msat: 15_000,
4582 fee_proportional_millionths: 0,
4583 excess_data: Vec::new()
4587 // Attempt to route more than available results in a failure.
4588 let route_params = RouteParameters::from_payment_params_and_value(
4589 payment_params.clone(), 15_001);
4590 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4591 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4592 &scorer, &Default::default(), &random_seed_bytes) {
4593 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4594 } else { panic!(); }
4598 // Now, attempt to route an exact amount we have should be fine.
4599 let route_params = RouteParameters::from_payment_params_and_value(
4600 payment_params.clone(), 15_000);
4601 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4602 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4603 assert_eq!(route.paths.len(), 1);
4604 let path = route.paths.last().unwrap();
4605 assert_eq!(path.hops.len(), 2);
4606 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4607 assert_eq!(path.final_value_msat(), 15_000);
4610 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4611 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4612 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4613 short_channel_id: 333,
4616 cltv_expiry_delta: 0,
4617 htlc_minimum_msat: 0,
4618 htlc_maximum_msat: 10_000,
4620 fee_proportional_millionths: 0,
4621 excess_data: Vec::new()
4625 // Attempt to route more than available results in a failure.
4626 let route_params = RouteParameters::from_payment_params_and_value(
4627 payment_params.clone(), 10_001);
4628 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4629 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4630 &scorer, &Default::default(), &random_seed_bytes) {
4631 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4632 } else { panic!(); }
4636 // Now, attempt to route an exact amount we have should be fine.
4637 let route_params = RouteParameters::from_payment_params_and_value(
4638 payment_params.clone(), 10_000);
4639 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4640 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4641 assert_eq!(route.paths.len(), 1);
4642 let path = route.paths.last().unwrap();
4643 assert_eq!(path.hops.len(), 2);
4644 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4645 assert_eq!(path.final_value_msat(), 10_000);
4650 fn available_liquidity_last_hop_test() {
4651 // Check that available liquidity properly limits the path even when only
4652 // one of the latter hops is limited.
4653 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4654 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4655 let scorer = ln_test_utils::TestScorer::new();
4656 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4657 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4658 let config = UserConfig::default();
4659 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4660 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4663 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4664 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4665 // Total capacity: 50 sats.
4667 // Disable other potential paths.
4668 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4669 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4670 short_channel_id: 2,
4673 cltv_expiry_delta: 0,
4674 htlc_minimum_msat: 0,
4675 htlc_maximum_msat: 100_000,
4677 fee_proportional_millionths: 0,
4678 excess_data: Vec::new()
4680 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4681 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4682 short_channel_id: 7,
4685 cltv_expiry_delta: 0,
4686 htlc_minimum_msat: 0,
4687 htlc_maximum_msat: 100_000,
4689 fee_proportional_millionths: 0,
4690 excess_data: Vec::new()
4695 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4696 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4697 short_channel_id: 12,
4700 cltv_expiry_delta: 0,
4701 htlc_minimum_msat: 0,
4702 htlc_maximum_msat: 100_000,
4704 fee_proportional_millionths: 0,
4705 excess_data: Vec::new()
4707 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4708 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4709 short_channel_id: 13,
4712 cltv_expiry_delta: 0,
4713 htlc_minimum_msat: 0,
4714 htlc_maximum_msat: 100_000,
4716 fee_proportional_millionths: 0,
4717 excess_data: Vec::new()
4720 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4721 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4722 short_channel_id: 6,
4725 cltv_expiry_delta: 0,
4726 htlc_minimum_msat: 0,
4727 htlc_maximum_msat: 50_000,
4729 fee_proportional_millionths: 0,
4730 excess_data: Vec::new()
4732 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4733 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4734 short_channel_id: 11,
4737 cltv_expiry_delta: 0,
4738 htlc_minimum_msat: 0,
4739 htlc_maximum_msat: 100_000,
4741 fee_proportional_millionths: 0,
4742 excess_data: Vec::new()
4745 // Attempt to route more than available results in a failure.
4746 let route_params = RouteParameters::from_payment_params_and_value(
4747 payment_params.clone(), 60_000);
4748 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4749 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4750 &scorer, &Default::default(), &random_seed_bytes) {
4751 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4752 } else { panic!(); }
4756 // Now, attempt to route 49 sats (just a bit below the capacity).
4757 let route_params = RouteParameters::from_payment_params_and_value(
4758 payment_params.clone(), 49_000);
4759 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4760 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4761 assert_eq!(route.paths.len(), 1);
4762 let mut total_amount_paid_msat = 0;
4763 for path in &route.paths {
4764 assert_eq!(path.hops.len(), 4);
4765 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4766 total_amount_paid_msat += path.final_value_msat();
4768 assert_eq!(total_amount_paid_msat, 49_000);
4772 // Attempt to route an exact amount is also fine
4773 let route_params = RouteParameters::from_payment_params_and_value(
4774 payment_params, 50_000);
4775 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4776 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4777 assert_eq!(route.paths.len(), 1);
4778 let mut total_amount_paid_msat = 0;
4779 for path in &route.paths {
4780 assert_eq!(path.hops.len(), 4);
4781 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4782 total_amount_paid_msat += path.final_value_msat();
4784 assert_eq!(total_amount_paid_msat, 50_000);
4789 fn ignore_fee_first_hop_test() {
4790 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4791 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4792 let scorer = ln_test_utils::TestScorer::new();
4793 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4794 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4795 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4797 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4798 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4799 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4800 short_channel_id: 1,
4803 cltv_expiry_delta: 0,
4804 htlc_minimum_msat: 0,
4805 htlc_maximum_msat: 100_000,
4806 fee_base_msat: 1_000_000,
4807 fee_proportional_millionths: 0,
4808 excess_data: Vec::new()
4810 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4811 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4812 short_channel_id: 3,
4815 cltv_expiry_delta: 0,
4816 htlc_minimum_msat: 0,
4817 htlc_maximum_msat: 50_000,
4819 fee_proportional_millionths: 0,
4820 excess_data: Vec::new()
4824 let route_params = RouteParameters::from_payment_params_and_value(
4825 payment_params, 50_000);
4826 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4827 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4828 assert_eq!(route.paths.len(), 1);
4829 let mut total_amount_paid_msat = 0;
4830 for path in &route.paths {
4831 assert_eq!(path.hops.len(), 2);
4832 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4833 total_amount_paid_msat += path.final_value_msat();
4835 assert_eq!(total_amount_paid_msat, 50_000);
4840 fn simple_mpp_route_test() {
4841 let (secp_ctx, _, _, _, _) = build_graph();
4842 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4843 let config = UserConfig::default();
4844 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4845 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4847 do_simple_mpp_route_test(clear_payment_params);
4849 // MPP to a 1-hop blinded path for nodes[2]
4850 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
4851 let blinded_path = BlindedPath {
4852 introduction_node_id: nodes[2],
4853 blinding_point: ln_test_utils::pubkey(42),
4854 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4856 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4858 fee_proportional_millionths: 0,
4859 htlc_minimum_msat: 0,
4860 htlc_maximum_msat: 0,
4861 cltv_expiry_delta: 0,
4862 features: BlindedHopFeatures::empty(),
4864 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4865 .with_bolt12_features(bolt12_features.clone()).unwrap();
4866 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4868 // MPP to 3 2-hop blinded paths
4869 let mut blinded_path_node_0 = blinded_path.clone();
4870 blinded_path_node_0.introduction_node_id = nodes[0];
4871 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4872 let mut node_0_payinfo = blinded_payinfo.clone();
4873 node_0_payinfo.htlc_maximum_msat = 50_000;
4875 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4876 blinded_path_node_7.introduction_node_id = nodes[7];
4877 let mut node_7_payinfo = blinded_payinfo.clone();
4878 node_7_payinfo.htlc_maximum_msat = 60_000;
4880 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4881 blinded_path_node_1.introduction_node_id = nodes[1];
4882 let mut node_1_payinfo = blinded_payinfo.clone();
4883 node_1_payinfo.htlc_maximum_msat = 180_000;
4885 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4887 (node_0_payinfo, blinded_path_node_0),
4888 (node_7_payinfo, blinded_path_node_7),
4889 (node_1_payinfo, blinded_path_node_1)
4891 .with_bolt12_features(bolt12_features).unwrap();
4892 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4896 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4897 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4898 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4899 let scorer = ln_test_utils::TestScorer::new();
4900 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4901 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4903 // We need a route consisting of 3 paths:
4904 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4905 // To achieve this, the amount being transferred should be around
4906 // the total capacity of these 3 paths.
4908 // First, we set limits on these (previously unlimited) channels.
4909 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4911 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4912 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4913 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4914 short_channel_id: 1,
4917 cltv_expiry_delta: 0,
4918 htlc_minimum_msat: 0,
4919 htlc_maximum_msat: 100_000,
4921 fee_proportional_millionths: 0,
4922 excess_data: Vec::new()
4924 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4925 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4926 short_channel_id: 3,
4929 cltv_expiry_delta: 0,
4930 htlc_minimum_msat: 0,
4931 htlc_maximum_msat: 50_000,
4933 fee_proportional_millionths: 0,
4934 excess_data: Vec::new()
4937 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4938 // (total limit 60).
4939 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4940 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4941 short_channel_id: 12,
4944 cltv_expiry_delta: 0,
4945 htlc_minimum_msat: 0,
4946 htlc_maximum_msat: 60_000,
4948 fee_proportional_millionths: 0,
4949 excess_data: Vec::new()
4951 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4952 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4953 short_channel_id: 13,
4956 cltv_expiry_delta: 0,
4957 htlc_minimum_msat: 0,
4958 htlc_maximum_msat: 60_000,
4960 fee_proportional_millionths: 0,
4961 excess_data: Vec::new()
4964 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4965 // (total capacity 180 sats).
4966 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4967 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4968 short_channel_id: 2,
4971 cltv_expiry_delta: 0,
4972 htlc_minimum_msat: 0,
4973 htlc_maximum_msat: 200_000,
4975 fee_proportional_millionths: 0,
4976 excess_data: Vec::new()
4978 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4979 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4980 short_channel_id: 4,
4983 cltv_expiry_delta: 0,
4984 htlc_minimum_msat: 0,
4985 htlc_maximum_msat: 180_000,
4987 fee_proportional_millionths: 0,
4988 excess_data: Vec::new()
4992 // Attempt to route more than available results in a failure.
4993 let route_params = RouteParameters::from_payment_params_and_value(
4994 payment_params.clone(), 300_000);
4995 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4996 &our_id, &route_params, &network_graph.read_only(), None,
4997 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4998 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4999 } else { panic!(); }
5003 // Attempt to route while setting max_path_count to 0 results in a failure.
5004 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5005 let route_params = RouteParameters::from_payment_params_and_value(
5006 zero_payment_params, 100);
5007 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5008 &our_id, &route_params, &network_graph.read_only(), None,
5009 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5010 assert_eq!(err, "Can't find a route with no paths allowed.");
5011 } else { panic!(); }
5015 // Attempt to route while setting max_path_count to 3 results in a failure.
5016 // This is the case because the minimal_value_contribution_msat would require each path
5017 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5018 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5019 let route_params = RouteParameters::from_payment_params_and_value(
5020 fail_payment_params, 250_000);
5021 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5022 &our_id, &route_params, &network_graph.read_only(), None,
5023 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5024 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5025 } else { panic!(); }
5029 // Now, attempt to route 250 sats (just a bit below the capacity).
5030 // Our algorithm should provide us with these 3 paths.
5031 let route_params = RouteParameters::from_payment_params_and_value(
5032 payment_params.clone(), 250_000);
5033 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5034 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5035 assert_eq!(route.paths.len(), 3);
5036 let mut total_amount_paid_msat = 0;
5037 for path in &route.paths {
5038 if let Some(bt) = &path.blinded_tail {
5039 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5041 assert_eq!(path.hops.len(), 2);
5042 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5044 total_amount_paid_msat += path.final_value_msat();
5046 assert_eq!(total_amount_paid_msat, 250_000);
5050 // Attempt to route an exact amount is also fine
5051 let route_params = RouteParameters::from_payment_params_and_value(
5052 payment_params.clone(), 290_000);
5053 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5054 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5055 assert_eq!(route.paths.len(), 3);
5056 let mut total_amount_paid_msat = 0;
5057 for path in &route.paths {
5058 if payment_params.payee.blinded_route_hints().len() != 0 {
5059 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5060 if let Some(bt) = &path.blinded_tail {
5061 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5062 if bt.hops.len() > 1 {
5063 assert_eq!(path.hops.last().unwrap().pubkey,
5064 payment_params.payee.blinded_route_hints().iter()
5065 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5066 .map(|(_, p)| p.introduction_node_id).unwrap());
5068 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5071 assert_eq!(path.hops.len(), 2);
5072 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5074 total_amount_paid_msat += path.final_value_msat();
5076 assert_eq!(total_amount_paid_msat, 290_000);
5081 fn long_mpp_route_test() {
5082 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5083 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5084 let scorer = ln_test_utils::TestScorer::new();
5085 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5086 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5087 let config = UserConfig::default();
5088 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5089 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5092 // We need a route consisting of 3 paths:
5093 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5094 // Note that these paths overlap (channels 5, 12, 13).
5095 // We will route 300 sats.
5096 // Each path will have 100 sats capacity, those channels which
5097 // are used twice will have 200 sats capacity.
5099 // Disable other potential paths.
5100 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5101 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5102 short_channel_id: 2,
5105 cltv_expiry_delta: 0,
5106 htlc_minimum_msat: 0,
5107 htlc_maximum_msat: 100_000,
5109 fee_proportional_millionths: 0,
5110 excess_data: Vec::new()
5112 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5113 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5114 short_channel_id: 7,
5117 cltv_expiry_delta: 0,
5118 htlc_minimum_msat: 0,
5119 htlc_maximum_msat: 100_000,
5121 fee_proportional_millionths: 0,
5122 excess_data: Vec::new()
5125 // Path via {node0, node2} is channels {1, 3, 5}.
5126 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5127 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5128 short_channel_id: 1,
5131 cltv_expiry_delta: 0,
5132 htlc_minimum_msat: 0,
5133 htlc_maximum_msat: 100_000,
5135 fee_proportional_millionths: 0,
5136 excess_data: Vec::new()
5138 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5139 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5140 short_channel_id: 3,
5143 cltv_expiry_delta: 0,
5144 htlc_minimum_msat: 0,
5145 htlc_maximum_msat: 100_000,
5147 fee_proportional_millionths: 0,
5148 excess_data: Vec::new()
5151 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5152 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5153 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5154 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5155 short_channel_id: 5,
5158 cltv_expiry_delta: 0,
5159 htlc_minimum_msat: 0,
5160 htlc_maximum_msat: 200_000,
5162 fee_proportional_millionths: 0,
5163 excess_data: Vec::new()
5166 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5167 // Add 100 sats to the capacities of {12, 13}, because these channels
5168 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5169 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5170 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5171 short_channel_id: 12,
5174 cltv_expiry_delta: 0,
5175 htlc_minimum_msat: 0,
5176 htlc_maximum_msat: 200_000,
5178 fee_proportional_millionths: 0,
5179 excess_data: Vec::new()
5181 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5182 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5183 short_channel_id: 13,
5186 cltv_expiry_delta: 0,
5187 htlc_minimum_msat: 0,
5188 htlc_maximum_msat: 200_000,
5190 fee_proportional_millionths: 0,
5191 excess_data: Vec::new()
5194 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5195 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5196 short_channel_id: 6,
5199 cltv_expiry_delta: 0,
5200 htlc_minimum_msat: 0,
5201 htlc_maximum_msat: 100_000,
5203 fee_proportional_millionths: 0,
5204 excess_data: Vec::new()
5206 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5207 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5208 short_channel_id: 11,
5211 cltv_expiry_delta: 0,
5212 htlc_minimum_msat: 0,
5213 htlc_maximum_msat: 100_000,
5215 fee_proportional_millionths: 0,
5216 excess_data: Vec::new()
5219 // Path via {node7, node2} is channels {12, 13, 5}.
5220 // We already limited them to 200 sats (they are used twice for 100 sats).
5221 // Nothing to do here.
5224 // Attempt to route more than available results in a failure.
5225 let route_params = RouteParameters::from_payment_params_and_value(
5226 payment_params.clone(), 350_000);
5227 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5228 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5229 &scorer, &Default::default(), &random_seed_bytes) {
5230 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5231 } else { panic!(); }
5235 // Now, attempt to route 300 sats (exact amount we can route).
5236 // Our algorithm should provide us with these 3 paths, 100 sats each.
5237 let route_params = RouteParameters::from_payment_params_and_value(
5238 payment_params, 300_000);
5239 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5240 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5241 assert_eq!(route.paths.len(), 3);
5243 let mut total_amount_paid_msat = 0;
5244 for path in &route.paths {
5245 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5246 total_amount_paid_msat += path.final_value_msat();
5248 assert_eq!(total_amount_paid_msat, 300_000);
5254 fn mpp_cheaper_route_test() {
5255 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5256 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5257 let scorer = ln_test_utils::TestScorer::new();
5258 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5259 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5260 let config = UserConfig::default();
5261 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5262 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5265 // This test checks that if we have two cheaper paths and one more expensive path,
5266 // so that liquidity-wise any 2 of 3 combination is sufficient,
5267 // two cheaper paths will be taken.
5268 // These paths have equal available liquidity.
5270 // We need a combination of 3 paths:
5271 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5272 // Note that these paths overlap (channels 5, 12, 13).
5273 // Each path will have 100 sats capacity, those channels which
5274 // are used twice will have 200 sats capacity.
5276 // Disable other potential paths.
5277 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5278 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5279 short_channel_id: 2,
5282 cltv_expiry_delta: 0,
5283 htlc_minimum_msat: 0,
5284 htlc_maximum_msat: 100_000,
5286 fee_proportional_millionths: 0,
5287 excess_data: Vec::new()
5289 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5290 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5291 short_channel_id: 7,
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()
5302 // Path via {node0, node2} is channels {1, 3, 5}.
5303 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5304 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5305 short_channel_id: 1,
5308 cltv_expiry_delta: 0,
5309 htlc_minimum_msat: 0,
5310 htlc_maximum_msat: 100_000,
5312 fee_proportional_millionths: 0,
5313 excess_data: Vec::new()
5315 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5316 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5317 short_channel_id: 3,
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()
5328 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5329 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5330 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5331 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5332 short_channel_id: 5,
5335 cltv_expiry_delta: 0,
5336 htlc_minimum_msat: 0,
5337 htlc_maximum_msat: 200_000,
5339 fee_proportional_millionths: 0,
5340 excess_data: Vec::new()
5343 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5344 // Add 100 sats to the capacities of {12, 13}, because these channels
5345 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5346 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5347 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5348 short_channel_id: 12,
5351 cltv_expiry_delta: 0,
5352 htlc_minimum_msat: 0,
5353 htlc_maximum_msat: 200_000,
5355 fee_proportional_millionths: 0,
5356 excess_data: Vec::new()
5358 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5359 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5360 short_channel_id: 13,
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()
5371 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5372 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5373 short_channel_id: 6,
5376 cltv_expiry_delta: 0,
5377 htlc_minimum_msat: 0,
5378 htlc_maximum_msat: 100_000,
5379 fee_base_msat: 1_000,
5380 fee_proportional_millionths: 0,
5381 excess_data: Vec::new()
5383 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5384 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5385 short_channel_id: 11,
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()
5396 // Path via {node7, node2} is channels {12, 13, 5}.
5397 // We already limited them to 200 sats (they are used twice for 100 sats).
5398 // Nothing to do here.
5401 // Now, attempt to route 180 sats.
5402 // Our algorithm should provide us with these 2 paths.
5403 let route_params = RouteParameters::from_payment_params_and_value(
5404 payment_params, 180_000);
5405 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5406 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5407 assert_eq!(route.paths.len(), 2);
5409 let mut total_value_transferred_msat = 0;
5410 let mut total_paid_msat = 0;
5411 for path in &route.paths {
5412 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5413 total_value_transferred_msat += path.final_value_msat();
5414 for hop in &path.hops {
5415 total_paid_msat += hop.fee_msat;
5418 // If we paid fee, this would be higher.
5419 assert_eq!(total_value_transferred_msat, 180_000);
5420 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5421 assert_eq!(total_fees_paid, 0);
5426 fn fees_on_mpp_route_test() {
5427 // This test makes sure that MPP algorithm properly takes into account
5428 // fees charged on the channels, by making the fees impactful:
5429 // if the fee is not properly accounted for, the behavior is different.
5430 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5431 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5432 let scorer = ln_test_utils::TestScorer::new();
5433 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5434 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5435 let config = UserConfig::default();
5436 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5437 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5440 // We need a route consisting of 2 paths:
5441 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5442 // We will route 200 sats, Each path will have 100 sats capacity.
5444 // This test is not particularly stable: e.g.,
5445 // there's a way to route via {node0, node2, node4}.
5446 // It works while pathfinding is deterministic, but can be broken otherwise.
5447 // It's fine to ignore this concern for now.
5449 // Disable other potential paths.
5450 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5451 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5452 short_channel_id: 2,
5455 cltv_expiry_delta: 0,
5456 htlc_minimum_msat: 0,
5457 htlc_maximum_msat: 100_000,
5459 fee_proportional_millionths: 0,
5460 excess_data: Vec::new()
5463 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5464 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5465 short_channel_id: 7,
5468 cltv_expiry_delta: 0,
5469 htlc_minimum_msat: 0,
5470 htlc_maximum_msat: 100_000,
5472 fee_proportional_millionths: 0,
5473 excess_data: Vec::new()
5476 // Path via {node0, node2} is channels {1, 3, 5}.
5477 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5478 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5479 short_channel_id: 1,
5482 cltv_expiry_delta: 0,
5483 htlc_minimum_msat: 0,
5484 htlc_maximum_msat: 100_000,
5486 fee_proportional_millionths: 0,
5487 excess_data: Vec::new()
5489 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5490 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5491 short_channel_id: 3,
5494 cltv_expiry_delta: 0,
5495 htlc_minimum_msat: 0,
5496 htlc_maximum_msat: 100_000,
5498 fee_proportional_millionths: 0,
5499 excess_data: Vec::new()
5502 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5503 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5504 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5505 short_channel_id: 5,
5508 cltv_expiry_delta: 0,
5509 htlc_minimum_msat: 0,
5510 htlc_maximum_msat: 100_000,
5512 fee_proportional_millionths: 0,
5513 excess_data: Vec::new()
5516 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5517 // All channels should be 100 sats capacity. But for the fee experiment,
5518 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5519 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5520 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5521 // so no matter how large are other channels,
5522 // the whole path will be limited by 100 sats with just these 2 conditions:
5523 // - channel 12 capacity is 250 sats
5524 // - fee for channel 6 is 150 sats
5525 // Let's test this by enforcing these 2 conditions and removing other limits.
5526 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5527 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5528 short_channel_id: 12,
5531 cltv_expiry_delta: 0,
5532 htlc_minimum_msat: 0,
5533 htlc_maximum_msat: 250_000,
5535 fee_proportional_millionths: 0,
5536 excess_data: Vec::new()
5538 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5539 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5540 short_channel_id: 13,
5543 cltv_expiry_delta: 0,
5544 htlc_minimum_msat: 0,
5545 htlc_maximum_msat: MAX_VALUE_MSAT,
5547 fee_proportional_millionths: 0,
5548 excess_data: Vec::new()
5551 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5552 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5553 short_channel_id: 6,
5556 cltv_expiry_delta: 0,
5557 htlc_minimum_msat: 0,
5558 htlc_maximum_msat: MAX_VALUE_MSAT,
5559 fee_base_msat: 150_000,
5560 fee_proportional_millionths: 0,
5561 excess_data: Vec::new()
5563 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5564 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5565 short_channel_id: 11,
5568 cltv_expiry_delta: 0,
5569 htlc_minimum_msat: 0,
5570 htlc_maximum_msat: MAX_VALUE_MSAT,
5572 fee_proportional_millionths: 0,
5573 excess_data: Vec::new()
5577 // Attempt to route more than available results in a failure.
5578 let route_params = RouteParameters::from_payment_params_and_value(
5579 payment_params.clone(), 210_000);
5580 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5581 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5582 &scorer, &Default::default(), &random_seed_bytes) {
5583 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5584 } else { panic!(); }
5588 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5589 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5590 max_total_routing_fee_msat: Some(149_999) };
5591 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5592 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5593 &scorer, &Default::default(), &random_seed_bytes) {
5594 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5595 } else { panic!(); }
5599 // Now, attempt to route 200 sats (exact amount we can route).
5600 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5601 max_total_routing_fee_msat: Some(150_000) };
5602 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5603 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5604 assert_eq!(route.paths.len(), 2);
5606 let mut total_amount_paid_msat = 0;
5607 for path in &route.paths {
5608 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5609 total_amount_paid_msat += path.final_value_msat();
5611 assert_eq!(total_amount_paid_msat, 200_000);
5612 assert_eq!(route.get_total_fees(), 150_000);
5617 fn mpp_with_last_hops() {
5618 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5619 // via a single last-hop route hint, we'd fail to route if we first collected routes
5620 // totaling close but not quite enough to fund the full payment.
5622 // This was because we considered last-hop hints to have exactly the sought payment amount
5623 // instead of the amount we were trying to collect, needlessly limiting our path searching
5624 // at the very first hop.
5626 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5627 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5628 // to only have the remaining to-collect amount in available liquidity.
5630 // This bug appeared in production in some specific channel configurations.
5631 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5632 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5633 let scorer = ln_test_utils::TestScorer::new();
5634 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5635 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5636 let config = UserConfig::default();
5637 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5638 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5639 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5640 src_node_id: nodes[2],
5641 short_channel_id: 42,
5642 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5643 cltv_expiry_delta: 42,
5644 htlc_minimum_msat: None,
5645 htlc_maximum_msat: None,
5646 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5648 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5649 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5650 // would first use the no-fee route and then fail to find a path along the second route as
5651 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5652 // under 5% of our payment amount.
5653 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5654 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5655 short_channel_id: 1,
5658 cltv_expiry_delta: (5 << 4) | 5,
5659 htlc_minimum_msat: 0,
5660 htlc_maximum_msat: 99_000,
5661 fee_base_msat: u32::max_value(),
5662 fee_proportional_millionths: u32::max_value(),
5663 excess_data: Vec::new()
5665 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5666 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5667 short_channel_id: 2,
5670 cltv_expiry_delta: (5 << 4) | 3,
5671 htlc_minimum_msat: 0,
5672 htlc_maximum_msat: 99_000,
5673 fee_base_msat: u32::max_value(),
5674 fee_proportional_millionths: u32::max_value(),
5675 excess_data: Vec::new()
5677 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5678 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5679 short_channel_id: 4,
5682 cltv_expiry_delta: (4 << 4) | 1,
5683 htlc_minimum_msat: 0,
5684 htlc_maximum_msat: MAX_VALUE_MSAT,
5686 fee_proportional_millionths: 0,
5687 excess_data: Vec::new()
5689 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5690 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5691 short_channel_id: 13,
5693 flags: 0|2, // Channel disabled
5694 cltv_expiry_delta: (13 << 4) | 1,
5695 htlc_minimum_msat: 0,
5696 htlc_maximum_msat: MAX_VALUE_MSAT,
5698 fee_proportional_millionths: 2000000,
5699 excess_data: Vec::new()
5702 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5704 let route_params = RouteParameters::from_payment_params_and_value(
5705 payment_params, 100_000);
5706 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5707 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5708 assert_eq!(route.paths.len(), 2);
5709 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5710 // Paths are manually ordered ordered by SCID, so:
5711 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5712 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5713 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5714 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5715 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5716 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5717 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5718 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5719 assert_eq!(route.get_total_fees(), 1);
5720 assert_eq!(route.get_total_amount(), 100_000);
5724 fn drop_lowest_channel_mpp_route_test() {
5725 // This test checks that low-capacity channel is dropped when after
5726 // path finding we realize that we found more capacity than we need.
5727 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5728 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5729 let scorer = ln_test_utils::TestScorer::new();
5730 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5731 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5732 let config = UserConfig::default();
5733 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5734 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5736 .with_max_channel_saturation_power_of_half(0);
5738 // We need a route consisting of 3 paths:
5739 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5741 // The first and the second paths should be sufficient, but the third should be
5742 // cheaper, so that we select it but drop later.
5744 // First, we set limits on these (previously unlimited) channels.
5745 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5747 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5748 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5749 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5750 short_channel_id: 1,
5753 cltv_expiry_delta: 0,
5754 htlc_minimum_msat: 0,
5755 htlc_maximum_msat: 100_000,
5757 fee_proportional_millionths: 0,
5758 excess_data: Vec::new()
5760 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5761 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5762 short_channel_id: 3,
5765 cltv_expiry_delta: 0,
5766 htlc_minimum_msat: 0,
5767 htlc_maximum_msat: 50_000,
5769 fee_proportional_millionths: 0,
5770 excess_data: Vec::new()
5773 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5774 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5775 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5776 short_channel_id: 12,
5779 cltv_expiry_delta: 0,
5780 htlc_minimum_msat: 0,
5781 htlc_maximum_msat: 60_000,
5783 fee_proportional_millionths: 0,
5784 excess_data: Vec::new()
5786 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5787 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5788 short_channel_id: 13,
5791 cltv_expiry_delta: 0,
5792 htlc_minimum_msat: 0,
5793 htlc_maximum_msat: 60_000,
5795 fee_proportional_millionths: 0,
5796 excess_data: Vec::new()
5799 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5800 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5801 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5802 short_channel_id: 2,
5805 cltv_expiry_delta: 0,
5806 htlc_minimum_msat: 0,
5807 htlc_maximum_msat: 20_000,
5809 fee_proportional_millionths: 0,
5810 excess_data: Vec::new()
5812 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5813 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5814 short_channel_id: 4,
5817 cltv_expiry_delta: 0,
5818 htlc_minimum_msat: 0,
5819 htlc_maximum_msat: 20_000,
5821 fee_proportional_millionths: 0,
5822 excess_data: Vec::new()
5826 // Attempt to route more than available results in a failure.
5827 let route_params = RouteParameters::from_payment_params_and_value(
5828 payment_params.clone(), 150_000);
5829 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5830 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5831 &scorer, &Default::default(), &random_seed_bytes) {
5832 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5833 } else { panic!(); }
5837 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5838 // Our algorithm should provide us with these 3 paths.
5839 let route_params = RouteParameters::from_payment_params_and_value(
5840 payment_params.clone(), 125_000);
5841 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5842 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5843 assert_eq!(route.paths.len(), 3);
5844 let mut total_amount_paid_msat = 0;
5845 for path in &route.paths {
5846 assert_eq!(path.hops.len(), 2);
5847 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5848 total_amount_paid_msat += path.final_value_msat();
5850 assert_eq!(total_amount_paid_msat, 125_000);
5854 // Attempt to route without the last small cheap channel
5855 let route_params = RouteParameters::from_payment_params_and_value(
5856 payment_params, 90_000);
5857 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5858 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5859 assert_eq!(route.paths.len(), 2);
5860 let mut total_amount_paid_msat = 0;
5861 for path in &route.paths {
5862 assert_eq!(path.hops.len(), 2);
5863 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5864 total_amount_paid_msat += path.final_value_msat();
5866 assert_eq!(total_amount_paid_msat, 90_000);
5871 fn min_criteria_consistency() {
5872 // Test that we don't use an inconsistent metric between updating and walking nodes during
5873 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5874 // was updated with a different criterion from the heap sorting, resulting in loops in
5875 // calculated paths. We test for that specific case here.
5877 // We construct a network that looks like this:
5879 // node2 -1(3)2- node3
5883 // node1 -1(5)2- node4 -1(1)2- node6
5889 // We create a loop on the side of our real path - our destination is node 6, with a
5890 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5891 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5892 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5893 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5894 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5895 // "previous hop" being set to node 3, creating a loop in the path.
5896 let secp_ctx = Secp256k1::new();
5897 let logger = Arc::new(ln_test_utils::TestLogger::new());
5898 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5899 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5900 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5901 let scorer = ln_test_utils::TestScorer::new();
5902 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5903 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5904 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5906 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5907 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5908 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5909 short_channel_id: 6,
5912 cltv_expiry_delta: (6 << 4) | 0,
5913 htlc_minimum_msat: 0,
5914 htlc_maximum_msat: MAX_VALUE_MSAT,
5916 fee_proportional_millionths: 0,
5917 excess_data: Vec::new()
5919 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5921 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5922 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5923 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5924 short_channel_id: 5,
5927 cltv_expiry_delta: (5 << 4) | 0,
5928 htlc_minimum_msat: 0,
5929 htlc_maximum_msat: MAX_VALUE_MSAT,
5931 fee_proportional_millionths: 0,
5932 excess_data: Vec::new()
5934 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5936 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5937 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5938 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5939 short_channel_id: 4,
5942 cltv_expiry_delta: (4 << 4) | 0,
5943 htlc_minimum_msat: 0,
5944 htlc_maximum_msat: MAX_VALUE_MSAT,
5946 fee_proportional_millionths: 0,
5947 excess_data: Vec::new()
5949 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5951 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5952 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5953 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5954 short_channel_id: 3,
5957 cltv_expiry_delta: (3 << 4) | 0,
5958 htlc_minimum_msat: 0,
5959 htlc_maximum_msat: MAX_VALUE_MSAT,
5961 fee_proportional_millionths: 0,
5962 excess_data: Vec::new()
5964 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5966 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5967 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5968 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5969 short_channel_id: 2,
5972 cltv_expiry_delta: (2 << 4) | 0,
5973 htlc_minimum_msat: 0,
5974 htlc_maximum_msat: MAX_VALUE_MSAT,
5976 fee_proportional_millionths: 0,
5977 excess_data: Vec::new()
5980 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5981 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5982 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5983 short_channel_id: 1,
5986 cltv_expiry_delta: (1 << 4) | 0,
5987 htlc_minimum_msat: 100,
5988 htlc_maximum_msat: MAX_VALUE_MSAT,
5990 fee_proportional_millionths: 0,
5991 excess_data: Vec::new()
5993 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5996 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5997 let route_params = RouteParameters::from_payment_params_and_value(
5998 payment_params, 10_000);
5999 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6000 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6001 assert_eq!(route.paths.len(), 1);
6002 assert_eq!(route.paths[0].hops.len(), 3);
6004 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6005 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6006 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6007 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6008 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6009 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6011 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6012 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6013 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6014 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6015 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6016 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6018 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6019 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6020 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6021 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6022 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6023 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6029 fn exact_fee_liquidity_limit() {
6030 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6031 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6032 // we calculated fees on a higher value, resulting in us ignoring such paths.
6033 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6034 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6035 let scorer = ln_test_utils::TestScorer::new();
6036 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6037 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6038 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6040 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6042 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6043 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6044 short_channel_id: 2,
6047 cltv_expiry_delta: 0,
6048 htlc_minimum_msat: 0,
6049 htlc_maximum_msat: 85_000,
6051 fee_proportional_millionths: 0,
6052 excess_data: Vec::new()
6055 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6056 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6057 short_channel_id: 12,
6060 cltv_expiry_delta: (4 << 4) | 1,
6061 htlc_minimum_msat: 0,
6062 htlc_maximum_msat: 270_000,
6064 fee_proportional_millionths: 1000000,
6065 excess_data: Vec::new()
6069 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6070 // 200% fee charged channel 13 in the 1-to-2 direction.
6071 let mut route_params = RouteParameters::from_payment_params_and_value(
6072 payment_params, 90_000);
6073 route_params.max_total_routing_fee_msat = Some(90_000*2);
6074 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6075 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6076 assert_eq!(route.paths.len(), 1);
6077 assert_eq!(route.paths[0].hops.len(), 2);
6079 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6080 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6081 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6082 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6083 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6084 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6086 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6087 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6088 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6089 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6090 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6091 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6096 fn htlc_max_reduction_below_min() {
6097 // Test that if, while walking the graph, we reduce the value being sent to meet an
6098 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6099 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6100 // resulting in us thinking there is no possible path, even if other paths exist.
6101 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6102 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6103 let scorer = ln_test_utils::TestScorer::new();
6104 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6105 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6106 let config = UserConfig::default();
6107 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6108 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6111 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6112 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6113 // then try to send 90_000.
6114 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6115 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6116 short_channel_id: 2,
6119 cltv_expiry_delta: 0,
6120 htlc_minimum_msat: 0,
6121 htlc_maximum_msat: 80_000,
6123 fee_proportional_millionths: 0,
6124 excess_data: Vec::new()
6126 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6127 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6128 short_channel_id: 4,
6131 cltv_expiry_delta: (4 << 4) | 1,
6132 htlc_minimum_msat: 90_000,
6133 htlc_maximum_msat: MAX_VALUE_MSAT,
6135 fee_proportional_millionths: 0,
6136 excess_data: Vec::new()
6140 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6141 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6142 // expensive) channels 12-13 path.
6143 let mut route_params = RouteParameters::from_payment_params_and_value(
6144 payment_params, 90_000);
6145 route_params.max_total_routing_fee_msat = Some(90_000*2);
6146 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6147 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6148 assert_eq!(route.paths.len(), 1);
6149 assert_eq!(route.paths[0].hops.len(), 2);
6151 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6152 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6153 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6154 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6155 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6156 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6158 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6159 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6160 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6161 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6162 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6163 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6168 fn multiple_direct_first_hops() {
6169 // Previously we'd only ever considered one first hop path per counterparty.
6170 // However, as we don't restrict users to one channel per peer, we really need to support
6171 // looking at all first hop paths.
6172 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6173 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6174 // route over multiple channels with the same first hop.
6175 let secp_ctx = Secp256k1::new();
6176 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6177 let logger = Arc::new(ln_test_utils::TestLogger::new());
6178 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6179 let scorer = ln_test_utils::TestScorer::new();
6180 let config = UserConfig::default();
6181 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6182 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6184 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6185 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6188 let route_params = RouteParameters::from_payment_params_and_value(
6189 payment_params.clone(), 100_000);
6190 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6191 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6192 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6193 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6194 assert_eq!(route.paths.len(), 1);
6195 assert_eq!(route.paths[0].hops.len(), 1);
6197 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6198 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6199 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6202 let route_params = RouteParameters::from_payment_params_and_value(
6203 payment_params.clone(), 100_000);
6204 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6205 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6206 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6207 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6208 assert_eq!(route.paths.len(), 2);
6209 assert_eq!(route.paths[0].hops.len(), 1);
6210 assert_eq!(route.paths[1].hops.len(), 1);
6212 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6213 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6215 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6216 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6218 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6219 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6223 // If we have a bunch of outbound channels to the same node, where most are not
6224 // sufficient to pay the full payment, but one is, we should default to just using the
6225 // one single channel that has sufficient balance, avoiding MPP.
6227 // If we have several options above the 3xpayment value threshold, we should pick the
6228 // smallest of them, avoiding further fragmenting our available outbound balance to
6230 let route_params = RouteParameters::from_payment_params_and_value(
6231 payment_params, 100_000);
6232 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6233 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6234 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6235 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6236 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6237 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6238 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6239 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6240 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6241 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6242 assert_eq!(route.paths.len(), 1);
6243 assert_eq!(route.paths[0].hops.len(), 1);
6245 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6246 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6247 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6252 fn prefers_shorter_route_with_higher_fees() {
6253 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6254 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6255 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6257 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6258 let scorer = ln_test_utils::TestScorer::new();
6259 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6260 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6261 let route_params = RouteParameters::from_payment_params_and_value(
6262 payment_params.clone(), 100);
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 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6267 assert_eq!(route.get_total_fees(), 100);
6268 assert_eq!(route.get_total_amount(), 100);
6269 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6271 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6272 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6273 let scorer = FixedPenaltyScorer::with_penalty(100);
6274 let route_params = RouteParameters::from_payment_params_and_value(
6275 payment_params, 100);
6276 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6277 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6278 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6280 assert_eq!(route.get_total_fees(), 300);
6281 assert_eq!(route.get_total_amount(), 100);
6282 assert_eq!(path, vec![2, 4, 7, 10]);
6285 struct BadChannelScorer {
6286 short_channel_id: u64,
6290 impl Writeable for BadChannelScorer {
6291 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6293 impl ScoreLookUp for BadChannelScorer {
6294 type ScoreParams = ();
6295 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6296 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6300 struct BadNodeScorer {
6305 impl Writeable for BadNodeScorer {
6306 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6309 impl ScoreLookUp for BadNodeScorer {
6310 type ScoreParams = ();
6311 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6312 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6317 fn avoids_routing_through_bad_channels_and_nodes() {
6318 let (secp_ctx, network, _, _, logger) = build_graph();
6319 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6320 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6321 let network_graph = network.read_only();
6323 // A path to nodes[6] exists when no penalties are applied to any channel.
6324 let scorer = ln_test_utils::TestScorer::new();
6325 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6326 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6327 let route_params = RouteParameters::from_payment_params_and_value(
6328 payment_params, 100);
6329 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6330 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6331 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6333 assert_eq!(route.get_total_fees(), 100);
6334 assert_eq!(route.get_total_amount(), 100);
6335 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6337 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6338 let scorer = BadChannelScorer { short_channel_id: 6 };
6339 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6340 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6341 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6343 assert_eq!(route.get_total_fees(), 300);
6344 assert_eq!(route.get_total_amount(), 100);
6345 assert_eq!(path, vec![2, 4, 7, 10]);
6347 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6348 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6349 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6350 &scorer, &Default::default(), &random_seed_bytes) {
6351 Err(LightningError { err, .. } ) => {
6352 assert_eq!(err, "Failed to find a path to the given destination");
6354 Ok(_) => panic!("Expected error"),
6359 fn total_fees_single_path() {
6361 paths: vec![Path { hops: vec![
6363 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6364 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6365 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6368 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6369 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6370 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6373 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6374 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6375 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6377 ], blinded_tail: None }],
6381 assert_eq!(route.get_total_fees(), 250);
6382 assert_eq!(route.get_total_amount(), 225);
6386 fn total_fees_multi_path() {
6388 paths: vec![Path { hops: vec![
6390 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6391 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6392 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6395 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6396 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6397 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6399 ], blinded_tail: None }, Path { hops: vec![
6401 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6402 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6403 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6406 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6407 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6408 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6410 ], blinded_tail: None }],
6414 assert_eq!(route.get_total_fees(), 200);
6415 assert_eq!(route.get_total_amount(), 300);
6419 fn total_empty_route_no_panic() {
6420 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6421 // would both panic if the route was completely empty. We test to ensure they return 0
6422 // here, even though its somewhat nonsensical as a route.
6423 let route = Route { paths: Vec::new(), route_params: None };
6425 assert_eq!(route.get_total_fees(), 0);
6426 assert_eq!(route.get_total_amount(), 0);
6430 fn limits_total_cltv_delta() {
6431 let (secp_ctx, network, _, _, logger) = build_graph();
6432 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6433 let network_graph = network.read_only();
6435 let scorer = ln_test_utils::TestScorer::new();
6437 // Make sure that generally there is at least one route available
6438 let feasible_max_total_cltv_delta = 1008;
6439 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6440 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6441 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6442 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6443 let route_params = RouteParameters::from_payment_params_and_value(
6444 feasible_payment_params, 100);
6445 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6446 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6447 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6448 assert_ne!(path.len(), 0);
6450 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6451 let fail_max_total_cltv_delta = 23;
6452 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6453 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6454 let route_params = RouteParameters::from_payment_params_and_value(
6455 fail_payment_params, 100);
6456 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6457 &Default::default(), &random_seed_bytes)
6459 Err(LightningError { err, .. } ) => {
6460 assert_eq!(err, "Failed to find a path to the given destination");
6462 Ok(_) => panic!("Expected error"),
6467 fn avoids_recently_failed_paths() {
6468 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6469 // randomly inserting channels into it until we can't find a route anymore.
6470 let (secp_ctx, network, _, _, logger) = build_graph();
6471 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6472 let network_graph = network.read_only();
6474 let scorer = ln_test_utils::TestScorer::new();
6475 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6476 .with_max_path_count(1);
6477 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6478 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6480 // We should be able to find a route initially, and then after we fail a few random
6481 // channels eventually we won't be able to any longer.
6482 let route_params = RouteParameters::from_payment_params_and_value(
6483 payment_params.clone(), 100);
6484 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6485 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6487 let route_params = RouteParameters::from_payment_params_and_value(
6488 payment_params.clone(), 100);
6489 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6490 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6492 for chan in route.paths[0].hops.iter() {
6493 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6495 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6496 % route.paths[0].hops.len();
6497 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6503 fn limits_path_length() {
6504 let (secp_ctx, network, _, _, logger) = build_line_graph();
6505 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6506 let network_graph = network.read_only();
6508 let scorer = ln_test_utils::TestScorer::new();
6509 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6510 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6512 // First check we can actually create a long route on this graph.
6513 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6514 let route_params = RouteParameters::from_payment_params_and_value(
6515 feasible_payment_params, 100);
6516 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6517 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6518 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6519 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6521 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6522 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6523 let route_params = RouteParameters::from_payment_params_and_value(
6524 fail_payment_params, 100);
6525 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6526 &Default::default(), &random_seed_bytes)
6528 Err(LightningError { err, .. } ) => {
6529 assert_eq!(err, "Failed to find a path to the given destination");
6531 Ok(_) => panic!("Expected error"),
6536 fn adds_and_limits_cltv_offset() {
6537 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6538 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6540 let scorer = ln_test_utils::TestScorer::new();
6542 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6543 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6544 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6545 let route_params = RouteParameters::from_payment_params_and_value(
6546 payment_params.clone(), 100);
6547 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6548 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6549 assert_eq!(route.paths.len(), 1);
6551 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6553 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6554 let mut route_default = route.clone();
6555 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6556 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6557 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6558 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6559 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6561 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6562 let mut route_limited = route.clone();
6563 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6564 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6565 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6566 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6567 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6571 fn adds_plausible_cltv_offset() {
6572 let (secp_ctx, network, _, _, logger) = build_graph();
6573 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6574 let network_graph = network.read_only();
6575 let network_nodes = network_graph.nodes();
6576 let network_channels = network_graph.channels();
6577 let scorer = ln_test_utils::TestScorer::new();
6578 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6579 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6580 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6582 let route_params = RouteParameters::from_payment_params_and_value(
6583 payment_params.clone(), 100);
6584 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6585 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6586 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6588 let mut path_plausibility = vec![];
6590 for p in route.paths {
6591 // 1. Select random observation point
6592 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6593 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6595 prng.process_in_place(&mut random_bytes);
6596 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6597 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6599 // 2. Calculate what CLTV expiry delta we would observe there
6600 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6602 // 3. Starting from the observation point, find candidate paths
6603 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6604 candidates.push_back((observation_point, vec![]));
6606 let mut found_plausible_candidate = false;
6608 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6609 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6610 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6611 found_plausible_candidate = true;
6612 break 'candidate_loop;
6616 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6617 for channel_id in &cur_node.channels {
6618 if let Some(channel_info) = network_channels.get(&channel_id) {
6619 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6620 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6621 if cur_path_cltv_deltas.iter().sum::<u32>()
6622 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6623 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6624 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6625 candidates.push_back((*next_id, new_path_cltv_deltas));
6633 path_plausibility.push(found_plausible_candidate);
6635 assert!(path_plausibility.iter().all(|x| *x));
6639 fn builds_correct_path_from_hops() {
6640 let (secp_ctx, network, _, _, logger) = build_graph();
6641 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6642 let network_graph = network.read_only();
6644 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6645 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6647 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6648 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6649 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6650 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6651 Arc::clone(&logger), &random_seed_bytes).unwrap();
6652 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6653 assert_eq!(hops.len(), route.paths[0].hops.len());
6654 for (idx, hop_pubkey) in hops.iter().enumerate() {
6655 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6660 fn avoids_saturating_channels() {
6661 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6662 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6663 let decay_params = ProbabilisticScoringDecayParameters::default();
6664 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6666 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6667 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6668 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6669 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6670 short_channel_id: 4,
6673 cltv_expiry_delta: (4 << 4) | 1,
6674 htlc_minimum_msat: 0,
6675 htlc_maximum_msat: 250_000_000,
6677 fee_proportional_millionths: 0,
6678 excess_data: Vec::new()
6680 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6681 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6682 short_channel_id: 13,
6685 cltv_expiry_delta: (13 << 4) | 1,
6686 htlc_minimum_msat: 0,
6687 htlc_maximum_msat: 250_000_000,
6689 fee_proportional_millionths: 0,
6690 excess_data: Vec::new()
6693 let config = UserConfig::default();
6694 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6695 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6697 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6698 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6699 // 100,000 sats is less than the available liquidity on each channel, set above.
6700 let route_params = RouteParameters::from_payment_params_and_value(
6701 payment_params, 100_000_000);
6702 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6703 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6704 assert_eq!(route.paths.len(), 2);
6705 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6706 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6709 #[cfg(not(feature = "no-std"))]
6710 pub(super) fn random_init_seed() -> u64 {
6711 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6712 use core::hash::{BuildHasher, Hasher};
6713 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6714 println!("Using seed of {}", seed);
6719 #[cfg(not(feature = "no-std"))]
6720 fn generate_routes() {
6721 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6723 let logger = ln_test_utils::TestLogger::new();
6724 let graph = match super::bench_utils::read_network_graph(&logger) {
6732 let params = ProbabilisticScoringFeeParameters::default();
6733 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6734 let features = super::Bolt11InvoiceFeatures::empty();
6736 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6740 #[cfg(not(feature = "no-std"))]
6741 fn generate_routes_mpp() {
6742 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6744 let logger = ln_test_utils::TestLogger::new();
6745 let graph = match super::bench_utils::read_network_graph(&logger) {
6753 let params = ProbabilisticScoringFeeParameters::default();
6754 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6755 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6757 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6761 #[cfg(not(feature = "no-std"))]
6762 fn generate_large_mpp_routes() {
6763 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6765 let logger = ln_test_utils::TestLogger::new();
6766 let graph = match super::bench_utils::read_network_graph(&logger) {
6774 let params = ProbabilisticScoringFeeParameters::default();
6775 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6776 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6778 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6782 fn honors_manual_penalties() {
6783 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6784 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6786 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6787 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6789 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6790 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6792 // First check set manual penalties are returned by the scorer.
6793 let usage = ChannelUsage {
6795 inflight_htlc_msat: 0,
6796 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6798 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6799 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6800 let network_graph = network_graph.read_only();
6801 let channels = network_graph.channels();
6802 let channel = channels.get(&5).unwrap();
6803 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
6804 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop {
6806 short_channel_id: 5,
6808 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
6810 // Then check we can get a normal route
6811 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6812 let route_params = RouteParameters::from_payment_params_and_value(
6813 payment_params, 100);
6814 let route = get_route(&our_id, &route_params, &network_graph, None,
6815 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6816 assert!(route.is_ok());
6818 // Then check that we can't get a route if we ban an intermediate node.
6819 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6820 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6821 assert!(route.is_err());
6823 // Finally make sure we can route again, when we remove the ban.
6824 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6825 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6826 assert!(route.is_ok());
6830 fn abide_by_route_hint_max_htlc() {
6831 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6832 // params in the final route.
6833 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6834 let netgraph = network_graph.read_only();
6835 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6836 let scorer = ln_test_utils::TestScorer::new();
6837 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6838 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6839 let config = UserConfig::default();
6841 let max_htlc_msat = 50_000;
6842 let route_hint_1 = RouteHint(vec![RouteHintHop {
6843 src_node_id: nodes[2],
6844 short_channel_id: 42,
6847 proportional_millionths: 0,
6849 cltv_expiry_delta: 10,
6850 htlc_minimum_msat: None,
6851 htlc_maximum_msat: Some(max_htlc_msat),
6853 let dest_node_id = ln_test_utils::pubkey(42);
6854 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6855 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6856 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6859 // Make sure we'll error if our route hints don't have enough liquidity according to their
6860 // htlc_maximum_msat.
6861 let mut route_params = RouteParameters::from_payment_params_and_value(
6862 payment_params, max_htlc_msat + 1);
6863 route_params.max_total_routing_fee_msat = None;
6864 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6865 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6868 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6869 } else { panic!(); }
6871 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6872 let mut route_hint_2 = route_hint_1.clone();
6873 route_hint_2.0[0].short_channel_id = 43;
6874 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6875 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6876 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6878 let mut route_params = RouteParameters::from_payment_params_and_value(
6879 payment_params, max_htlc_msat + 1);
6880 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
6881 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6882 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6883 assert_eq!(route.paths.len(), 2);
6884 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6885 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6889 fn direct_channel_to_hints_with_max_htlc() {
6890 // Check that if we have a first hop channel peer that's connected to multiple provided route
6891 // hints, that we properly split the payment between the route hints if needed.
6892 let logger = Arc::new(ln_test_utils::TestLogger::new());
6893 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6894 let scorer = ln_test_utils::TestScorer::new();
6895 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6896 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6897 let config = UserConfig::default();
6899 let our_node_id = ln_test_utils::pubkey(42);
6900 let intermed_node_id = ln_test_utils::pubkey(43);
6901 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6903 let amt_msat = 900_000;
6904 let max_htlc_msat = 500_000;
6905 let route_hint_1 = RouteHint(vec![RouteHintHop {
6906 src_node_id: intermed_node_id,
6907 short_channel_id: 44,
6910 proportional_millionths: 0,
6912 cltv_expiry_delta: 10,
6913 htlc_minimum_msat: None,
6914 htlc_maximum_msat: Some(max_htlc_msat),
6916 src_node_id: intermed_node_id,
6917 short_channel_id: 45,
6920 proportional_millionths: 0,
6922 cltv_expiry_delta: 10,
6923 htlc_minimum_msat: None,
6924 // Check that later route hint max htlcs don't override earlier ones
6925 htlc_maximum_msat: Some(max_htlc_msat - 50),
6927 let mut route_hint_2 = route_hint_1.clone();
6928 route_hint_2.0[0].short_channel_id = 46;
6929 route_hint_2.0[1].short_channel_id = 47;
6930 let dest_node_id = ln_test_utils::pubkey(44);
6931 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6932 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6933 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6936 let route_params = RouteParameters::from_payment_params_and_value(
6937 payment_params, amt_msat);
6938 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6939 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6940 &Default::default(), &random_seed_bytes).unwrap();
6941 assert_eq!(route.paths.len(), 2);
6942 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6943 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6944 assert_eq!(route.get_total_amount(), amt_msat);
6946 // Re-run but with two first hop channels connected to the same route hint peers that must be
6948 let first_hops = vec![
6949 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6950 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6952 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6953 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6954 &Default::default(), &random_seed_bytes).unwrap();
6955 assert_eq!(route.paths.len(), 2);
6956 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6957 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6958 assert_eq!(route.get_total_amount(), amt_msat);
6960 // Make sure this works for blinded route hints.
6961 let blinded_path = BlindedPath {
6962 introduction_node_id: intermed_node_id,
6963 blinding_point: ln_test_utils::pubkey(42),
6965 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6966 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6969 let blinded_payinfo = BlindedPayInfo {
6971 fee_proportional_millionths: 0,
6972 htlc_minimum_msat: 1,
6973 htlc_maximum_msat: max_htlc_msat,
6974 cltv_expiry_delta: 10,
6975 features: BlindedHopFeatures::empty(),
6977 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
6978 let payment_params = PaymentParameters::blinded(vec![
6979 (blinded_payinfo.clone(), blinded_path.clone()),
6980 (blinded_payinfo.clone(), blinded_path.clone())])
6981 .with_bolt12_features(bolt12_features).unwrap();
6982 let route_params = RouteParameters::from_payment_params_and_value(
6983 payment_params, amt_msat);
6984 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6985 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6986 &Default::default(), &random_seed_bytes).unwrap();
6987 assert_eq!(route.paths.len(), 2);
6988 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6989 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6990 assert_eq!(route.get_total_amount(), amt_msat);
6994 fn blinded_route_ser() {
6995 let blinded_path_1 = BlindedPath {
6996 introduction_node_id: ln_test_utils::pubkey(42),
6997 blinding_point: ln_test_utils::pubkey(43),
6999 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7000 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7003 let blinded_path_2 = BlindedPath {
7004 introduction_node_id: ln_test_utils::pubkey(46),
7005 blinding_point: ln_test_utils::pubkey(47),
7007 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7008 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7011 // (De)serialize a Route with 1 blinded path out of two total paths.
7012 let mut route = Route { paths: vec![Path {
7013 hops: vec![RouteHop {
7014 pubkey: ln_test_utils::pubkey(50),
7015 node_features: NodeFeatures::empty(),
7016 short_channel_id: 42,
7017 channel_features: ChannelFeatures::empty(),
7019 cltv_expiry_delta: 0,
7020 maybe_announced_channel: true,
7022 blinded_tail: Some(BlindedTail {
7023 hops: blinded_path_1.blinded_hops,
7024 blinding_point: blinded_path_1.blinding_point,
7025 excess_final_cltv_expiry_delta: 40,
7026 final_value_msat: 100,
7028 hops: vec![RouteHop {
7029 pubkey: ln_test_utils::pubkey(51),
7030 node_features: NodeFeatures::empty(),
7031 short_channel_id: 43,
7032 channel_features: ChannelFeatures::empty(),
7034 cltv_expiry_delta: 0,
7035 maybe_announced_channel: true,
7036 }], blinded_tail: None }],
7039 let encoded_route = route.encode();
7040 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7041 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7042 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7044 // (De)serialize a Route with two paths, each containing a blinded tail.
7045 route.paths[1].blinded_tail = Some(BlindedTail {
7046 hops: blinded_path_2.blinded_hops,
7047 blinding_point: blinded_path_2.blinding_point,
7048 excess_final_cltv_expiry_delta: 41,
7049 final_value_msat: 101,
7051 let encoded_route = route.encode();
7052 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7053 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7054 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7058 fn blinded_path_inflight_processing() {
7059 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7060 // account for the blinded tail's final amount_msat.
7061 let mut inflight_htlcs = InFlightHtlcs::new();
7062 let blinded_path = BlindedPath {
7063 introduction_node_id: ln_test_utils::pubkey(43),
7064 blinding_point: ln_test_utils::pubkey(48),
7065 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7068 hops: vec![RouteHop {
7069 pubkey: ln_test_utils::pubkey(42),
7070 node_features: NodeFeatures::empty(),
7071 short_channel_id: 42,
7072 channel_features: ChannelFeatures::empty(),
7074 cltv_expiry_delta: 0,
7075 maybe_announced_channel: false,
7078 pubkey: blinded_path.introduction_node_id,
7079 node_features: NodeFeatures::empty(),
7080 short_channel_id: 43,
7081 channel_features: ChannelFeatures::empty(),
7083 cltv_expiry_delta: 0,
7084 maybe_announced_channel: false,
7086 blinded_tail: Some(BlindedTail {
7087 hops: blinded_path.blinded_hops,
7088 blinding_point: blinded_path.blinding_point,
7089 excess_final_cltv_expiry_delta: 0,
7090 final_value_msat: 200,
7093 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7094 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7095 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7099 fn blinded_path_cltv_shadow_offset() {
7100 // Make sure we add a shadow offset when sending to blinded paths.
7101 let blinded_path = BlindedPath {
7102 introduction_node_id: ln_test_utils::pubkey(43),
7103 blinding_point: ln_test_utils::pubkey(44),
7105 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7106 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7109 let mut route = Route { paths: vec![Path {
7110 hops: vec![RouteHop {
7111 pubkey: ln_test_utils::pubkey(42),
7112 node_features: NodeFeatures::empty(),
7113 short_channel_id: 42,
7114 channel_features: ChannelFeatures::empty(),
7116 cltv_expiry_delta: 0,
7117 maybe_announced_channel: false,
7120 pubkey: blinded_path.introduction_node_id,
7121 node_features: NodeFeatures::empty(),
7122 short_channel_id: 43,
7123 channel_features: ChannelFeatures::empty(),
7125 cltv_expiry_delta: 0,
7126 maybe_announced_channel: false,
7129 blinded_tail: Some(BlindedTail {
7130 hops: blinded_path.blinded_hops,
7131 blinding_point: blinded_path.blinding_point,
7132 excess_final_cltv_expiry_delta: 0,
7133 final_value_msat: 200,
7135 }], route_params: None};
7137 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7138 let (_, network_graph, _, _, _) = build_line_graph();
7139 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7140 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7141 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7145 fn simple_blinded_route_hints() {
7146 do_simple_blinded_route_hints(1);
7147 do_simple_blinded_route_hints(2);
7148 do_simple_blinded_route_hints(3);
7151 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7152 // Check that we can generate a route to a blinded path with the expected hops.
7153 let (secp_ctx, network, _, _, logger) = build_graph();
7154 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7155 let network_graph = network.read_only();
7157 let scorer = ln_test_utils::TestScorer::new();
7158 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7159 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7161 let mut blinded_path = BlindedPath {
7162 introduction_node_id: nodes[2],
7163 blinding_point: ln_test_utils::pubkey(42),
7164 blinded_hops: Vec::with_capacity(num_blinded_hops),
7166 for i in 0..num_blinded_hops {
7167 blinded_path.blinded_hops.push(
7168 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7171 let blinded_payinfo = BlindedPayInfo {
7173 fee_proportional_millionths: 500,
7174 htlc_minimum_msat: 1000,
7175 htlc_maximum_msat: 100_000_000,
7176 cltv_expiry_delta: 15,
7177 features: BlindedHopFeatures::empty(),
7180 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7181 let route_params = RouteParameters::from_payment_params_and_value(
7182 payment_params, 1001);
7183 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7184 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7185 assert_eq!(route.paths.len(), 1);
7186 assert_eq!(route.paths[0].hops.len(), 2);
7188 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7189 assert_eq!(tail.hops, blinded_path.blinded_hops);
7190 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7191 assert_eq!(tail.final_value_msat, 1001);
7193 let final_hop = route.paths[0].hops.last().unwrap();
7194 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7195 if tail.hops.len() > 1 {
7196 assert_eq!(final_hop.fee_msat,
7197 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7198 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7200 assert_eq!(final_hop.fee_msat, 0);
7201 assert_eq!(final_hop.cltv_expiry_delta, 0);
7206 fn blinded_path_routing_errors() {
7207 // Check that we can generate a route to a blinded path with the expected hops.
7208 let (secp_ctx, network, _, _, logger) = build_graph();
7209 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7210 let network_graph = network.read_only();
7212 let scorer = ln_test_utils::TestScorer::new();
7213 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7214 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7216 let mut invalid_blinded_path = BlindedPath {
7217 introduction_node_id: nodes[2],
7218 blinding_point: ln_test_utils::pubkey(42),
7220 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7223 let blinded_payinfo = BlindedPayInfo {
7225 fee_proportional_millionths: 500,
7226 htlc_minimum_msat: 1000,
7227 htlc_maximum_msat: 100_000_000,
7228 cltv_expiry_delta: 15,
7229 features: BlindedHopFeatures::empty(),
7232 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7233 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7234 let payment_params = PaymentParameters::blinded(vec![
7235 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7236 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7237 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7238 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7239 &scorer, &Default::default(), &random_seed_bytes)
7241 Err(LightningError { err, .. }) => {
7242 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7244 _ => panic!("Expected error")
7247 invalid_blinded_path.introduction_node_id = our_id;
7248 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7249 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7250 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7251 &Default::default(), &random_seed_bytes)
7253 Err(LightningError { err, .. }) => {
7254 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7256 _ => panic!("Expected error")
7259 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7260 invalid_blinded_path.blinded_hops.clear();
7261 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7262 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7263 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7264 &Default::default(), &random_seed_bytes)
7266 Err(LightningError { err, .. }) => {
7267 assert_eq!(err, "0-hop blinded path provided");
7269 _ => panic!("Expected error")
7274 fn matching_intro_node_paths_provided() {
7275 // Check that if multiple blinded paths with the same intro node are provided in payment
7276 // parameters, we'll return the correct paths in the resulting MPP route.
7277 let (secp_ctx, network, _, _, logger) = build_graph();
7278 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7279 let network_graph = network.read_only();
7281 let scorer = ln_test_utils::TestScorer::new();
7282 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7283 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7284 let config = UserConfig::default();
7286 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7287 let blinded_path_1 = BlindedPath {
7288 introduction_node_id: nodes[2],
7289 blinding_point: ln_test_utils::pubkey(42),
7291 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7292 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7295 let blinded_payinfo_1 = BlindedPayInfo {
7297 fee_proportional_millionths: 0,
7298 htlc_minimum_msat: 0,
7299 htlc_maximum_msat: 30_000,
7300 cltv_expiry_delta: 0,
7301 features: BlindedHopFeatures::empty(),
7304 let mut blinded_path_2 = blinded_path_1.clone();
7305 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7306 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7307 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7309 let blinded_hints = vec![
7310 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7311 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7313 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7314 .with_bolt12_features(bolt12_features).unwrap();
7316 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7317 route_params.max_total_routing_fee_msat = Some(100_000);
7318 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7319 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7320 assert_eq!(route.paths.len(), 2);
7321 let mut total_amount_paid_msat = 0;
7322 for path in route.paths.into_iter() {
7323 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7324 if let Some(bt) = &path.blinded_tail {
7325 assert_eq!(bt.blinding_point,
7326 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7327 .map(|(_, bp)| bp.blinding_point).unwrap());
7328 } else { panic!(); }
7329 total_amount_paid_msat += path.final_value_msat();
7331 assert_eq!(total_amount_paid_msat, 100_000);
7335 fn direct_to_intro_node() {
7336 // This previously caused a debug panic in the router when asserting
7337 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7338 // direct channels we failed to account for the fee charged for use of the blinded path.
7341 // node0 -1(1)2 - node1
7342 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7343 // doesn't account for the blinded path fee.
7345 let secp_ctx = Secp256k1::new();
7346 let logger = Arc::new(ln_test_utils::TestLogger::new());
7347 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7348 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7349 let scorer = ln_test_utils::TestScorer::new();
7350 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7351 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7353 let amt_msat = 10_000_000;
7354 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7355 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7356 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7357 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7358 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7359 short_channel_id: 1,
7362 cltv_expiry_delta: 42,
7363 htlc_minimum_msat: 1_000,
7364 htlc_maximum_msat: 10_000_000,
7366 fee_proportional_millionths: 0,
7367 excess_data: Vec::new()
7369 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7370 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7371 short_channel_id: 1,
7374 cltv_expiry_delta: 42,
7375 htlc_minimum_msat: 1_000,
7376 htlc_maximum_msat: 10_000_000,
7378 fee_proportional_millionths: 0,
7379 excess_data: Vec::new()
7381 let first_hops = vec![
7382 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7384 let blinded_path = BlindedPath {
7385 introduction_node_id: nodes[1],
7386 blinding_point: ln_test_utils::pubkey(42),
7388 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7389 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7392 let blinded_payinfo = BlindedPayInfo {
7393 fee_base_msat: 1000,
7394 fee_proportional_millionths: 0,
7395 htlc_minimum_msat: 1000,
7396 htlc_maximum_msat: MAX_VALUE_MSAT,
7397 cltv_expiry_delta: 0,
7398 features: BlindedHopFeatures::empty(),
7400 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7402 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7404 let netgraph = network_graph.read_only();
7405 let route_params = RouteParameters::from_payment_params_and_value(
7406 payment_params.clone(), amt_msat);
7407 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7408 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7409 &Default::default(), &random_seed_bytes) {
7410 assert_eq!(err, "Failed to find a path to the given destination");
7411 } else { panic!("Expected error") }
7413 // Sending an exact amount accounting for the blinded path fee works.
7414 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7415 let route_params = RouteParameters::from_payment_params_and_value(
7416 payment_params, amt_minus_blinded_path_fee);
7417 let route = get_route(&nodes[0], &route_params, &netgraph,
7418 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7419 &Default::default(), &random_seed_bytes).unwrap();
7420 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7421 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7425 fn direct_to_matching_intro_nodes() {
7426 // This previously caused us to enter `unreachable` code in the following situation:
7427 // 1. We add a route candidate for intro_node contributing a high amount
7428 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7429 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7430 // amount, and update our route candidate for intro_node for the lower amount
7431 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7432 // lower contribution amount, but fail (this was previously caused by failure to account for
7433 // blinded path fees when adding first_hop<>intro_node candidates)
7434 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7435 // candidate still thinks its path is contributing the original higher amount. This caused us
7436 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7438 let secp_ctx = Secp256k1::new();
7439 let logger = Arc::new(ln_test_utils::TestLogger::new());
7440 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7441 let scorer = ln_test_utils::TestScorer::new();
7442 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7443 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7444 let config = UserConfig::default();
7446 // Values are taken from the fuzz input that uncovered this panic.
7447 let amt_msat = 21_7020_5185_1403_2640;
7448 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7449 let first_hops = vec![
7450 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7451 18446744073709551615)];
7453 let blinded_path = BlindedPath {
7454 introduction_node_id: nodes[1],
7455 blinding_point: ln_test_utils::pubkey(42),
7457 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7458 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7461 let blinded_payinfo = BlindedPayInfo {
7462 fee_base_msat: 5046_2720,
7463 fee_proportional_millionths: 0,
7464 htlc_minimum_msat: 4503_5996_2737_0496,
7465 htlc_maximum_msat: 45_0359_9627_3704_9600,
7466 cltv_expiry_delta: 0,
7467 features: BlindedHopFeatures::empty(),
7469 let mut blinded_hints = vec![
7470 (blinded_payinfo.clone(), blinded_path.clone()),
7471 (blinded_payinfo.clone(), blinded_path.clone()),
7473 blinded_hints[1].0.fee_base_msat = 419_4304;
7474 blinded_hints[1].0.fee_proportional_millionths = 257;
7475 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7476 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7477 blinded_hints[1].0.cltv_expiry_delta = 0;
7479 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7480 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7481 .with_bolt12_features(bolt12_features).unwrap();
7483 let netgraph = network_graph.read_only();
7484 let route_params = RouteParameters::from_payment_params_and_value(
7485 payment_params, amt_msat);
7486 let route = get_route(&nodes[0], &route_params, &netgraph,
7487 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7488 &Default::default(), &random_seed_bytes).unwrap();
7489 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7490 assert_eq!(route.get_total_amount(), amt_msat);
7494 fn we_are_intro_node_candidate_hops() {
7495 // This previously led to a panic in the router because we'd generate a Path with only a
7496 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7497 // where the origin node is the intro node. We now fully disallow considering candidate hops
7498 // where the origin node is the intro node.
7499 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7500 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7501 let scorer = ln_test_utils::TestScorer::new();
7502 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7503 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7504 let config = UserConfig::default();
7506 // Values are taken from the fuzz input that uncovered this panic.
7507 let amt_msat = 21_7020_5185_1423_0019;
7509 let blinded_path = BlindedPath {
7510 introduction_node_id: our_id,
7511 blinding_point: ln_test_utils::pubkey(42),
7513 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7514 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7517 let blinded_payinfo = BlindedPayInfo {
7518 fee_base_msat: 5052_9027,
7519 fee_proportional_millionths: 0,
7520 htlc_minimum_msat: 21_7020_5185_1423_0019,
7521 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7522 cltv_expiry_delta: 0,
7523 features: BlindedHopFeatures::empty(),
7525 let mut blinded_hints = vec![
7526 (blinded_payinfo.clone(), blinded_path.clone()),
7527 (blinded_payinfo.clone(), blinded_path.clone()),
7529 blinded_hints[1].1.introduction_node_id = nodes[6];
7531 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7532 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7533 .with_bolt12_features(bolt12_features.clone()).unwrap();
7535 let netgraph = network_graph.read_only();
7536 let route_params = RouteParameters::from_payment_params_and_value(
7537 payment_params, amt_msat);
7538 if let Err(LightningError { err, .. }) = get_route(
7539 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7541 assert_eq!(err, "Failed to find a path to the given destination");
7546 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7547 // This previously led to a debug panic in the router because we'd find an invalid Path with
7548 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7549 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7550 // the payment, when it was intended to only include the final value of the payment.
7551 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7552 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7553 let scorer = ln_test_utils::TestScorer::new();
7554 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7555 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7556 let config = UserConfig::default();
7558 // Values are taken from the fuzz input that uncovered this panic.
7559 let amt_msat = 21_7020_5185_1423_0019;
7561 let blinded_path = BlindedPath {
7562 introduction_node_id: our_id,
7563 blinding_point: ln_test_utils::pubkey(42),
7565 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7566 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7569 let blinded_payinfo = BlindedPayInfo {
7570 fee_base_msat: 10_4425_1395,
7571 fee_proportional_millionths: 0,
7572 htlc_minimum_msat: 21_7301_9934_9094_0931,
7573 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7574 cltv_expiry_delta: 0,
7575 features: BlindedHopFeatures::empty(),
7577 let mut blinded_hints = vec![
7578 (blinded_payinfo.clone(), blinded_path.clone()),
7579 (blinded_payinfo.clone(), blinded_path.clone()),
7580 (blinded_payinfo.clone(), blinded_path.clone()),
7582 blinded_hints[1].0.fee_base_msat = 5052_9027;
7583 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7584 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7586 blinded_hints[2].1.introduction_node_id = nodes[6];
7588 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7589 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7590 .with_bolt12_features(bolt12_features.clone()).unwrap();
7592 let netgraph = network_graph.read_only();
7593 let route_params = RouteParameters::from_payment_params_and_value(
7594 payment_params, amt_msat);
7595 if let Err(LightningError { err, .. }) = get_route(
7596 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7598 assert_eq!(err, "Failed to find a path to the given destination");
7603 fn min_htlc_overpay_violates_max_htlc() {
7604 do_min_htlc_overpay_violates_max_htlc(true);
7605 do_min_htlc_overpay_violates_max_htlc(false);
7607 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7608 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7609 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7610 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7611 // that the used liquidity for a hop was less than its available liquidity limit.
7612 let secp_ctx = Secp256k1::new();
7613 let logger = Arc::new(ln_test_utils::TestLogger::new());
7614 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7615 let scorer = ln_test_utils::TestScorer::new();
7616 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7617 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7618 let config = UserConfig::default();
7620 // Values are taken from the fuzz input that uncovered this panic.
7621 let amt_msat = 7_4009_8048;
7622 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7623 let first_hop_outbound_capacity = 2_7345_2000;
7624 let first_hops = vec![get_channel_details(
7625 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7626 first_hop_outbound_capacity
7629 let base_fee = 1_6778_3453;
7630 let htlc_min = 2_5165_8240;
7631 let payment_params = if blinded_payee {
7632 let blinded_path = BlindedPath {
7633 introduction_node_id: nodes[0],
7634 blinding_point: ln_test_utils::pubkey(42),
7636 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7637 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7640 let blinded_payinfo = BlindedPayInfo {
7641 fee_base_msat: base_fee,
7642 fee_proportional_millionths: 0,
7643 htlc_minimum_msat: htlc_min,
7644 htlc_maximum_msat: htlc_min * 1000,
7645 cltv_expiry_delta: 0,
7646 features: BlindedHopFeatures::empty(),
7648 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7649 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7650 .with_bolt12_features(bolt12_features.clone()).unwrap()
7652 let route_hint = RouteHint(vec![RouteHintHop {
7653 src_node_id: nodes[0],
7654 short_channel_id: 42,
7656 base_msat: base_fee,
7657 proportional_millionths: 0,
7659 cltv_expiry_delta: 10,
7660 htlc_minimum_msat: Some(htlc_min),
7661 htlc_maximum_msat: None,
7664 PaymentParameters::from_node_id(nodes[1], 42)
7665 .with_route_hints(vec![route_hint]).unwrap()
7666 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7669 let netgraph = network_graph.read_only();
7670 let route_params = RouteParameters::from_payment_params_and_value(
7671 payment_params, amt_msat);
7672 if let Err(LightningError { err, .. }) = get_route(
7673 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7674 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7676 assert_eq!(err, "Failed to find a path to the given destination");
7681 fn previously_used_liquidity_violates_max_htlc() {
7682 do_previously_used_liquidity_violates_max_htlc(true);
7683 do_previously_used_liquidity_violates_max_htlc(false);
7686 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7687 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7688 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7689 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7690 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7691 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7692 let secp_ctx = Secp256k1::new();
7693 let logger = Arc::new(ln_test_utils::TestLogger::new());
7694 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7695 let scorer = ln_test_utils::TestScorer::new();
7696 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7697 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7698 let config = UserConfig::default();
7700 // Values are taken from the fuzz input that uncovered this panic.
7701 let amt_msat = 52_4288;
7702 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7703 let first_hops = vec![get_channel_details(
7704 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7705 ), get_channel_details(
7706 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7709 let base_fees = [0, 425_9840, 0, 0];
7710 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7711 let payment_params = if blinded_payee {
7712 let blinded_path = BlindedPath {
7713 introduction_node_id: nodes[0],
7714 blinding_point: ln_test_utils::pubkey(42),
7716 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7717 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7720 let mut blinded_hints = Vec::new();
7721 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7722 blinded_hints.push((BlindedPayInfo {
7723 fee_base_msat: *base_fee,
7724 fee_proportional_millionths: 0,
7725 htlc_minimum_msat: *htlc_min,
7726 htlc_maximum_msat: htlc_min * 100,
7727 cltv_expiry_delta: 10,
7728 features: BlindedHopFeatures::empty(),
7729 }, blinded_path.clone()));
7731 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7732 PaymentParameters::blinded(blinded_hints.clone())
7733 .with_bolt12_features(bolt12_features.clone()).unwrap()
7735 let mut route_hints = Vec::new();
7736 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7737 route_hints.push(RouteHint(vec![RouteHintHop {
7738 src_node_id: nodes[0],
7739 short_channel_id: 42 + idx as u64,
7741 base_msat: *base_fee,
7742 proportional_millionths: 0,
7744 cltv_expiry_delta: 10,
7745 htlc_minimum_msat: Some(*htlc_min),
7746 htlc_maximum_msat: Some(htlc_min * 100),
7749 PaymentParameters::from_node_id(nodes[1], 42)
7750 .with_route_hints(route_hints).unwrap()
7751 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7754 let netgraph = network_graph.read_only();
7755 let route_params = RouteParameters::from_payment_params_and_value(
7756 payment_params, amt_msat);
7758 let route = get_route(
7759 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7760 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7762 assert_eq!(route.paths.len(), 1);
7763 assert_eq!(route.get_total_amount(), amt_msat);
7767 fn candidate_path_min() {
7768 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7769 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7770 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7771 // would add a connecting first_hop node that did not have enough contribution amount, leading
7772 // to a debug panic upon invalid path construction.
7773 let secp_ctx = Secp256k1::new();
7774 let logger = Arc::new(ln_test_utils::TestLogger::new());
7775 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7776 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7777 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7778 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7779 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7780 let config = UserConfig::default();
7782 // Values are taken from the fuzz input that uncovered this panic.
7783 let amt_msat = 7_4009_8048;
7784 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7785 let first_hops = vec![get_channel_details(
7786 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7789 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7790 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7791 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7792 short_channel_id: 6,
7795 cltv_expiry_delta: (6 << 4) | 0,
7796 htlc_minimum_msat: 0,
7797 htlc_maximum_msat: MAX_VALUE_MSAT,
7799 fee_proportional_millionths: 0,
7800 excess_data: Vec::new()
7802 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
7804 let htlc_min = 2_5165_8240;
7805 let blinded_hints = vec![
7807 fee_base_msat: 1_6778_3453,
7808 fee_proportional_millionths: 0,
7809 htlc_minimum_msat: htlc_min,
7810 htlc_maximum_msat: htlc_min * 100,
7811 cltv_expiry_delta: 10,
7812 features: BlindedHopFeatures::empty(),
7814 introduction_node_id: nodes[0],
7815 blinding_point: ln_test_utils::pubkey(42),
7817 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7818 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7822 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7823 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7824 .with_bolt12_features(bolt12_features.clone()).unwrap();
7825 let route_params = RouteParameters::from_payment_params_and_value(
7826 payment_params, amt_msat);
7827 let netgraph = network_graph.read_only();
7829 if let Err(LightningError { err, .. }) = get_route(
7830 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7831 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7834 assert_eq!(err, "Failed to find a path to the given destination");
7839 fn path_contribution_includes_min_htlc_overpay() {
7840 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
7841 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
7842 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
7843 // selection, both tested here.
7844 let secp_ctx = Secp256k1::new();
7845 let logger = Arc::new(ln_test_utils::TestLogger::new());
7846 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7847 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7848 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7849 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7850 let config = UserConfig::default();
7852 // Values are taken from the fuzz input that uncovered this panic.
7853 let amt_msat = 562_0000;
7854 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7855 let first_hops = vec![
7856 get_channel_details(
7857 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
7861 let htlc_mins = [49_0000, 1125_0000];
7862 let payment_params = {
7863 let blinded_path = BlindedPath {
7864 introduction_node_id: nodes[0],
7865 blinding_point: ln_test_utils::pubkey(42),
7867 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7868 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7871 let mut blinded_hints = Vec::new();
7872 for htlc_min in htlc_mins.iter() {
7873 blinded_hints.push((BlindedPayInfo {
7875 fee_proportional_millionths: 0,
7876 htlc_minimum_msat: *htlc_min,
7877 htlc_maximum_msat: *htlc_min * 100,
7878 cltv_expiry_delta: 10,
7879 features: BlindedHopFeatures::empty(),
7880 }, blinded_path.clone()));
7882 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7883 PaymentParameters::blinded(blinded_hints.clone())
7884 .with_bolt12_features(bolt12_features.clone()).unwrap()
7887 let netgraph = network_graph.read_only();
7888 let route_params = RouteParameters::from_payment_params_and_value(
7889 payment_params, amt_msat);
7890 let route = get_route(
7891 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7892 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7895 assert_eq!(route.paths.len(), 1);
7896 assert_eq!(route.get_total_amount(), amt_msat);
7900 fn first_hop_preferred_over_hint() {
7901 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
7902 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
7903 let secp_ctx = Secp256k1::new();
7904 let logger = Arc::new(ln_test_utils::TestLogger::new());
7905 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7906 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7907 let scorer = ln_test_utils::TestScorer::new();
7908 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7909 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7910 let config = UserConfig::default();
7912 let amt_msat = 1_000_000;
7913 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
7915 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
7916 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7917 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
7918 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7919 short_channel_id: 1,
7922 cltv_expiry_delta: 42,
7923 htlc_minimum_msat: 1_000,
7924 htlc_maximum_msat: 10_000_000,
7926 fee_proportional_millionths: 0,
7927 excess_data: Vec::new()
7929 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7930 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7931 short_channel_id: 1,
7934 cltv_expiry_delta: 42,
7935 htlc_minimum_msat: 1_000,
7936 htlc_maximum_msat: 10_000_000,
7938 fee_proportional_millionths: 0,
7939 excess_data: Vec::new()
7942 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7943 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
7944 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7945 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7946 short_channel_id: 2,
7949 cltv_expiry_delta: 42,
7950 htlc_minimum_msat: 1_000,
7951 htlc_maximum_msat: 10_000_000,
7953 fee_proportional_millionths: 0,
7954 excess_data: Vec::new()
7956 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7957 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7958 short_channel_id: 2,
7961 cltv_expiry_delta: 42,
7962 htlc_minimum_msat: 1_000,
7963 htlc_maximum_msat: 10_000_000,
7965 fee_proportional_millionths: 0,
7966 excess_data: Vec::new()
7969 let dest_node_id = nodes[2];
7971 let route_hint = RouteHint(vec![RouteHintHop {
7972 src_node_id: our_node_id,
7973 short_channel_id: 44,
7976 proportional_millionths: 0,
7978 cltv_expiry_delta: 10,
7979 htlc_minimum_msat: None,
7980 htlc_maximum_msat: Some(5_000_000),
7983 src_node_id: nodes[0],
7984 short_channel_id: 45,
7987 proportional_millionths: 0,
7989 cltv_expiry_delta: 10,
7990 htlc_minimum_msat: None,
7991 htlc_maximum_msat: None,
7994 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7995 .with_route_hints(vec![route_hint]).unwrap()
7996 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
7997 let route_params = RouteParameters::from_payment_params_and_value(
7998 payment_params, amt_msat);
8000 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8002 let first_hop = get_channel_details(Some(1), nodes[0],
8003 channelmanager::provided_init_features(&config), 999_999);
8004 let first_hops = vec![first_hop];
8006 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8007 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8008 &Default::default(), &random_seed_bytes).unwrap();
8009 assert_eq!(route.paths.len(), 1);
8010 assert_eq!(route.get_total_amount(), amt_msat);
8011 assert_eq!(route.paths[0].hops.len(), 2);
8012 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8013 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8014 assert_eq!(route.get_total_fees(), 123);
8016 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8017 // for a first hop channel.
8018 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8019 first_hop.outbound_scid_alias = Some(44);
8020 let first_hops = vec![first_hop];
8022 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8023 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8024 &Default::default(), &random_seed_bytes);
8025 assert!(route_res.is_err());
8027 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8028 // use the cheaper second hop of the route hint.
8029 let mut first_hop = get_channel_details(Some(1), nodes[0],
8030 channelmanager::provided_init_features(&config), 10_000_000);
8031 first_hop.outbound_scid_alias = Some(44);
8032 let first_hops = vec![first_hop];
8034 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8035 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8036 &Default::default(), &random_seed_bytes).unwrap();
8037 assert_eq!(route.paths.len(), 1);
8038 assert_eq!(route.get_total_amount(), amt_msat);
8039 assert_eq!(route.paths[0].hops.len(), 2);
8040 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8041 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8042 assert_eq!(route.get_total_fees(), 123);
8046 fn allow_us_being_first_hint() {
8047 // Check that we consider a route hint even if we are the src of the first hop.
8048 let secp_ctx = Secp256k1::new();
8049 let logger = Arc::new(ln_test_utils::TestLogger::new());
8050 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8051 let scorer = ln_test_utils::TestScorer::new();
8052 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8053 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8054 let config = UserConfig::default();
8056 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8058 let amt_msat = 1_000_000;
8059 let dest_node_id = nodes[1];
8061 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8062 let first_hops = vec![first_hop];
8064 let route_hint = RouteHint(vec![RouteHintHop {
8065 src_node_id: our_node_id,
8066 short_channel_id: 44,
8069 proportional_millionths: 0,
8071 cltv_expiry_delta: 10,
8072 htlc_minimum_msat: None,
8073 htlc_maximum_msat: None,
8076 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8077 .with_route_hints(vec![route_hint]).unwrap()
8078 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8080 let route_params = RouteParameters::from_payment_params_and_value(
8081 payment_params, amt_msat);
8084 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8085 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8086 &Default::default(), &random_seed_bytes).unwrap();
8088 assert_eq!(route.paths.len(), 1);
8089 assert_eq!(route.get_total_amount(), amt_msat);
8090 assert_eq!(route.get_total_fees(), 0);
8091 assert_eq!(route.paths[0].hops.len(), 1);
8093 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8097 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8098 pub(crate) mod bench_utils {
8102 use bitcoin::hashes::Hash;
8103 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8105 use crate::chain::transaction::OutPoint;
8106 use crate::routing::scoring::ScoreUpdate;
8107 use crate::sign::{EntropySource, KeysManager};
8108 use crate::ln::ChannelId;
8109 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8110 use crate::ln::features::Bolt11InvoiceFeatures;
8111 use crate::routing::gossip::NetworkGraph;
8112 use crate::util::config::UserConfig;
8113 use crate::util::ser::ReadableArgs;
8114 use crate::util::test_utils::TestLogger;
8116 /// Tries to open a network graph file, or panics with a URL to fetch it.
8117 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8118 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8119 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8120 .or_else(|_| { // Fall back to guessing based on the binary location
8121 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8122 let mut path = std::env::current_exe().unwrap();
8123 path.pop(); // lightning-...
8125 path.pop(); // debug
8126 path.pop(); // target
8127 path.push("lightning");
8128 path.push("net_graph-2023-01-18.bin");
8131 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8132 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8133 let mut path = std::env::current_exe().unwrap();
8134 path.pop(); // bench...
8136 path.pop(); // debug
8137 path.pop(); // target
8138 path.pop(); // bench
8139 path.push("lightning");
8140 path.push("net_graph-2023-01-18.bin");
8143 .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");
8144 #[cfg(require_route_graph_test)]
8145 return Ok(res.unwrap());
8146 #[cfg(not(require_route_graph_test))]
8150 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8151 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8154 pub(crate) fn payer_pubkey() -> PublicKey {
8155 let secp_ctx = Secp256k1::new();
8156 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8160 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8162 channel_id: ChannelId::new_zero(),
8163 counterparty: ChannelCounterparty {
8164 features: channelmanager::provided_init_features(&UserConfig::default()),
8166 unspendable_punishment_reserve: 0,
8167 forwarding_info: None,
8168 outbound_htlc_minimum_msat: None,
8169 outbound_htlc_maximum_msat: None,
8171 funding_txo: Some(OutPoint {
8172 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8175 short_channel_id: Some(1),
8176 inbound_scid_alias: None,
8177 outbound_scid_alias: None,
8178 channel_value_satoshis: 10_000_000_000,
8180 balance_msat: 10_000_000_000,
8181 outbound_capacity_msat: 10_000_000_000,
8182 next_outbound_htlc_minimum_msat: 0,
8183 next_outbound_htlc_limit_msat: 10_000_000_000,
8184 inbound_capacity_msat: 0,
8185 unspendable_punishment_reserve: None,
8186 confirmations_required: None,
8187 confirmations: None,
8188 force_close_spend_delay: None,
8190 is_channel_ready: true,
8193 inbound_htlc_minimum_msat: None,
8194 inbound_htlc_maximum_msat: None,
8196 feerate_sat_per_1000_weight: None,
8197 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8201 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8202 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8203 starting_amount: u64, route_count: usize,
8204 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8205 let payer = payer_pubkey();
8206 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8207 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8209 let nodes = graph.read_only().nodes().clone();
8210 let mut route_endpoints = Vec::new();
8211 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8212 // with some routes we picked being un-routable.
8213 for _ in 0..route_count * 3 / 2 {
8215 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8216 let src = PublicKey::from_slice(nodes.unordered_keys()
8217 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8218 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8219 let dst = PublicKey::from_slice(nodes.unordered_keys()
8220 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8221 let params = PaymentParameters::from_node_id(dst, 42)
8222 .with_bolt11_features(features.clone()).unwrap();
8223 let first_hop = first_hop(src);
8224 let amt_msat = starting_amount + seed % 1_000_000;
8225 let route_params = RouteParameters::from_payment_params_and_value(
8226 params.clone(), amt_msat);
8228 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8229 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8231 // ...and seed the scorer with success and failure data...
8232 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8233 let mut score_amt = seed % 1_000_000_000;
8235 // Generate fail/success paths for a wider range of potential amounts with
8236 // MPP enabled to give us a chance to apply penalties for more potential
8238 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8239 let params = PaymentParameters::from_node_id(dst, 42)
8240 .with_bolt11_features(mpp_features).unwrap();
8241 let route_params = RouteParameters::from_payment_params_and_value(
8242 params.clone(), score_amt);
8243 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8244 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8245 &random_seed_bytes);
8246 if let Ok(route) = route_res {
8247 for path in route.paths {
8248 if seed & 0x80 == 0 {
8249 scorer.payment_path_successful(&path);
8251 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8252 scorer.payment_path_failed(&path, short_channel_id);
8254 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8258 // If we couldn't find a path with a higer amount, reduce and try again.
8262 route_endpoints.push((first_hop, params, amt_msat));
8268 // Because we've changed channel scores, it's possible we'll take different routes to the
8269 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8270 // requires a too-high CLTV delta.
8271 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8272 let route_params = RouteParameters::from_payment_params_and_value(
8273 params.clone(), *amt_msat);
8274 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8275 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8277 route_endpoints.truncate(route_count);
8278 assert_eq!(route_endpoints.len(), route_count);
8286 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8287 use crate::sign::{EntropySource, KeysManager};
8288 use crate::ln::channelmanager;
8289 use crate::ln::features::Bolt11InvoiceFeatures;
8290 use crate::routing::gossip::NetworkGraph;
8291 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8292 use crate::util::config::UserConfig;
8293 use crate::util::logger::{Logger, Record};
8294 use crate::util::test_utils::TestLogger;
8296 use criterion::Criterion;
8298 struct DummyLogger {}
8299 impl Logger for DummyLogger {
8300 fn log(&self, _record: Record) {}
8303 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8304 let logger = TestLogger::new();
8305 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8306 let scorer = FixedPenaltyScorer::with_penalty(0);
8307 generate_routes(bench, &network_graph, scorer, &Default::default(),
8308 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8311 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8312 let logger = TestLogger::new();
8313 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8314 let scorer = FixedPenaltyScorer::with_penalty(0);
8315 generate_routes(bench, &network_graph, scorer, &Default::default(),
8316 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8317 "generate_mpp_routes_with_zero_penalty_scorer");
8320 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8321 let logger = TestLogger::new();
8322 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8323 let params = ProbabilisticScoringFeeParameters::default();
8324 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8325 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8326 "generate_routes_with_probabilistic_scorer");
8329 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8330 let logger = TestLogger::new();
8331 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8332 let params = ProbabilisticScoringFeeParameters::default();
8333 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8334 generate_routes(bench, &network_graph, scorer, ¶ms,
8335 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8336 "generate_mpp_routes_with_probabilistic_scorer");
8339 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8340 let logger = TestLogger::new();
8341 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8342 let params = ProbabilisticScoringFeeParameters::default();
8343 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8344 generate_routes(bench, &network_graph, scorer, ¶ms,
8345 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8346 "generate_large_mpp_routes_with_probabilistic_scorer");
8349 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8350 let logger = TestLogger::new();
8351 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8352 let mut params = ProbabilisticScoringFeeParameters::default();
8353 params.linear_success_probability = false;
8354 let scorer = ProbabilisticScorer::new(
8355 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8356 generate_routes(bench, &network_graph, scorer, ¶ms,
8357 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8358 "generate_routes_with_nonlinear_probabilistic_scorer");
8361 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8362 let logger = TestLogger::new();
8363 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8364 let mut params = ProbabilisticScoringFeeParameters::default();
8365 params.linear_success_probability = false;
8366 let scorer = ProbabilisticScorer::new(
8367 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8368 generate_routes(bench, &network_graph, scorer, ¶ms,
8369 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8370 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8373 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8374 let logger = TestLogger::new();
8375 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8376 let mut params = ProbabilisticScoringFeeParameters::default();
8377 params.linear_success_probability = false;
8378 let scorer = ProbabilisticScorer::new(
8379 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8380 generate_routes(bench, &network_graph, scorer, ¶ms,
8381 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8382 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8385 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8386 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8387 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8388 bench_name: &'static str,
8390 let payer = bench_utils::payer_pubkey();
8391 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8392 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8394 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8395 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8397 // ...then benchmark finding paths between the nodes we learned.
8399 bench.bench_function(bench_name, |b| b.iter(|| {
8400 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8401 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8402 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8403 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());