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.
941 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
942 pub struct RouteHintHop {
943 /// The node_id of the non-target end of the route
944 pub src_node_id: PublicKey,
945 /// The short_channel_id of this channel
946 pub short_channel_id: u64,
947 /// The fees which must be paid to use this channel
948 pub fees: RoutingFees,
949 /// The difference in CLTV values between this node and the next node.
950 pub cltv_expiry_delta: u16,
951 /// The minimum value, in msat, which must be relayed to the next hop.
952 pub htlc_minimum_msat: Option<u64>,
953 /// The maximum value in msat available for routing with a single HTLC.
954 pub htlc_maximum_msat: Option<u64>,
957 impl_writeable_tlv_based!(RouteHintHop, {
958 (0, src_node_id, required),
959 (1, htlc_minimum_msat, option),
960 (2, short_channel_id, required),
961 (3, htlc_maximum_msat, option),
963 (6, cltv_expiry_delta, required),
966 #[derive(Eq, PartialEq)]
967 struct RouteGraphNode {
969 lowest_fee_to_node: u64,
970 total_cltv_delta: u32,
971 // The maximum value a yet-to-be-constructed payment path might flow through this node.
972 // This value is upper-bounded by us by:
973 // - how much is needed for a path being constructed
974 // - how much value can channels following this node (up to the destination) can contribute,
975 // considering their capacity and fees
976 value_contribution_msat: u64,
977 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
978 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
979 path_htlc_minimum_msat: u64,
980 /// All penalties incurred from this hop on the way to the destination, as calculated using
982 path_penalty_msat: u64,
983 /// The number of hops walked up to this node.
984 path_length_to_node: u8,
987 impl cmp::Ord for RouteGraphNode {
988 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
989 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
990 .saturating_add(other.path_penalty_msat);
991 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
992 .saturating_add(self.path_penalty_msat);
993 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
997 impl cmp::PartialOrd for RouteGraphNode {
998 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
999 Some(self.cmp(other))
1003 /// A wrapper around the various hop representations.
1005 /// Can be used to examine the properties of a hop,
1006 /// potentially to decide whether to include it in a route.
1007 #[derive(Clone, Debug)]
1008 pub enum CandidateRouteHop<'a> {
1009 /// A hop from the payer, where the outbound liquidity is known.
1011 /// Channel details of the first hop
1012 /// [`ChannelDetails::get_outbound_payment_scid`] is assumed
1013 /// to always return `Some(scid)`
1014 /// this assumption is checked in [`find_route`] method.
1015 details: &'a ChannelDetails,
1016 /// The node id of the payer.
1018 /// Can be accessed via `source` method.
1021 /// A hop found in the [`ReadOnlyNetworkGraph`],
1022 /// where the channel capacity may be unknown.
1024 /// channel info of the hop.
1025 info: DirectedChannelInfo<'a>,
1026 /// short_channel_id of the channel.
1027 short_channel_id: u64,
1029 /// A hop to the payee found in the BOLT 11 payment invoice,
1030 /// though not necessarily a direct
1033 /// Hint provides information about a private hop,
1034 /// needed while routing through a private
1036 hint: &'a RouteHintHop,
1037 /// Node id of the next hop in route.
1038 target_node_id: NodeId
1040 /// The payee's identity is concealed behind
1041 /// blinded paths provided in a BOLT 12 invoice.
1043 /// Hint provides information about a blinded hop,
1044 /// needed while routing through a blinded path.
1045 /// `BlindedPayInfo` provides information needed about the
1046 /// payment while routing through a blinded path.
1047 /// `BlindedPath` is the blinded path to the destination.
1048 hint: &'a (BlindedPayInfo, BlindedPath),
1049 /// Index of the hint in the original list of blinded hints.
1050 /// Provided to uniquely identify a hop as we are
1054 /// Similar to [`Self::Blinded`], but the path here
1055 /// has 1 blinded hop. `BlindedPayInfo` provided
1056 /// for 1-hop blinded paths is ignored
1057 /// because it is meant to apply to the hops *between* the
1058 /// introduction node and the destination.
1059 /// Useful for tracking that we need to include a blinded
1060 /// path at the end of our [`Route`].
1062 /// Hint provides information about a single blinded hop,
1063 /// needed while routing through a one hop blinded path.
1064 /// `BlindedPayInfo` is ignored here.
1065 /// `BlindedPath` is the blinded path to the destination.
1066 hint: &'a (BlindedPayInfo, BlindedPath),
1067 /// Index of the hint in the original list of blinded hints.
1068 /// Provided to uniquely identify a hop as we are route building.
1073 impl<'a> CandidateRouteHop<'a> {
1074 /// Returns short_channel_id if known.
1075 /// For `FirstHop` we assume [`ChannelDetails::get_outbound_payment_scid`] is always set, this assumption is checked in
1076 /// [`find_route`] method.
1077 /// For `Blinded` and `OneHopBlinded` we return `None` because next hop is not known.
1078 pub fn short_channel_id(&self) -> Option<u64> {
1080 CandidateRouteHop::FirstHop { details, .. } => details.get_outbound_payment_scid(),
1081 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1082 CandidateRouteHop::PrivateHop { hint, .. } => Some(hint.short_channel_id),
1083 CandidateRouteHop::Blinded { .. } => None,
1084 CandidateRouteHop::OneHopBlinded { .. } => None,
1088 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1089 fn features(&self) -> ChannelFeatures {
1091 CandidateRouteHop::FirstHop { details, .. } => details.counterparty.features.to_context(),
1092 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1093 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1094 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1095 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1099 /// Returns cltv_expiry_delta for this hop.
1100 pub fn cltv_expiry_delta(&self) -> u32 {
1102 CandidateRouteHop::FirstHop { .. } => 0,
1103 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1104 CandidateRouteHop::PrivateHop { hint, .. } => hint.cltv_expiry_delta as u32,
1105 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1106 CandidateRouteHop::OneHopBlinded { .. } => 0,
1110 /// Returns the htlc_minimum_msat for this hop.
1111 pub fn htlc_minimum_msat(&self) -> u64 {
1113 CandidateRouteHop::FirstHop { details, .. } => details.next_outbound_htlc_minimum_msat,
1114 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1115 CandidateRouteHop::PrivateHop { hint, .. } => hint.htlc_minimum_msat.unwrap_or(0),
1116 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1117 CandidateRouteHop::OneHopBlinded { .. } => 0,
1121 /// Returns the fees for this hop.
1122 pub fn fees(&self) -> RoutingFees {
1124 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1125 base_msat: 0, proportional_millionths: 0,
1127 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1128 CandidateRouteHop::PrivateHop { hint, .. } => hint.fees,
1129 CandidateRouteHop::Blinded { hint, .. } => {
1131 base_msat: hint.0.fee_base_msat,
1132 proportional_millionths: hint.0.fee_proportional_millionths
1135 CandidateRouteHop::OneHopBlinded { .. } =>
1136 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1140 fn effective_capacity(&self) -> EffectiveCapacity {
1142 CandidateRouteHop::FirstHop { details, .. } => EffectiveCapacity::ExactLiquidity {
1143 liquidity_msat: details.next_outbound_htlc_limit_msat,
1145 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1146 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. } =>
1147 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1148 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. } =>
1149 EffectiveCapacity::Infinite,
1150 CandidateRouteHop::Blinded { hint, .. } =>
1151 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1152 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1156 /// Returns the id of this hop.
1157 /// For `Blinded` and `OneHopBlinded` we return `CandidateHopId::Blinded` with `hint_idx` because we don't know the channel id.
1158 /// For any other option we return `CandidateHopId::Clear` because we know the channel id and the direction.
1159 pub fn id(&self) -> CandidateHopId {
1161 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1162 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1163 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1166 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1168 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1174 /// Returns the source node id of current hop.
1176 /// Source node id refers to the hop forwarding the payment.
1178 /// For `FirstHop` we return payer's node id.
1179 pub fn source(&self) -> NodeId {
1181 CandidateRouteHop::FirstHop { node_id, .. } => *node_id,
1182 CandidateRouteHop::PublicHop { info, .. } => *info.source(),
1183 CandidateRouteHop::PrivateHop { hint, .. } => hint.src_node_id.into(),
1184 CandidateRouteHop::Blinded { hint, .. } => hint.1.introduction_node_id.into(),
1185 CandidateRouteHop::OneHopBlinded { hint, .. } => hint.1.introduction_node_id.into(),
1188 /// Returns the target node id of this hop, if known.
1190 /// Target node id refers to the hop receiving the payment.
1192 /// For `Blinded` and `OneHopBlinded` we return `None` because next hop is blinded.
1193 pub fn target(&self) -> Option<NodeId> {
1195 CandidateRouteHop::FirstHop { details, .. } => Some(details.counterparty.node_id.into()),
1196 CandidateRouteHop::PublicHop { info, .. } => Some(*info.target()),
1197 CandidateRouteHop::PrivateHop { target_node_id, .. } => Some(*target_node_id),
1198 CandidateRouteHop::Blinded { .. } => None,
1199 CandidateRouteHop::OneHopBlinded { .. } => None,
1204 /// A wrapper around the various hop id representations.
1206 /// `CandidateHopId::Clear` is used to identify a hop with a known short channel id and direction.
1207 /// `CandidateHopId::Blinded` is used to identify a blinded hop `hint_idx`.
1208 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1209 pub enum CandidateHopId {
1210 /// Contains (scid, src_node_id < target_node_id)
1212 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1217 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1218 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1220 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1221 EffectiveCapacity::Infinite => u64::max_value(),
1222 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1223 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1224 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1225 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1226 // expected to have been generated from up-to-date capacity information.
1227 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1228 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1229 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1233 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1234 -> bool where I1::Item: PartialEq<I2::Item> {
1236 let a = iter_a.next();
1237 let b = iter_b.next();
1238 if a.is_none() && b.is_none() { return true; }
1239 if a.is_none() || b.is_none() { return false; }
1240 if a.unwrap().ne(&b.unwrap()) { return false; }
1244 /// It's useful to keep track of the hops associated with the fees required to use them,
1245 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1246 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1247 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1249 struct PathBuildingHop<'a> {
1250 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1251 // is a larger refactor and will require careful performance analysis.
1253 candidate: CandidateRouteHop<'a>,
1256 /// All the fees paid *after* this channel on the way to the destination
1257 next_hops_fee_msat: u64,
1258 /// Fee paid for the use of the current channel (see candidate.fees()).
1259 /// The value will be actually deducted from the counterparty balance on the previous link.
1260 hop_use_fee_msat: u64,
1261 /// Used to compare channels when choosing the for routing.
1262 /// Includes paying for the use of a hop and the following hops, as well as
1263 /// an estimated cost of reaching this hop.
1264 /// Might get stale when fees are recomputed. Primarily for internal use.
1265 total_fee_msat: u64,
1266 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1267 /// walk and may be invalid thereafter.
1268 path_htlc_minimum_msat: u64,
1269 /// All penalties incurred from this channel on the way to the destination, as calculated using
1270 /// channel scoring.
1271 path_penalty_msat: u64,
1272 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1273 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1274 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1275 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1276 /// avoid processing them again.
1277 was_processed: bool,
1278 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1279 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1280 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1281 // value_contribution_msat, which requires tracking it here. See comments below where it is
1282 // used for more info.
1283 value_contribution_msat: u64,
1286 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1287 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1288 let mut debug_struct = f.debug_struct("PathBuildingHop");
1290 .field("node_id", &self.node_id)
1291 .field("short_channel_id", &self.candidate.short_channel_id())
1292 .field("total_fee_msat", &self.total_fee_msat)
1293 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1294 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1295 .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)))
1296 .field("path_penalty_msat", &self.path_penalty_msat)
1297 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1298 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1299 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1300 let debug_struct = debug_struct
1301 .field("value_contribution_msat", &self.value_contribution_msat);
1302 debug_struct.finish()
1306 // Instantiated with a list of hops with correct data in them collected during path finding,
1307 // an instance of this struct should be further modified only via given methods.
1309 struct PaymentPath<'a> {
1310 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1313 impl<'a> PaymentPath<'a> {
1314 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1315 fn get_value_msat(&self) -> u64 {
1316 self.hops.last().unwrap().0.fee_msat
1319 fn get_path_penalty_msat(&self) -> u64 {
1320 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1323 fn get_total_fee_paid_msat(&self) -> u64 {
1324 if self.hops.len() < 1 {
1328 // Can't use next_hops_fee_msat because it gets outdated.
1329 for (i, (hop, _)) in self.hops.iter().enumerate() {
1330 if i != self.hops.len() - 1 {
1331 result += hop.fee_msat;
1337 fn get_cost_msat(&self) -> u64 {
1338 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1341 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1342 // to change fees may result in an inconsistency.
1344 // Sometimes we call this function right after constructing a path which is inconsistent in
1345 // that it the value being transferred has decreased while we were doing path finding, leading
1346 // to the fees being paid not lining up with the actual limits.
1348 // Note that this function is not aware of the available_liquidity limit, and thus does not
1349 // support increasing the value being transferred beyond what was selected during the initial
1352 // Returns the amount that this path contributes to the total payment value, which may be greater
1353 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1354 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1355 let mut extra_contribution_msat = 0;
1356 let mut total_fee_paid_msat = 0 as u64;
1357 for i in (0..self.hops.len()).rev() {
1358 let last_hop = i == self.hops.len() - 1;
1360 // For non-last-hop, this value will represent the fees paid on the current hop. It
1361 // will consist of the fees for the use of the next hop, and extra fees to match
1362 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1363 let mut cur_hop_fees_msat = 0;
1365 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1368 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1369 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1370 cur_hop.path_penalty_msat += extra_contribution_msat;
1371 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1372 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1373 // set it too high just to maliciously take more fees by exploiting this
1374 // match htlc_minimum_msat logic.
1375 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1376 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1377 // Note that there is a risk that *previous hops* (those closer to us, as we go
1378 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1380 // This might make us end up with a broken route, although this should be super-rare
1381 // in practice, both because of how healthy channels look like, and how we pick
1382 // channels in add_entry.
1383 // Also, this can't be exploited more heavily than *announce a free path and fail
1385 cur_hop_transferred_amount_msat += extra_fees_msat;
1387 // We remember and return the extra fees on the final hop to allow accounting for
1388 // them in the path's value contribution.
1390 extra_contribution_msat = extra_fees_msat;
1392 total_fee_paid_msat += extra_fees_msat;
1393 cur_hop_fees_msat += extra_fees_msat;
1398 // Final hop is a special case: it usually has just value_msat (by design), but also
1399 // it still could overpay for the htlc_minimum_msat.
1400 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1402 // Propagate updated fees for the use of the channels to one hop back, where they
1403 // will be actually paid (fee_msat). The last hop is handled above separately.
1404 cur_hop.fee_msat = cur_hop_fees_msat;
1407 // Fee for the use of the current hop which will be deducted on the previous hop.
1408 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1409 // this channel is free for us.
1411 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1412 cur_hop.hop_use_fee_msat = new_fee;
1413 total_fee_paid_msat += new_fee;
1415 // It should not be possible because this function is called only to reduce the
1416 // value. In that case, compute_fee was already called with the same fees for
1417 // larger amount and there was no overflow.
1422 value_msat + extra_contribution_msat
1427 /// Calculate the fees required to route the given amount over a channel with the given fees.
1428 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1429 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1430 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1434 /// Calculate the fees required to route the given amount over a channel with the given fees,
1435 /// saturating to [`u64::max_value`].
1436 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1437 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1438 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1439 .saturating_add(channel_fees.base_msat as u64)
1442 /// The default `features` we assume for a node in a route, when no `features` are known about that
1445 /// Default features are:
1446 /// * variable_length_onion_optional
1447 fn default_node_features() -> NodeFeatures {
1448 let mut features = NodeFeatures::empty();
1449 features.set_variable_length_onion_optional();
1453 struct LoggedPayeePubkey(Option<PublicKey>);
1454 impl fmt::Display for LoggedPayeePubkey {
1455 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1458 "payee node id ".fmt(f)?;
1462 "blinded payee".fmt(f)
1468 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1469 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1470 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1472 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1473 "blinded route hint with introduction node id ".fmt(f)?;
1474 hint.1.introduction_node_id.fmt(f)?;
1475 " and blinding point ".fmt(f)?;
1476 hint.1.blinding_point.fmt(f)
1478 CandidateRouteHop::FirstHop { .. } => {
1479 "first hop with SCID ".fmt(f)?;
1480 self.0.short_channel_id().unwrap().fmt(f)
1482 CandidateRouteHop::PrivateHop { .. } => {
1483 "route hint with SCID ".fmt(f)?;
1484 self.0.short_channel_id().unwrap().fmt(f)
1488 self.0.short_channel_id().unwrap().fmt(f)
1495 fn sort_first_hop_channels(
1496 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1497 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1499 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1500 // most like to use.
1502 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1503 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1506 // Second, because simply always sorting in descending order would always use our largest
1507 // available outbound capacity, needlessly fragmenting our available channel capacities,
1508 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1509 // which have enough, but not too much, capacity for the payment.
1511 // Available outbound balances factor in liquidity already reserved for previously found paths.
1512 channels.sort_unstable_by(|chan_a, chan_b| {
1513 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1514 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1515 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1516 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1517 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1518 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1519 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1520 // Sort in descending order
1521 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1523 // Sort in ascending order
1524 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1529 /// Finds a route from us (payer) to the given target node (payee).
1531 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1532 /// in the given [`RouteParameters::payment_params`].
1533 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1535 /// Private routing paths between a public node and the target may be included in the `payee` field
1536 /// of [`RouteParameters::payment_params`].
1538 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1539 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1540 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1542 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1543 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1544 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1548 /// Panics if first_hops contains channels without `short_channel_id`s;
1549 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1551 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1552 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1553 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1554 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1555 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1556 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1557 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1558 ) -> Result<Route, LightningError>
1559 where L::Target: Logger, GL::Target: Logger {
1560 let graph_lock = network_graph.read_only();
1561 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1562 scorer, score_params, random_seed_bytes)?;
1563 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1567 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1568 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1569 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1570 _random_seed_bytes: &[u8; 32]
1571 ) -> Result<Route, LightningError>
1572 where L::Target: Logger {
1574 let payment_params = &route_params.payment_params;
1575 let final_value_msat = route_params.final_value_msat;
1576 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1577 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1578 // so use a dummy id for this in the blinded case.
1579 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1580 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1581 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1582 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1583 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1585 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1586 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1588 if our_node_id == maybe_dummy_payee_node_id {
1589 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1592 if final_value_msat > MAX_VALUE_MSAT {
1593 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1596 if final_value_msat == 0 {
1597 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1600 match &payment_params.payee {
1601 Payee::Clear { route_hints, node_id, .. } => {
1602 for route in route_hints.iter() {
1603 for hop in &route.0 {
1604 if hop.src_node_id == *node_id {
1605 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1610 Payee::Blinded { route_hints, .. } => {
1611 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1612 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});
1614 for (_, blinded_path) in route_hints.iter() {
1615 if blinded_path.blinded_hops.len() == 0 {
1616 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1617 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1618 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1619 } else if blinded_path.blinded_hops.len() == 1 &&
1620 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1621 && p.introduction_node_id != blinded_path.introduction_node_id)
1623 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1628 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1629 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1630 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});
1633 // The general routing idea is the following:
1634 // 1. Fill first/last hops communicated by the caller.
1635 // 2. Attempt to construct a path from payer to payee for transferring
1636 // any ~sufficient (described later) value.
1637 // If succeed, remember which channels were used and how much liquidity they have available,
1638 // so that future paths don't rely on the same liquidity.
1639 // 3. Proceed to the next step if:
1640 // - we hit the recommended target value;
1641 // - OR if we could not construct a new path. Any next attempt will fail too.
1642 // Otherwise, repeat step 2.
1643 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1644 // (not recommended value).
1645 // 5. If yes, proceed. If not, fail routing.
1646 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1647 // transferred up to the transfer target value.
1648 // 7. Reduce the value of the last path until we are sending only the target value.
1649 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1650 // them so that we're not sending two HTLCs along the same path.
1652 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1653 // distance from the payee
1655 // We are not a faithful Dijkstra's implementation because we can change values which impact
1656 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1657 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1658 // the value we are currently attempting to send over a path, we simply reduce the value being
1659 // sent along the path for any hops after that channel. This may imply that later fees (which
1660 // we've already tabulated) are lower because a smaller value is passing through the channels
1661 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1662 // channels which were selected earlier (and which may still be used for other paths without a
1663 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1666 // One potentially problematic case for this algorithm would be if there are many
1667 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1668 // graph walking), we may never find a path which is not liquidity-limited and has lower
1669 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1670 // Because we only consider paths with at least 5% of the total value being sent, the damage
1671 // from such a case should be limited, however this could be further reduced in the future by
1672 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1673 // limits for the purposes of fee calculation.
1675 // Alternatively, we could store more detailed path information in the heap (targets, below)
1676 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1677 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1678 // and practically (as we would need to store dynamically-allocated path information in heap
1679 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1680 // results of such an algorithm would likely be biased towards lower-value paths.
1682 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1683 // outside of our current search value, running a path search more times to gather candidate
1684 // paths at different values. While this may be acceptable, further path searches may increase
1685 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1686 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1687 // the same time, remaining generic across different payment values.
1689 let network_channels = network_graph.channels();
1690 let network_nodes = network_graph.nodes();
1692 if payment_params.max_path_count == 0 {
1693 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1696 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1697 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1699 let allow_mpp = if payment_params.max_path_count == 1 {
1701 } else if payment_params.payee.supports_basic_mpp() {
1703 } else if let Some(payee) = payee_node_id_opt {
1704 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1705 |info| info.features.supports_basic_mpp()))
1708 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1710 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1711 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1712 if allow_mpp { "with" } else { "without" },
1713 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1714 max_total_routing_fee_msat);
1717 // Prepare the data we'll use for payee-to-payer search by
1718 // inserting first hops suggested by the caller as targets.
1719 // Our search will then attempt to reach them while traversing from the payee node.
1720 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1721 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1722 if let Some(hops) = first_hops {
1724 if chan.get_outbound_payment_scid().is_none() {
1725 panic!("first_hops should be filled in with usable channels, not pending ones");
1727 if chan.counterparty.node_id == *our_node_pubkey {
1728 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1731 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1732 .or_insert(Vec::new())
1735 if first_hop_targets.is_empty() {
1736 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1740 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1741 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1742 // adding duplicate entries when we find a better path to a given node.
1743 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1745 // Map from node_id to information about the best current path to that node, including feerate
1747 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1749 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1750 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1751 // htlc_minimum with extra fees while still finding a cheaper path.
1752 let mut hit_minimum_limit;
1754 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1755 // We start with a path_value of the exact amount we want, and if that generates a route we may
1756 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1757 // amount we want in total across paths, selecting the best subset at the end.
1758 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1759 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1760 let mut path_value_msat = final_value_msat;
1762 // Routing Fragmentation Mitigation heuristic:
1764 // Routing fragmentation across many payment paths increases the overall routing
1765 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1766 // Taking too many smaller paths also increases the chance of payment failure.
1767 // Thus to avoid this effect, we require from our collected links to provide
1768 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1769 // This requirement is currently set to be 1/max_path_count of the payment
1770 // value to ensure we only ever return routes that do not violate this limit.
1771 let minimal_value_contribution_msat: u64 = if allow_mpp {
1772 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1777 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1778 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1779 // drop the requirement by setting this to 0.
1780 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1782 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1783 // determine if the channel can be used by additional MPP paths or to inform path finding
1784 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1785 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1787 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1788 HashMap::with_capacity(network_nodes.len());
1790 // Keeping track of how much value we already collected across other paths. Helps to decide
1791 // when we want to stop looking for new paths.
1792 let mut already_collected_value_msat = 0;
1794 for (_, channels) in first_hop_targets.iter_mut() {
1795 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1799 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1800 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1802 // Remember how many candidates we ignored to allow for some logging afterwards.
1803 let mut num_ignored_value_contribution: u32 = 0;
1804 let mut num_ignored_path_length_limit: u32 = 0;
1805 let mut num_ignored_cltv_delta_limit: u32 = 0;
1806 let mut num_ignored_previously_failed: u32 = 0;
1807 let mut num_ignored_total_fee_limit: u32 = 0;
1808 let mut num_ignored_avoid_overpayment: u32 = 0;
1809 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
1811 macro_rules! add_entry {
1812 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
1813 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1814 // since that value has to be transferred over this channel.
1815 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
1816 ( $candidate: expr, $next_hops_fee_msat: expr,
1817 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1818 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1819 // We "return" whether we updated the path at the end, and how much we can route via
1820 // this channel, via this:
1821 let mut hop_contribution_amt_msat = None;
1822 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1823 // practice these cases should be caught earlier:
1824 // - for regular channels at channel announcement (TODO)
1825 // - for first and last hops early in get_route
1826 let src_node_id = $candidate.source();
1827 let dest_node_id = $candidate.target().unwrap_or(maybe_dummy_payee_node_id);
1828 if src_node_id != dest_node_id {
1829 let scid_opt = $candidate.short_channel_id();
1830 let effective_capacity = $candidate.effective_capacity();
1831 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1833 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1834 // It may be misleading because we might later choose to reduce the value transferred
1835 // over these channels, and the channel which was insufficient might become sufficient.
1836 // Worst case: we drop a good channel here because it can't cover the high following
1837 // fees caused by one expensive channel, but then this channel could have been used
1838 // if the amount being transferred over this path is lower.
1839 // We do this for now, but this is a subject for removal.
1840 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1841 let used_liquidity_msat = used_liquidities
1842 .get(&$candidate.id())
1843 .map_or(0, |used_liquidity_msat| {
1844 available_value_contribution_msat = available_value_contribution_msat
1845 .saturating_sub(*used_liquidity_msat);
1846 *used_liquidity_msat
1849 // Verify the liquidity offered by this channel complies to the minimal contribution.
1850 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1851 // Do not consider candidate hops that would exceed the maximum path length.
1852 let path_length_to_node = $next_hops_path_length + 1;
1853 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1855 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1856 // In order to already account for some of the privacy enhancing random CLTV
1857 // expiry delta offset we add on top later, we subtract a rough estimate
1858 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1859 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1860 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1861 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1862 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1863 .saturating_add($candidate.cltv_expiry_delta());
1864 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1866 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1867 // Includes paying fees for the use of the following channels.
1868 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1869 Some(result) => result,
1870 // Can't overflow due to how the values were computed right above.
1871 None => unreachable!(),
1873 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1874 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1875 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1877 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1878 let may_overpay_to_meet_path_minimum_msat =
1879 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1880 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
1881 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1882 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
1884 let payment_failed_on_this_channel = scid_opt.map_or(false,
1885 |scid| payment_params.previously_failed_channels.contains(&scid));
1887 let (should_log_candidate, first_hop_details) = match $candidate {
1888 CandidateRouteHop::FirstHop { details, .. } => (true, Some(details)),
1889 CandidateRouteHop::PrivateHop { .. } => (true, None),
1890 CandidateRouteHop::Blinded { .. } => (true, None),
1891 CandidateRouteHop::OneHopBlinded { .. } => (true, None),
1895 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1896 // bother considering this channel. If retrying with recommended_value_msat may
1897 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1898 // around again with a higher amount.
1899 if !contributes_sufficient_value {
1900 if should_log_candidate {
1901 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1903 if let Some(details) = first_hop_details {
1905 "First hop candidate next_outbound_htlc_limit_msat: {}",
1906 details.next_outbound_htlc_limit_msat,
1910 num_ignored_value_contribution += 1;
1911 } else if exceeds_max_path_length {
1912 if should_log_candidate {
1913 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1915 num_ignored_path_length_limit += 1;
1916 } else if exceeds_cltv_delta_limit {
1917 if should_log_candidate {
1918 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1920 if let Some(_) = first_hop_details {
1922 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
1923 hop_total_cltv_delta,
1924 max_total_cltv_expiry_delta,
1928 num_ignored_cltv_delta_limit += 1;
1929 } else if payment_failed_on_this_channel {
1930 if should_log_candidate {
1931 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1933 num_ignored_previously_failed += 1;
1934 } else if may_overpay_to_meet_path_minimum_msat {
1935 if should_log_candidate {
1937 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
1938 LoggedCandidateHop(&$candidate));
1940 if let Some(details) = first_hop_details {
1942 "First hop candidate next_outbound_htlc_minimum_msat: {}",
1943 details.next_outbound_htlc_minimum_msat,
1947 num_ignored_avoid_overpayment += 1;
1948 hit_minimum_limit = true;
1949 } else if over_path_minimum_msat {
1950 // Note that low contribution here (limited by available_liquidity_msat)
1951 // might violate htlc_minimum_msat on the hops which are next along the
1952 // payment path (upstream to the payee). To avoid that, we recompute
1953 // path fees knowing the final path contribution after constructing it.
1954 let curr_min = cmp::max(
1955 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
1957 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
1958 .saturating_add(curr_min);
1959 let hm_entry = dist.entry(src_node_id);
1960 let old_entry = hm_entry.or_insert_with(|| {
1961 // If there was previously no known way to access the source node
1962 // (recall it goes payee-to-payer) of short_channel_id, first add a
1963 // semi-dummy record just to compute the fees to reach the source node.
1964 // This will affect our decision on selecting short_channel_id
1965 // as a way to reach the $candidate.target() node.
1967 node_id: dest_node_id.clone(),
1968 candidate: $candidate.clone(),
1970 next_hops_fee_msat: u64::max_value(),
1971 hop_use_fee_msat: u64::max_value(),
1972 total_fee_msat: u64::max_value(),
1973 path_htlc_minimum_msat,
1974 path_penalty_msat: u64::max_value(),
1975 was_processed: false,
1976 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1977 value_contribution_msat,
1981 #[allow(unused_mut)] // We only use the mut in cfg(test)
1982 let mut should_process = !old_entry.was_processed;
1983 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1985 // In test/fuzzing builds, we do extra checks to make sure the skipping
1986 // of already-seen nodes only happens in cases we expect (see below).
1987 if !should_process { should_process = true; }
1991 let mut hop_use_fee_msat = 0;
1992 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1994 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1995 // will have the same effective-fee
1996 if src_node_id != our_node_id {
1997 // Note that `u64::max_value` means we'll always fail the
1998 // `old_entry.total_fee_msat > total_fee_msat` check below
1999 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2000 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2003 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2004 if total_fee_msat > max_total_routing_fee_msat {
2005 if should_log_candidate {
2006 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2008 if let Some(_) = first_hop_details {
2010 "First hop candidate routing fee: {}. Limit: {}",
2012 max_total_routing_fee_msat,
2016 num_ignored_total_fee_limit += 1;
2018 let channel_usage = ChannelUsage {
2019 amount_msat: amount_to_transfer_over_msat,
2020 inflight_htlc_msat: used_liquidity_msat,
2023 let channel_penalty_msat =
2024 scorer.channel_penalty_msat($candidate,
2027 let path_penalty_msat = $next_hops_path_penalty_msat
2028 .saturating_add(channel_penalty_msat);
2029 let new_graph_node = RouteGraphNode {
2030 node_id: src_node_id,
2031 lowest_fee_to_node: total_fee_msat,
2032 total_cltv_delta: hop_total_cltv_delta,
2033 value_contribution_msat,
2034 path_htlc_minimum_msat,
2036 path_length_to_node,
2039 // Update the way of reaching $candidate.source()
2040 // with the given short_channel_id (from $candidate.target()),
2041 // if this way is cheaper than the already known
2042 // (considering the cost to "reach" this channel from the route destination,
2043 // the cost of using this channel,
2044 // and the cost of routing to the source node of this channel).
2045 // Also, consider that htlc_minimum_msat_difference, because we might end up
2046 // paying it. Consider the following exploit:
2047 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2048 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2049 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2050 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2052 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2053 // but it may require additional tracking - we don't want to double-count
2054 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2055 // can't use something that may decrease on future hops.
2056 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2057 .saturating_add(old_entry.path_penalty_msat);
2058 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2059 .saturating_add(path_penalty_msat);
2061 if !old_entry.was_processed && new_cost < old_cost {
2062 targets.push(new_graph_node);
2063 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2064 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2065 old_entry.total_fee_msat = total_fee_msat;
2066 old_entry.node_id = dest_node_id;
2067 old_entry.candidate = $candidate.clone();
2068 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2069 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2070 old_entry.path_penalty_msat = path_penalty_msat;
2071 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2073 old_entry.value_contribution_msat = value_contribution_msat;
2075 hop_contribution_amt_msat = Some(value_contribution_msat);
2076 } else if old_entry.was_processed && new_cost < old_cost {
2077 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2079 // If we're skipping processing a node which was previously
2080 // processed even though we found another path to it with a
2081 // cheaper fee, check that it was because the second path we
2082 // found (which we are processing now) has a lower value
2083 // contribution due to an HTLC minimum limit.
2085 // e.g. take a graph with two paths from node 1 to node 2, one
2086 // through channel A, and one through channel B. Channel A and
2087 // B are both in the to-process heap, with their scores set by
2088 // a higher htlc_minimum than fee.
2089 // Channel A is processed first, and the channels onwards from
2090 // node 1 are added to the to-process heap. Thereafter, we pop
2091 // Channel B off of the heap, note that it has a much more
2092 // restrictive htlc_maximum_msat, and recalculate the fees for
2093 // all of node 1's channels using the new, reduced, amount.
2095 // This would be bogus - we'd be selecting a higher-fee path
2096 // with a lower htlc_maximum_msat instead of the one we'd
2097 // already decided to use.
2098 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2100 value_contribution_msat + path_penalty_msat <
2101 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2108 if should_log_candidate {
2110 "Ignoring {} due to its htlc_minimum_msat limit.",
2111 LoggedCandidateHop(&$candidate));
2113 if let Some(details) = first_hop_details {
2115 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2116 details.next_outbound_htlc_minimum_msat,
2120 num_ignored_htlc_minimum_msat_limit += 1;
2124 hop_contribution_amt_msat
2128 let default_node_features = default_node_features();
2130 // Find ways (channels with destination) to reach a given node and store them
2131 // in the corresponding data structures (routing graph etc).
2132 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2133 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2134 // This data can later be helpful to optimize routing (pay lower fees).
2135 macro_rules! add_entries_to_cheapest_to_target_node {
2136 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
2137 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
2138 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2139 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2140 let was_processed = elem.was_processed;
2141 elem.was_processed = true;
2144 // Entries are added to dist in add_entry!() when there is a channel from a node.
2145 // Because there are no channels from payee, it will not have a dist entry at this point.
2146 // If we're processing any other node, it is always be the result of a channel from it.
2147 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2152 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2153 for details in first_channels {
2154 let candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id };
2155 add_entry!(&candidate, $fee_to_target_msat,
2156 $next_hops_value_contribution,
2157 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
2158 $next_hops_cltv_delta, $next_hops_path_length);
2162 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2165 &default_node_features
2168 if !features.requires_unknown_bits() {
2169 for chan_id in $node.channels.iter() {
2170 let chan = network_channels.get(chan_id).unwrap();
2171 if !chan.features.requires_unknown_bits() {
2172 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2173 if first_hops.is_none() || *source != our_node_id {
2174 if directed_channel.direction().enabled {
2175 let candidate = CandidateRouteHop::PublicHop {
2176 info: directed_channel,
2177 short_channel_id: *chan_id,
2179 add_entry!(&candidate,
2180 $fee_to_target_msat,
2181 $next_hops_value_contribution,
2182 $next_hops_path_htlc_minimum_msat,
2183 $next_hops_path_penalty_msat,
2184 $next_hops_cltv_delta, $next_hops_path_length);
2195 let mut payment_paths = Vec::<PaymentPath>::new();
2197 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2198 'paths_collection: loop {
2199 // For every new path, start from scratch, except for used_liquidities, which
2200 // helps to avoid reusing previously selected paths in future iterations.
2203 hit_minimum_limit = false;
2205 // If first hop is a private channel and the only way to reach the payee, this is the only
2206 // place where it could be added.
2207 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2208 for details in first_channels {
2209 let candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id };
2210 let added = add_entry!(&candidate, 0, path_value_msat,
2211 0, 0u64, 0, 0).is_some();
2212 log_trace!(logger, "{} direct route to payee via {}",
2213 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2217 // Add the payee as a target, so that the payee-to-payer
2218 // search algorithm knows what to start with.
2219 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2220 // The payee is not in our network graph, so nothing to add here.
2221 // There is still a chance of reaching them via last_hops though,
2222 // so don't yet fail the payment here.
2223 // If not, targets.pop() will not even let us enter the loop in step 2.
2226 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2231 // If a caller provided us with last hops, add them to routing targets. Since this happens
2232 // earlier than general path finding, they will be somewhat prioritized, although currently
2233 // it matters only if the fees are exactly the same.
2234 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2235 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2236 let have_intro_node_in_graph =
2237 // Only add the hops in this route to our candidate set if either
2238 // we have a direct channel to the first hop or the first hop is
2239 // in the regular network graph.
2240 first_hop_targets.get(&intro_node_id).is_some() ||
2241 network_nodes.get(&intro_node_id).is_some();
2242 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2243 let candidate = if hint.1.blinded_hops.len() == 1 {
2244 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2245 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2246 let mut path_contribution_msat = path_value_msat;
2247 if let Some(hop_used_msat) = add_entry!(&candidate,
2248 0, path_contribution_msat, 0, 0_u64, 0, 0)
2250 path_contribution_msat = hop_used_msat;
2252 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2253 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2255 for details in first_channels {
2256 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2257 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2261 let path_min = candidate.htlc_minimum_msat().saturating_add(
2262 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2263 add_entry!(&first_hop_candidate, blinded_path_fee,
2264 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2265 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2269 for route in payment_params.payee.unblinded_route_hints().iter()
2270 .filter(|route| !route.0.is_empty())
2272 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2273 let first_hop_src_is_reachable =
2274 // Only add the hops in this route to our candidate set if either we are part of
2275 // the first hop, we have a direct channel to the first hop, or the first hop is in
2276 // the regular network graph.
2277 our_node_id == first_hop_src_id ||
2278 first_hop_targets.get(&first_hop_src_id).is_some() ||
2279 network_nodes.get(&first_hop_src_id).is_some();
2280 if first_hop_src_is_reachable {
2281 // We start building the path from reverse, i.e., from payee
2282 // to the first RouteHintHop in the path.
2283 let hop_iter = route.0.iter().rev();
2284 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2285 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2286 let mut hop_used = true;
2287 let mut aggregate_next_hops_fee_msat: u64 = 0;
2288 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2289 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2290 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2291 let mut aggregate_next_hops_path_length: u8 = 0;
2292 let mut aggregate_path_contribution_msat = path_value_msat;
2294 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2295 let source = NodeId::from_pubkey(&hop.src_node_id);
2296 let target = NodeId::from_pubkey(&prev_hop_id);
2298 if let Some(first_channels) = first_hop_targets.get(&target) {
2299 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2300 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2301 hop.short_channel_id);
2306 let candidate = network_channels
2307 .get(&hop.short_channel_id)
2308 .and_then(|channel| channel.as_directed_to(&target))
2309 .map(|(info, _)| CandidateRouteHop::PublicHop {
2311 short_channel_id: hop.short_channel_id,
2313 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop, target_node_id: target });
2315 if let Some(hop_used_msat) = add_entry!(&candidate,
2316 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2317 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2318 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2320 aggregate_path_contribution_msat = hop_used_msat;
2322 // If this hop was not used then there is no use checking the preceding
2323 // hops in the RouteHint. We can break by just searching for a direct
2324 // channel between last checked hop and first_hop_targets.
2328 let used_liquidity_msat = used_liquidities
2329 .get(&candidate.id()).copied()
2331 let channel_usage = ChannelUsage {
2332 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2333 inflight_htlc_msat: used_liquidity_msat,
2334 effective_capacity: candidate.effective_capacity(),
2336 let channel_penalty_msat = scorer.channel_penalty_msat(
2337 &candidate, channel_usage, score_params
2339 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2340 .saturating_add(channel_penalty_msat);
2342 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2343 .saturating_add(hop.cltv_expiry_delta as u32);
2345 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2348 // Searching for a direct channel between last checked hop and first_hop_targets
2349 if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2350 sort_first_hop_channels(first_channels, &used_liquidities,
2351 recommended_value_msat, our_node_pubkey);
2352 for details in first_channels {
2353 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2354 add_entry!(&first_hop_candidate,
2355 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2356 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2357 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2365 // In the next values of the iterator, the aggregate fees already reflects
2366 // the sum of value sent from payer (final_value_msat) and routing fees
2367 // for the last node in the RouteHint. We need to just add the fees to
2368 // route through the current node so that the preceding node (next iteration)
2370 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2371 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2372 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2374 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2375 // this route hint's source node to forward said min over this channel.
2376 aggregate_next_hops_path_htlc_minimum_msat = {
2377 let curr_htlc_min = cmp::max(
2378 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2380 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2381 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2384 if idx == route.0.len() - 1 {
2385 // The last hop in this iterator is the first hop in
2386 // overall RouteHint.
2387 // If this hop connects to a node with which we have a direct channel,
2388 // ignore the network graph and, if the last hop was added, add our
2389 // direct channel to the candidate set.
2391 // Note that we *must* check if the last hop was added as `add_entry`
2392 // always assumes that the third argument is a node to which we have a
2394 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2395 sort_first_hop_channels(first_channels, &used_liquidities,
2396 recommended_value_msat, our_node_pubkey);
2397 for details in first_channels {
2398 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2399 add_entry!(&first_hop_candidate,
2400 aggregate_next_hops_fee_msat,
2401 aggregate_path_contribution_msat,
2402 aggregate_next_hops_path_htlc_minimum_msat,
2403 aggregate_next_hops_path_penalty_msat,
2404 aggregate_next_hops_cltv_delta,
2405 aggregate_next_hops_path_length);
2413 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2415 // At this point, targets are filled with the data from first and
2416 // last hops communicated by the caller, and the payment receiver.
2417 let mut found_new_path = false;
2420 // If this loop terminates due the exhaustion of targets, two situations are possible:
2421 // - not enough outgoing liquidity:
2422 // 0 < already_collected_value_msat < final_value_msat
2423 // - enough outgoing liquidity:
2424 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2425 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2426 // paths_collection will be stopped because found_new_path==false.
2427 // This is not necessarily a routing failure.
2428 '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() {
2430 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2431 // traversing the graph and arrange the path out of what we found.
2432 if node_id == our_node_id {
2433 let mut new_entry = dist.remove(&our_node_id).unwrap();
2434 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2437 let mut features_set = false;
2438 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2439 for details in first_channels {
2440 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2441 if details.get_outbound_payment_scid().unwrap() == scid {
2442 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2443 features_set = true;
2450 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2451 if let Some(node_info) = node.announcement_info.as_ref() {
2452 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2454 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2457 // We can fill in features for everything except hops which were
2458 // provided via the invoice we're paying. We could guess based on the
2459 // recipient's features but for now we simply avoid guessing at all.
2463 // Means we succesfully traversed from the payer to the payee, now
2464 // save this path for the payment route. Also, update the liquidity
2465 // remaining on the used hops, so that we take them into account
2466 // while looking for more paths.
2467 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2471 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2472 Some(payment_hop) => payment_hop,
2473 // We can't arrive at None because, if we ever add an entry to targets,
2474 // we also fill in the entry in dist (see add_entry!).
2475 None => unreachable!(),
2477 // We "propagate" the fees one hop backward (topologically) here,
2478 // so that fees paid for a HTLC forwarding on the current channel are
2479 // associated with the previous channel (where they will be subtracted).
2480 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2481 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2483 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2484 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2486 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2487 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2489 let mut payment_path = PaymentPath {hops: ordered_hops};
2491 // We could have possibly constructed a slightly inconsistent path: since we reduce
2492 // value being transferred along the way, we could have violated htlc_minimum_msat
2493 // on some channels we already passed (assuming dest->source direction). Here, we
2494 // recompute the fees again, so that if that's the case, we match the currently
2495 // underpaid htlc_minimum_msat with fees.
2496 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2497 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2498 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2500 // Since a path allows to transfer as much value as
2501 // the smallest channel it has ("bottleneck"), we should recompute
2502 // the fees so sender HTLC don't overpay fees when traversing
2503 // larger channels than the bottleneck. This may happen because
2504 // when we were selecting those channels we were not aware how much value
2505 // this path will transfer, and the relative fee for them
2506 // might have been computed considering a larger value.
2507 // Remember that we used these channels so that we don't rely
2508 // on the same liquidity in future paths.
2509 let mut prevented_redundant_path_selection = false;
2510 for (hop, _) in payment_path.hops.iter() {
2511 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2512 let used_liquidity_msat = used_liquidities
2513 .entry(hop.candidate.id())
2514 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2515 .or_insert(spent_on_hop_msat);
2516 let hop_capacity = hop.candidate.effective_capacity();
2517 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2518 if *used_liquidity_msat == hop_max_msat {
2519 // If this path used all of this channel's available liquidity, we know
2520 // this path will not be selected again in the next loop iteration.
2521 prevented_redundant_path_selection = true;
2523 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2525 if !prevented_redundant_path_selection {
2526 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2527 // we'll probably end up picking the same path again on the next iteration.
2528 // Decrease the available liquidity of a hop in the middle of the path.
2529 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2530 let exhausted = u64::max_value();
2532 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2533 LoggedCandidateHop(victim_candidate));
2534 if let Some(scid) = victim_candidate.short_channel_id() {
2535 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2536 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2540 // Track the total amount all our collected paths allow to send so that we know
2541 // when to stop looking for more paths
2542 already_collected_value_msat += value_contribution_msat;
2544 payment_paths.push(payment_path);
2545 found_new_path = true;
2546 break 'path_construction;
2549 // If we found a path back to the payee, we shouldn't try to process it again. This is
2550 // the equivalent of the `elem.was_processed` check in
2551 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2552 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2554 // Otherwise, since the current target node is not us,
2555 // keep "unrolling" the payment graph from payee to payer by
2556 // finding a way to reach the current target from the payer side.
2557 match network_nodes.get(&node_id) {
2560 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2561 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2562 total_cltv_delta, path_length_to_node);
2568 if !found_new_path && channel_saturation_pow_half != 0 {
2569 channel_saturation_pow_half = 0;
2570 continue 'paths_collection;
2572 // If we don't support MPP, no use trying to gather more value ever.
2573 break 'paths_collection;
2577 // Stop either when the recommended value is reached or if no new path was found in this
2579 // In the latter case, making another path finding attempt won't help,
2580 // because we deterministically terminated the search due to low liquidity.
2581 if !found_new_path && channel_saturation_pow_half != 0 {
2582 channel_saturation_pow_half = 0;
2583 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2584 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2585 path_value_msat = recommended_value_msat;
2586 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2587 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2588 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2589 break 'paths_collection;
2590 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2591 // Further, if this was our first walk of the graph, and we weren't limited by an
2592 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2593 // limited by an htlc_minimum_msat value, find another path with a higher value,
2594 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2595 // still keeping a lower total fee than this path.
2596 if !hit_minimum_limit {
2597 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2598 break 'paths_collection;
2600 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.");
2601 path_value_msat = recommended_value_msat;
2605 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2606 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2607 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2608 num_ignored_total_fee_limit;
2609 if num_ignored_total > 0 {
2611 "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.",
2612 num_ignored_value_contribution, num_ignored_path_length_limit,
2613 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2614 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2615 num_ignored_total_fee_limit, num_ignored_total);
2619 if payment_paths.len() == 0 {
2620 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2623 if already_collected_value_msat < final_value_msat {
2624 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2628 let mut selected_route = payment_paths;
2630 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2631 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2633 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2634 // the value they contribute towards the payment amount.
2635 // We sort in descending order as we will remove from the front in `retain`, next.
2636 selected_route.sort_unstable_by(|a, b|
2637 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2638 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2641 // We should make sure that at least 1 path left.
2642 let mut paths_left = selected_route.len();
2643 selected_route.retain(|path| {
2644 if paths_left == 1 {
2647 let path_value_msat = path.get_value_msat();
2648 if path_value_msat <= overpaid_value_msat {
2649 overpaid_value_msat -= path_value_msat;
2655 debug_assert!(selected_route.len() > 0);
2657 if overpaid_value_msat != 0 {
2659 // Now, subtract the remaining overpaid value from the most-expensive path.
2660 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2661 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2662 selected_route.sort_unstable_by(|a, b| {
2663 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2664 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2665 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2667 let expensive_payment_path = selected_route.first_mut().unwrap();
2669 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2670 // can't go negative.
2671 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2672 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2676 // Sort by the path itself and combine redundant paths.
2677 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2678 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2680 selected_route.sort_unstable_by_key(|path| {
2681 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2682 debug_assert!(path.hops.len() <= key.len());
2683 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2688 for idx in 0..(selected_route.len() - 1) {
2689 if idx + 1 >= selected_route.len() { break; }
2690 if iter_equal(selected_route[idx].hops.iter().map(|h| (h.0.candidate.id(), h.0.node_id)),
2691 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.node_id))) {
2692 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2693 selected_route[idx].update_value_and_recompute_fees(new_value);
2694 selected_route.remove(idx + 1);
2698 let mut paths = Vec::new();
2699 for payment_path in selected_route {
2700 let mut hops = Vec::with_capacity(payment_path.hops.len());
2701 for (hop, node_features) in payment_path.hops.iter()
2702 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2704 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2705 // If we sourced the hop from the graph we're sure the target node is announced.
2707 } else if let CandidateRouteHop::FirstHop { details, .. } = hop.candidate {
2708 // If this is a first hop we also know if it's announced.
2711 // If we sourced it any other way, we double-check the network graph to see if
2712 // there are announced channels between the endpoints. If so, the hop might be
2713 // referring to any of the announced channels, as its `short_channel_id` might be
2714 // an alias, in which case we don't take any chances here.
2715 network_graph.node(&hop.node_id).map_or(false, |hop_node|
2716 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2717 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
2721 hops.push(RouteHop {
2722 pubkey: PublicKey::from_slice(hop.node_id.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &hop.node_id), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2723 node_features: node_features.clone(),
2724 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2725 channel_features: hop.candidate.features(),
2726 fee_msat: hop.fee_msat,
2727 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2728 maybe_announced_channel,
2731 let mut final_cltv_delta = final_cltv_expiry_delta;
2732 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2733 if let Some(blinded_path) = h.candidate.blinded_path() {
2734 final_cltv_delta = h.candidate.cltv_expiry_delta();
2736 hops: blinded_path.blinded_hops.clone(),
2737 blinding_point: blinded_path.blinding_point,
2738 excess_final_cltv_expiry_delta: 0,
2739 final_value_msat: h.fee_msat,
2743 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2744 // applicable for the previous hop.
2745 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2746 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2749 paths.push(Path { hops, blinded_tail });
2751 // Make sure we would never create a route with more paths than we allow.
2752 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2754 if let Some(node_features) = payment_params.payee.node_features() {
2755 for path in paths.iter_mut() {
2756 path.hops.last_mut().unwrap().node_features = node_features.clone();
2760 let route = Route { paths, route_params: Some(route_params.clone()) };
2762 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2763 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2764 if route.get_total_fees() > max_total_routing_fee_msat {
2765 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2766 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2770 log_info!(logger, "Got route: {}", log_route!(route));
2774 // When an adversarial intermediary node observes a payment, it may be able to infer its
2775 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2776 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2777 // payment path by adding a randomized 'shadow route' offset to the final hop.
2778 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2779 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2781 let network_channels = network_graph.channels();
2782 let network_nodes = network_graph.nodes();
2784 for path in route.paths.iter_mut() {
2785 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2787 // Remember the last three nodes of the random walk and avoid looping back on them.
2788 // Init with the last three nodes from the actual path, if possible.
2789 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2790 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2791 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2793 // Choose the last publicly known node as the starting point for the random walk.
2794 let mut cur_hop: Option<NodeId> = None;
2795 let mut path_nonce = [0u8; 12];
2796 if let Some(starting_hop) = path.hops.iter().rev()
2797 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2798 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2799 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2802 // Init PRNG with the path-dependant nonce, which is static for private paths.
2803 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2804 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2806 // Pick a random path length in [1 .. 3]
2807 prng.process_in_place(&mut random_path_bytes);
2808 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2810 for random_hop in 0..random_walk_length {
2811 // If we don't find a suitable offset in the public network graph, we default to
2812 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2813 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2815 if let Some(cur_node_id) = cur_hop {
2816 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2817 // Randomly choose the next unvisited hop.
2818 prng.process_in_place(&mut random_path_bytes);
2819 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2820 .checked_rem(cur_node.channels.len())
2821 .and_then(|index| cur_node.channels.get(index))
2822 .and_then(|id| network_channels.get(id)) {
2823 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2824 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2825 nodes_to_avoid[random_hop] = *next_id;
2826 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2827 cur_hop = Some(*next_id);
2834 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2835 .checked_add(random_hop_offset)
2836 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2839 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2840 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2841 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2843 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2844 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2845 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2846 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2847 max_path_offset = cmp::max(
2848 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2849 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2850 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2852 // Add 'shadow' CLTV offset to the final hop
2853 if let Some(tail) = path.blinded_tail.as_mut() {
2854 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2855 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2857 if let Some(last_hop) = path.hops.last_mut() {
2858 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2859 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2864 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2865 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2867 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2868 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2869 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2870 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2871 ) -> Result<Route, LightningError>
2872 where L::Target: Logger, GL::Target: Logger {
2873 let graph_lock = network_graph.read_only();
2874 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2875 &graph_lock, logger, random_seed_bytes)?;
2876 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2880 fn build_route_from_hops_internal<L: Deref>(
2881 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2882 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2883 ) -> Result<Route, LightningError> where L::Target: Logger {
2886 our_node_id: NodeId,
2887 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2890 impl ScoreLookUp for HopScorer {
2891 type ScoreParams = ();
2892 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
2893 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2895 let mut cur_id = self.our_node_id;
2896 for i in 0..self.hop_ids.len() {
2897 if let Some(next_id) = self.hop_ids[i] {
2898 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
2910 impl<'a> Writeable for HopScorer {
2912 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2917 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2918 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2921 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2922 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2923 for i in 0..hops.len() {
2924 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2927 let scorer = HopScorer { our_node_id, hop_ids };
2929 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2934 use crate::blinded_path::{BlindedHop, BlindedPath};
2935 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2936 use crate::routing::utxo::UtxoResult;
2937 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2938 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2939 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop};
2940 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2941 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2942 use crate::chain::transaction::OutPoint;
2943 use crate::sign::EntropySource;
2944 use crate::ln::ChannelId;
2945 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2946 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2947 use crate::ln::channelmanager;
2948 use crate::offers::invoice::BlindedPayInfo;
2949 use crate::util::config::UserConfig;
2950 use crate::util::test_utils as ln_test_utils;
2951 use crate::util::chacha20::ChaCha20;
2952 use crate::util::ser::{Readable, Writeable};
2954 use crate::util::ser::Writer;
2956 use bitcoin::hashes::Hash;
2957 use bitcoin::network::constants::Network;
2958 use bitcoin::blockdata::constants::ChainHash;
2959 use bitcoin::blockdata::script::Builder;
2960 use bitcoin::blockdata::opcodes;
2961 use bitcoin::blockdata::transaction::TxOut;
2962 use bitcoin::hashes::hex::FromHex;
2963 use bitcoin::secp256k1::{PublicKey,SecretKey};
2964 use bitcoin::secp256k1::Secp256k1;
2966 use crate::io::Cursor;
2967 use crate::prelude::*;
2968 use crate::sync::Arc;
2970 use core::convert::TryInto;
2972 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2973 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2974 channelmanager::ChannelDetails {
2975 channel_id: ChannelId::new_zero(),
2976 counterparty: channelmanager::ChannelCounterparty {
2979 unspendable_punishment_reserve: 0,
2980 forwarding_info: None,
2981 outbound_htlc_minimum_msat: None,
2982 outbound_htlc_maximum_msat: None,
2984 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2987 outbound_scid_alias: None,
2988 inbound_scid_alias: None,
2989 channel_value_satoshis: 0,
2992 outbound_capacity_msat,
2993 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2994 next_outbound_htlc_minimum_msat: 0,
2995 inbound_capacity_msat: 42,
2996 unspendable_punishment_reserve: None,
2997 confirmations_required: None,
2998 confirmations: None,
2999 force_close_spend_delay: None,
3000 is_outbound: true, is_channel_ready: true,
3001 is_usable: true, is_public: true,
3002 inbound_htlc_minimum_msat: None,
3003 inbound_htlc_maximum_msat: None,
3005 feerate_sat_per_1000_weight: None,
3006 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3011 fn simple_route_test() {
3012 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3013 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3014 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3015 let scorer = ln_test_utils::TestScorer::new();
3016 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3017 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3019 // Simple route to 2 via 1
3021 let route_params = RouteParameters::from_payment_params_and_value(
3022 payment_params.clone(), 0);
3023 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3024 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3025 &Default::default(), &random_seed_bytes) {
3026 assert_eq!(err, "Cannot send a payment of 0 msat");
3027 } else { panic!(); }
3029 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3030 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3031 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3032 assert_eq!(route.paths[0].hops.len(), 2);
3034 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3035 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3036 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3037 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3038 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3039 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3041 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3042 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3043 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3044 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3045 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3046 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3050 fn invalid_first_hop_test() {
3051 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3052 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3053 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3054 let scorer = ln_test_utils::TestScorer::new();
3055 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3056 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3058 // Simple route to 2 via 1
3060 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3062 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3063 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3064 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3065 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3066 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3067 } else { panic!(); }
3069 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3070 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3071 assert_eq!(route.paths[0].hops.len(), 2);
3075 fn htlc_minimum_test() {
3076 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3077 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3078 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3079 let scorer = ln_test_utils::TestScorer::new();
3080 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3081 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3083 // Simple route to 2 via 1
3085 // Disable other paths
3086 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3087 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3088 short_channel_id: 12,
3090 flags: 2, // to disable
3091 cltv_expiry_delta: 0,
3092 htlc_minimum_msat: 0,
3093 htlc_maximum_msat: MAX_VALUE_MSAT,
3095 fee_proportional_millionths: 0,
3096 excess_data: Vec::new()
3098 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3099 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3100 short_channel_id: 3,
3102 flags: 2, // to disable
3103 cltv_expiry_delta: 0,
3104 htlc_minimum_msat: 0,
3105 htlc_maximum_msat: MAX_VALUE_MSAT,
3107 fee_proportional_millionths: 0,
3108 excess_data: Vec::new()
3110 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3111 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3112 short_channel_id: 13,
3114 flags: 2, // to disable
3115 cltv_expiry_delta: 0,
3116 htlc_minimum_msat: 0,
3117 htlc_maximum_msat: MAX_VALUE_MSAT,
3119 fee_proportional_millionths: 0,
3120 excess_data: Vec::new()
3122 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3123 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3124 short_channel_id: 6,
3126 flags: 2, // to disable
3127 cltv_expiry_delta: 0,
3128 htlc_minimum_msat: 0,
3129 htlc_maximum_msat: MAX_VALUE_MSAT,
3131 fee_proportional_millionths: 0,
3132 excess_data: Vec::new()
3134 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3135 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3136 short_channel_id: 7,
3138 flags: 2, // to disable
3139 cltv_expiry_delta: 0,
3140 htlc_minimum_msat: 0,
3141 htlc_maximum_msat: MAX_VALUE_MSAT,
3143 fee_proportional_millionths: 0,
3144 excess_data: Vec::new()
3147 // Check against amount_to_transfer_over_msat.
3148 // Set minimal HTLC of 200_000_000 msat.
3149 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3150 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3151 short_channel_id: 2,
3154 cltv_expiry_delta: 0,
3155 htlc_minimum_msat: 200_000_000,
3156 htlc_maximum_msat: MAX_VALUE_MSAT,
3158 fee_proportional_millionths: 0,
3159 excess_data: Vec::new()
3162 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3164 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3165 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3166 short_channel_id: 4,
3169 cltv_expiry_delta: 0,
3170 htlc_minimum_msat: 0,
3171 htlc_maximum_msat: 199_999_999,
3173 fee_proportional_millionths: 0,
3174 excess_data: Vec::new()
3177 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3178 let route_params = RouteParameters::from_payment_params_and_value(
3179 payment_params, 199_999_999);
3180 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3181 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3182 &Default::default(), &random_seed_bytes) {
3183 assert_eq!(err, "Failed to find a path to the given destination");
3184 } else { panic!(); }
3186 // Lift the restriction on the first hop.
3187 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3188 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3189 short_channel_id: 2,
3192 cltv_expiry_delta: 0,
3193 htlc_minimum_msat: 0,
3194 htlc_maximum_msat: MAX_VALUE_MSAT,
3196 fee_proportional_millionths: 0,
3197 excess_data: Vec::new()
3200 // A payment above the minimum should pass
3201 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3202 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3203 assert_eq!(route.paths[0].hops.len(), 2);
3207 fn htlc_minimum_overpay_test() {
3208 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3209 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3210 let config = UserConfig::default();
3211 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3212 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3214 let scorer = ln_test_utils::TestScorer::new();
3215 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3216 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3218 // A route to node#2 via two paths.
3219 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3220 // Thus, they can't send 60 without overpaying.
3221 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3222 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3223 short_channel_id: 2,
3226 cltv_expiry_delta: 0,
3227 htlc_minimum_msat: 35_000,
3228 htlc_maximum_msat: 40_000,
3230 fee_proportional_millionths: 0,
3231 excess_data: Vec::new()
3233 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3234 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3235 short_channel_id: 12,
3238 cltv_expiry_delta: 0,
3239 htlc_minimum_msat: 35_000,
3240 htlc_maximum_msat: 40_000,
3242 fee_proportional_millionths: 0,
3243 excess_data: Vec::new()
3247 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3248 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3249 short_channel_id: 13,
3252 cltv_expiry_delta: 0,
3253 htlc_minimum_msat: 0,
3254 htlc_maximum_msat: MAX_VALUE_MSAT,
3256 fee_proportional_millionths: 0,
3257 excess_data: Vec::new()
3259 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3260 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3261 short_channel_id: 4,
3264 cltv_expiry_delta: 0,
3265 htlc_minimum_msat: 0,
3266 htlc_maximum_msat: MAX_VALUE_MSAT,
3268 fee_proportional_millionths: 0,
3269 excess_data: Vec::new()
3272 // Disable other paths
3273 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3274 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3275 short_channel_id: 1,
3277 flags: 2, // to disable
3278 cltv_expiry_delta: 0,
3279 htlc_minimum_msat: 0,
3280 htlc_maximum_msat: MAX_VALUE_MSAT,
3282 fee_proportional_millionths: 0,
3283 excess_data: Vec::new()
3286 let mut route_params = RouteParameters::from_payment_params_and_value(
3287 payment_params.clone(), 60_000);
3288 route_params.max_total_routing_fee_msat = Some(15_000);
3289 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3290 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3291 // Overpay fees to hit htlc_minimum_msat.
3292 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3293 // TODO: this could be better balanced to overpay 10k and not 15k.
3294 assert_eq!(overpaid_fees, 15_000);
3296 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3297 // while taking even more fee to match htlc_minimum_msat.
3298 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3299 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3300 short_channel_id: 12,
3303 cltv_expiry_delta: 0,
3304 htlc_minimum_msat: 65_000,
3305 htlc_maximum_msat: 80_000,
3307 fee_proportional_millionths: 0,
3308 excess_data: Vec::new()
3310 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3311 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3312 short_channel_id: 2,
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()
3322 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3323 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3324 short_channel_id: 4,
3327 cltv_expiry_delta: 0,
3328 htlc_minimum_msat: 0,
3329 htlc_maximum_msat: MAX_VALUE_MSAT,
3331 fee_proportional_millionths: 100_000,
3332 excess_data: Vec::new()
3335 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3336 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3337 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3338 assert_eq!(route.paths.len(), 1);
3339 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3340 let fees = route.paths[0].hops[0].fee_msat;
3341 assert_eq!(fees, 5_000);
3343 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3344 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3345 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3346 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3347 // the other channel.
3348 assert_eq!(route.paths.len(), 1);
3349 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3350 let fees = route.paths[0].hops[0].fee_msat;
3351 assert_eq!(fees, 5_000);
3355 fn htlc_minimum_recipient_overpay_test() {
3356 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3357 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3358 let config = UserConfig::default();
3359 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3360 let scorer = ln_test_utils::TestScorer::new();
3361 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3362 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3364 // Route to node2 over a single path which requires overpaying the recipient themselves.
3366 // First disable all paths except the us -> node1 -> node2 path
3367 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3368 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3369 short_channel_id: 13,
3372 cltv_expiry_delta: 0,
3373 htlc_minimum_msat: 0,
3374 htlc_maximum_msat: 0,
3376 fee_proportional_millionths: 0,
3377 excess_data: Vec::new()
3380 // Set channel 4 to free but with a high htlc_minimum_msat
3381 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3382 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3383 short_channel_id: 4,
3386 cltv_expiry_delta: 0,
3387 htlc_minimum_msat: 15_000,
3388 htlc_maximum_msat: MAX_VALUE_MSAT,
3390 fee_proportional_millionths: 0,
3391 excess_data: Vec::new()
3394 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3395 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3396 // what we try to find a route for, so this test only just happens to work out to exactly
3398 let mut route_params = RouteParameters::from_payment_params_and_value(
3399 payment_params.clone(), 5_000);
3400 route_params.max_total_routing_fee_msat = Some(9_999);
3401 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3402 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3403 &Default::default(), &random_seed_bytes) {
3404 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3405 } else { panic!(); }
3407 let mut route_params = RouteParameters::from_payment_params_and_value(
3408 payment_params.clone(), 5_000);
3409 route_params.max_total_routing_fee_msat = Some(10_000);
3410 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3411 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3412 assert_eq!(route.get_total_fees(), 10_000);
3416 fn disable_channels_test() {
3417 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3418 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3419 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3420 let scorer = ln_test_utils::TestScorer::new();
3421 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3422 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3424 // // Disable channels 4 and 12 by flags=2
3425 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3426 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3427 short_channel_id: 4,
3429 flags: 2, // to disable
3430 cltv_expiry_delta: 0,
3431 htlc_minimum_msat: 0,
3432 htlc_maximum_msat: MAX_VALUE_MSAT,
3434 fee_proportional_millionths: 0,
3435 excess_data: Vec::new()
3437 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3438 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3439 short_channel_id: 12,
3441 flags: 2, // to disable
3442 cltv_expiry_delta: 0,
3443 htlc_minimum_msat: 0,
3444 htlc_maximum_msat: MAX_VALUE_MSAT,
3446 fee_proportional_millionths: 0,
3447 excess_data: Vec::new()
3450 // If all the channels require some features we don't understand, route should fail
3451 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
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 a path to the given destination");
3456 } else { panic!(); }
3458 // If we specify a channel to node7, that overrides our local channel view and that gets used
3459 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3460 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3461 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3462 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3463 &Default::default(), &random_seed_bytes).unwrap();
3464 assert_eq!(route.paths[0].hops.len(), 2);
3466 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3467 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3468 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3469 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3470 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3471 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3473 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3474 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3475 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3476 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3477 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3478 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3482 fn disable_node_test() {
3483 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3484 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3485 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3486 let scorer = ln_test_utils::TestScorer::new();
3487 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3488 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3490 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3491 let mut unknown_features = NodeFeatures::empty();
3492 unknown_features.set_unknown_feature_required();
3493 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3494 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3495 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3497 // If all nodes require some features we don't understand, route should fail
3498 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3499 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3500 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3501 &Default::default(), &random_seed_bytes) {
3502 assert_eq!(err, "Failed to find a path to the given destination");
3503 } else { panic!(); }
3505 // If we specify a channel to node7, that overrides our local channel view and that gets used
3506 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3507 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3508 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3509 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3510 &Default::default(), &random_seed_bytes).unwrap();
3511 assert_eq!(route.paths[0].hops.len(), 2);
3513 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3514 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3515 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3516 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3517 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3518 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3520 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3521 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3522 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3523 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3524 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3525 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3527 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3528 // naively) assume that the user checked the feature bits on the invoice, which override
3529 // the node_announcement.
3533 fn our_chans_test() {
3534 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3535 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3536 let scorer = ln_test_utils::TestScorer::new();
3537 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3538 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3540 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3541 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3542 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3543 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3544 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3545 assert_eq!(route.paths[0].hops.len(), 3);
3547 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3548 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3549 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3550 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3551 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3552 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3554 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3555 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3556 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3557 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3558 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3559 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3561 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3562 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3563 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3564 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3565 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3566 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3568 // If we specify a channel to node7, that overrides our local channel view and that gets used
3569 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3570 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3571 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3572 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3573 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3574 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3575 &Default::default(), &random_seed_bytes).unwrap();
3576 assert_eq!(route.paths[0].hops.len(), 2);
3578 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3579 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3580 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3581 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3582 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3583 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3585 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3586 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3587 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3588 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3589 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3590 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3593 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3594 let zero_fees = RoutingFees {
3596 proportional_millionths: 0,
3598 vec![RouteHint(vec![RouteHintHop {
3599 src_node_id: nodes[3],
3600 short_channel_id: 8,
3602 cltv_expiry_delta: (8 << 4) | 1,
3603 htlc_minimum_msat: None,
3604 htlc_maximum_msat: None,
3606 ]), RouteHint(vec![RouteHintHop {
3607 src_node_id: nodes[4],
3608 short_channel_id: 9,
3611 proportional_millionths: 0,
3613 cltv_expiry_delta: (9 << 4) | 1,
3614 htlc_minimum_msat: None,
3615 htlc_maximum_msat: None,
3616 }]), RouteHint(vec![RouteHintHop {
3617 src_node_id: nodes[5],
3618 short_channel_id: 10,
3620 cltv_expiry_delta: (10 << 4) | 1,
3621 htlc_minimum_msat: None,
3622 htlc_maximum_msat: None,
3626 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3627 let zero_fees = RoutingFees {
3629 proportional_millionths: 0,
3631 vec![RouteHint(vec![RouteHintHop {
3632 src_node_id: nodes[2],
3633 short_channel_id: 5,
3636 proportional_millionths: 0,
3638 cltv_expiry_delta: (5 << 4) | 1,
3639 htlc_minimum_msat: None,
3640 htlc_maximum_msat: None,
3642 src_node_id: nodes[3],
3643 short_channel_id: 8,
3645 cltv_expiry_delta: (8 << 4) | 1,
3646 htlc_minimum_msat: None,
3647 htlc_maximum_msat: None,
3649 ]), RouteHint(vec![RouteHintHop {
3650 src_node_id: nodes[4],
3651 short_channel_id: 9,
3654 proportional_millionths: 0,
3656 cltv_expiry_delta: (9 << 4) | 1,
3657 htlc_minimum_msat: None,
3658 htlc_maximum_msat: None,
3659 }]), RouteHint(vec![RouteHintHop {
3660 src_node_id: nodes[5],
3661 short_channel_id: 10,
3663 cltv_expiry_delta: (10 << 4) | 1,
3664 htlc_minimum_msat: None,
3665 htlc_maximum_msat: None,
3670 fn partial_route_hint_test() {
3671 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3672 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3673 let scorer = ln_test_utils::TestScorer::new();
3674 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3675 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3677 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3678 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3679 // RouteHint may be partially used by the algo to build the best path.
3681 // First check that last hop can't have its source as the payee.
3682 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3683 src_node_id: nodes[6],
3684 short_channel_id: 8,
3687 proportional_millionths: 0,
3689 cltv_expiry_delta: (8 << 4) | 1,
3690 htlc_minimum_msat: None,
3691 htlc_maximum_msat: None,
3694 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3695 invalid_last_hops.push(invalid_last_hop);
3697 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3698 .with_route_hints(invalid_last_hops).unwrap();
3699 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3700 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3701 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3702 &Default::default(), &random_seed_bytes) {
3703 assert_eq!(err, "Route hint cannot have the payee as the source.");
3704 } else { panic!(); }
3707 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3708 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3709 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3710 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3711 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3712 assert_eq!(route.paths[0].hops.len(), 5);
3714 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3715 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3716 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3717 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3718 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3719 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3721 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3722 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3723 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3724 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3725 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3726 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3728 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3729 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3730 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3731 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3732 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3733 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3735 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3736 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3737 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3738 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3739 // If we have a peer in the node map, we'll use their features here since we don't have
3740 // a way of figuring out their features from the invoice:
3741 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3742 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3744 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3745 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3746 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3747 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3748 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3749 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3752 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3753 let zero_fees = RoutingFees {
3755 proportional_millionths: 0,
3757 vec![RouteHint(vec![RouteHintHop {
3758 src_node_id: nodes[3],
3759 short_channel_id: 8,
3761 cltv_expiry_delta: (8 << 4) | 1,
3762 htlc_minimum_msat: None,
3763 htlc_maximum_msat: None,
3764 }]), RouteHint(vec![
3766 ]), RouteHint(vec![RouteHintHop {
3767 src_node_id: nodes[5],
3768 short_channel_id: 10,
3770 cltv_expiry_delta: (10 << 4) | 1,
3771 htlc_minimum_msat: None,
3772 htlc_maximum_msat: None,
3777 fn ignores_empty_last_hops_test() {
3778 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3779 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3780 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3781 let scorer = ln_test_utils::TestScorer::new();
3782 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3783 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3785 // Test handling of an empty RouteHint passed in Invoice.
3786 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3787 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3788 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3789 assert_eq!(route.paths[0].hops.len(), 5);
3791 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3792 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3793 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3794 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3795 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3796 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3798 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3799 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3800 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3801 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3802 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3803 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3805 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3806 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3807 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3808 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3809 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3810 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3812 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3813 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3814 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3815 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3816 // If we have a peer in the node map, we'll use their features here since we don't have
3817 // a way of figuring out their features from the invoice:
3818 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3819 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3821 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3822 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3823 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3824 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3825 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3826 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3829 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3831 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3832 let zero_fees = RoutingFees {
3834 proportional_millionths: 0,
3836 vec![RouteHint(vec![RouteHintHop {
3837 src_node_id: hint_hops[0],
3838 short_channel_id: 0xff00,
3841 proportional_millionths: 0,
3843 cltv_expiry_delta: (5 << 4) | 1,
3844 htlc_minimum_msat: None,
3845 htlc_maximum_msat: None,
3847 src_node_id: hint_hops[1],
3848 short_channel_id: 0xff01,
3850 cltv_expiry_delta: (8 << 4) | 1,
3851 htlc_minimum_msat: None,
3852 htlc_maximum_msat: None,
3857 fn multi_hint_last_hops_test() {
3858 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3859 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3860 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3861 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3862 let scorer = ln_test_utils::TestScorer::new();
3863 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3864 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3865 // Test through channels 2, 3, 0xff00, 0xff01.
3866 // Test shows that multiple hop hints are considered.
3868 // Disabling channels 6 & 7 by flags=2
3869 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3870 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3871 short_channel_id: 6,
3873 flags: 2, // to disable
3874 cltv_expiry_delta: 0,
3875 htlc_minimum_msat: 0,
3876 htlc_maximum_msat: MAX_VALUE_MSAT,
3878 fee_proportional_millionths: 0,
3879 excess_data: Vec::new()
3881 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3882 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3883 short_channel_id: 7,
3885 flags: 2, // to disable
3886 cltv_expiry_delta: 0,
3887 htlc_minimum_msat: 0,
3888 htlc_maximum_msat: MAX_VALUE_MSAT,
3890 fee_proportional_millionths: 0,
3891 excess_data: Vec::new()
3894 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3895 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3896 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3897 assert_eq!(route.paths[0].hops.len(), 4);
3899 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3900 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3901 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3902 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3903 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3904 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3906 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3907 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3908 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3909 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3910 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3911 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3913 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3914 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3915 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3916 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3917 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3918 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3920 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3921 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3922 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3923 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3924 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3925 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3929 fn private_multi_hint_last_hops_test() {
3930 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3931 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3933 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3934 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3936 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3937 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3938 let scorer = ln_test_utils::TestScorer::new();
3939 // Test through channels 2, 3, 0xff00, 0xff01.
3940 // Test shows that multiple hop hints are considered.
3942 // Disabling channels 6 & 7 by flags=2
3943 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3944 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3945 short_channel_id: 6,
3947 flags: 2, // to disable
3948 cltv_expiry_delta: 0,
3949 htlc_minimum_msat: 0,
3950 htlc_maximum_msat: MAX_VALUE_MSAT,
3952 fee_proportional_millionths: 0,
3953 excess_data: Vec::new()
3955 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3956 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3957 short_channel_id: 7,
3959 flags: 2, // to disable
3960 cltv_expiry_delta: 0,
3961 htlc_minimum_msat: 0,
3962 htlc_maximum_msat: MAX_VALUE_MSAT,
3964 fee_proportional_millionths: 0,
3965 excess_data: Vec::new()
3968 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3969 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3970 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
3971 assert_eq!(route.paths[0].hops.len(), 4);
3973 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3974 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3975 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3976 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3977 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3978 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3980 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3981 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3982 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3983 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3984 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3985 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3987 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3988 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3989 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3990 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3991 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3992 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3994 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3995 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3996 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3997 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3998 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3999 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4002 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4003 let zero_fees = RoutingFees {
4005 proportional_millionths: 0,
4007 vec![RouteHint(vec![RouteHintHop {
4008 src_node_id: nodes[4],
4009 short_channel_id: 11,
4011 cltv_expiry_delta: (11 << 4) | 1,
4012 htlc_minimum_msat: None,
4013 htlc_maximum_msat: None,
4015 src_node_id: nodes[3],
4016 short_channel_id: 8,
4018 cltv_expiry_delta: (8 << 4) | 1,
4019 htlc_minimum_msat: None,
4020 htlc_maximum_msat: None,
4021 }]), RouteHint(vec![RouteHintHop {
4022 src_node_id: nodes[4],
4023 short_channel_id: 9,
4026 proportional_millionths: 0,
4028 cltv_expiry_delta: (9 << 4) | 1,
4029 htlc_minimum_msat: None,
4030 htlc_maximum_msat: None,
4031 }]), RouteHint(vec![RouteHintHop {
4032 src_node_id: nodes[5],
4033 short_channel_id: 10,
4035 cltv_expiry_delta: (10 << 4) | 1,
4036 htlc_minimum_msat: None,
4037 htlc_maximum_msat: None,
4042 fn last_hops_with_public_channel_test() {
4043 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4044 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4045 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4046 let scorer = ln_test_utils::TestScorer::new();
4047 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4048 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4049 // This test shows that public routes can be present in the invoice
4050 // which would be handled in the same manner.
4052 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4053 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4054 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4055 assert_eq!(route.paths[0].hops.len(), 5);
4057 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4058 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4059 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4060 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4061 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4062 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4064 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4065 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4066 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4067 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4068 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4069 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4071 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4072 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4073 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4074 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4075 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4076 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4078 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4079 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4080 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4081 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4082 // If we have a peer in the node map, we'll use their features here since we don't have
4083 // a way of figuring out their features from the invoice:
4084 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4085 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4087 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4088 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4089 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4090 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4091 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4092 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4096 fn our_chans_last_hop_connect_test() {
4097 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4098 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4099 let scorer = ln_test_utils::TestScorer::new();
4100 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4101 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4103 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4104 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4105 let mut last_hops = last_hops(&nodes);
4106 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4107 .with_route_hints(last_hops.clone()).unwrap();
4108 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4109 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4110 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4111 &Default::default(), &random_seed_bytes).unwrap();
4112 assert_eq!(route.paths[0].hops.len(), 2);
4114 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4115 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4116 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4117 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4118 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4119 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4121 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4122 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4123 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4124 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4125 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4126 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4128 last_hops[0].0[0].fees.base_msat = 1000;
4130 // Revert to via 6 as the fee on 8 goes up
4131 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4132 .with_route_hints(last_hops).unwrap();
4133 let route_params = RouteParameters::from_payment_params_and_value(
4134 payment_params.clone(), 100);
4135 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4136 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4137 assert_eq!(route.paths[0].hops.len(), 4);
4139 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4140 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4141 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4142 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4143 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4144 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4146 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4147 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4148 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4149 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4150 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4151 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4153 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4154 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4155 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4156 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4157 // If we have a peer in the node map, we'll use their features here since we don't have
4158 // a way of figuring out their features from the invoice:
4159 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4160 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4162 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4163 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4164 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4165 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4166 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4167 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4169 // ...but still use 8 for larger payments as 6 has a variable feerate
4170 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4171 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4172 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4173 assert_eq!(route.paths[0].hops.len(), 5);
4175 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4176 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4177 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4178 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4179 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4180 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4182 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4183 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4184 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4185 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4186 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4187 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4189 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4190 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4191 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4192 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4193 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4194 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4196 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4197 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4198 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4199 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4200 // If we have a peer in the node map, we'll use their features here since we don't have
4201 // a way of figuring out their features from the invoice:
4202 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4203 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4205 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4206 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4207 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4208 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4209 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4210 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4213 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> {
4214 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4215 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4216 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4218 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4219 let last_hops = RouteHint(vec![RouteHintHop {
4220 src_node_id: middle_node_id,
4221 short_channel_id: 8,
4224 proportional_millionths: last_hop_fee_prop,
4226 cltv_expiry_delta: (8 << 4) | 1,
4227 htlc_minimum_msat: None,
4228 htlc_maximum_msat: last_hop_htlc_max,
4230 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4231 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4232 let scorer = ln_test_utils::TestScorer::new();
4233 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4234 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4235 let logger = ln_test_utils::TestLogger::new();
4236 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4237 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4238 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4239 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4240 &random_seed_bytes);
4245 fn unannounced_path_test() {
4246 // We should be able to send a payment to a destination without any help of a routing graph
4247 // if we have a channel with a common counterparty that appears in the first and last hop
4249 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4251 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4252 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4253 assert_eq!(route.paths[0].hops.len(), 2);
4255 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4256 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4257 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4258 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4259 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4260 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4262 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4263 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4264 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4265 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4266 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4267 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4271 fn overflow_unannounced_path_test_liquidity_underflow() {
4272 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4273 // the last-hop had a fee which overflowed a u64, we'd panic.
4274 // This was due to us adding the first-hop from us unconditionally, causing us to think
4275 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4276 // In this test, we previously hit a subtraction underflow due to having less available
4277 // liquidity at the last hop than 0.
4278 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());
4282 fn overflow_unannounced_path_test_feerate_overflow() {
4283 // This tests for the same case as above, except instead of hitting a subtraction
4284 // underflow, we hit a case where the fee charged at a hop overflowed.
4285 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());
4289 fn available_amount_while_routing_test() {
4290 // Tests whether we choose the correct available channel amount while routing.
4292 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4293 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4294 let scorer = ln_test_utils::TestScorer::new();
4295 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4296 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4297 let config = UserConfig::default();
4298 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4299 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4302 // We will use a simple single-path route from
4303 // our node to node2 via node0: channels {1, 3}.
4305 // First disable all other paths.
4306 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4307 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4308 short_channel_id: 2,
4311 cltv_expiry_delta: 0,
4312 htlc_minimum_msat: 0,
4313 htlc_maximum_msat: 100_000,
4315 fee_proportional_millionths: 0,
4316 excess_data: Vec::new()
4318 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4319 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4320 short_channel_id: 12,
4323 cltv_expiry_delta: 0,
4324 htlc_minimum_msat: 0,
4325 htlc_maximum_msat: 100_000,
4327 fee_proportional_millionths: 0,
4328 excess_data: Vec::new()
4331 // Make the first channel (#1) very permissive,
4332 // and we will be testing all limits on the second channel.
4333 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4334 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4335 short_channel_id: 1,
4338 cltv_expiry_delta: 0,
4339 htlc_minimum_msat: 0,
4340 htlc_maximum_msat: 1_000_000_000,
4342 fee_proportional_millionths: 0,
4343 excess_data: Vec::new()
4346 // First, let's see if routing works if we have absolutely no idea about the available amount.
4347 // In this case, it should be set to 250_000 sats.
4348 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4349 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4350 short_channel_id: 3,
4353 cltv_expiry_delta: 0,
4354 htlc_minimum_msat: 0,
4355 htlc_maximum_msat: 250_000_000,
4357 fee_proportional_millionths: 0,
4358 excess_data: Vec::new()
4362 // Attempt to route more than available results in a failure.
4363 let route_params = RouteParameters::from_payment_params_and_value(
4364 payment_params.clone(), 250_000_001);
4365 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4366 &our_id, &route_params, &network_graph.read_only(), None,
4367 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4368 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4369 } else { panic!(); }
4373 // Now, attempt to route an exact amount we have should be fine.
4374 let route_params = RouteParameters::from_payment_params_and_value(
4375 payment_params.clone(), 250_000_000);
4376 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4377 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4378 assert_eq!(route.paths.len(), 1);
4379 let path = route.paths.last().unwrap();
4380 assert_eq!(path.hops.len(), 2);
4381 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4382 assert_eq!(path.final_value_msat(), 250_000_000);
4385 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4386 // Disable channel #1 and use another first hop.
4387 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4388 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4389 short_channel_id: 1,
4392 cltv_expiry_delta: 0,
4393 htlc_minimum_msat: 0,
4394 htlc_maximum_msat: 1_000_000_000,
4396 fee_proportional_millionths: 0,
4397 excess_data: Vec::new()
4400 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4401 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4404 // Attempt to route more than available results in a failure.
4405 let route_params = RouteParameters::from_payment_params_and_value(
4406 payment_params.clone(), 200_000_001);
4407 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4408 &our_id, &route_params, &network_graph.read_only(),
4409 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4410 &Default::default(), &random_seed_bytes) {
4411 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4412 } else { panic!(); }
4416 // Now, attempt to route an exact amount we have should be fine.
4417 let route_params = RouteParameters::from_payment_params_and_value(
4418 payment_params.clone(), 200_000_000);
4419 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4420 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4421 &Default::default(), &random_seed_bytes).unwrap();
4422 assert_eq!(route.paths.len(), 1);
4423 let path = route.paths.last().unwrap();
4424 assert_eq!(path.hops.len(), 2);
4425 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4426 assert_eq!(path.final_value_msat(), 200_000_000);
4429 // Enable channel #1 back.
4430 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4431 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4432 short_channel_id: 1,
4435 cltv_expiry_delta: 0,
4436 htlc_minimum_msat: 0,
4437 htlc_maximum_msat: 1_000_000_000,
4439 fee_proportional_millionths: 0,
4440 excess_data: Vec::new()
4444 // Now let's see if routing works if we know only htlc_maximum_msat.
4445 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4446 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4447 short_channel_id: 3,
4450 cltv_expiry_delta: 0,
4451 htlc_minimum_msat: 0,
4452 htlc_maximum_msat: 15_000,
4454 fee_proportional_millionths: 0,
4455 excess_data: Vec::new()
4459 // Attempt to route more than available results in a failure.
4460 let route_params = RouteParameters::from_payment_params_and_value(
4461 payment_params.clone(), 15_001);
4462 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4463 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4464 &scorer, &Default::default(), &random_seed_bytes) {
4465 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4466 } else { panic!(); }
4470 // Now, attempt to route an exact amount we have should be fine.
4471 let route_params = RouteParameters::from_payment_params_and_value(
4472 payment_params.clone(), 15_000);
4473 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4474 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4475 assert_eq!(route.paths.len(), 1);
4476 let path = route.paths.last().unwrap();
4477 assert_eq!(path.hops.len(), 2);
4478 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4479 assert_eq!(path.final_value_msat(), 15_000);
4482 // Now let's see if routing works if we know only capacity from the UTXO.
4484 // We can't change UTXO capacity on the fly, so we'll disable
4485 // the existing channel and add another one with the capacity we need.
4486 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4487 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4488 short_channel_id: 3,
4491 cltv_expiry_delta: 0,
4492 htlc_minimum_msat: 0,
4493 htlc_maximum_msat: MAX_VALUE_MSAT,
4495 fee_proportional_millionths: 0,
4496 excess_data: Vec::new()
4499 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4500 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4501 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4502 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4503 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4505 *chain_monitor.utxo_ret.lock().unwrap() =
4506 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4507 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4509 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4510 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4511 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4512 short_channel_id: 333,
4515 cltv_expiry_delta: (3 << 4) | 1,
4516 htlc_minimum_msat: 0,
4517 htlc_maximum_msat: 15_000,
4519 fee_proportional_millionths: 0,
4520 excess_data: Vec::new()
4522 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4523 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4524 short_channel_id: 333,
4527 cltv_expiry_delta: (3 << 4) | 2,
4528 htlc_minimum_msat: 0,
4529 htlc_maximum_msat: 15_000,
4531 fee_proportional_millionths: 0,
4532 excess_data: Vec::new()
4536 // Attempt to route more than available results in a failure.
4537 let route_params = RouteParameters::from_payment_params_and_value(
4538 payment_params.clone(), 15_001);
4539 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4540 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4541 &scorer, &Default::default(), &random_seed_bytes) {
4542 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4543 } else { panic!(); }
4547 // Now, attempt to route an exact amount we have should be fine.
4548 let route_params = RouteParameters::from_payment_params_and_value(
4549 payment_params.clone(), 15_000);
4550 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4551 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4552 assert_eq!(route.paths.len(), 1);
4553 let path = route.paths.last().unwrap();
4554 assert_eq!(path.hops.len(), 2);
4555 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4556 assert_eq!(path.final_value_msat(), 15_000);
4559 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4560 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4561 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4562 short_channel_id: 333,
4565 cltv_expiry_delta: 0,
4566 htlc_minimum_msat: 0,
4567 htlc_maximum_msat: 10_000,
4569 fee_proportional_millionths: 0,
4570 excess_data: Vec::new()
4574 // Attempt to route more than available results in a failure.
4575 let route_params = RouteParameters::from_payment_params_and_value(
4576 payment_params.clone(), 10_001);
4577 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4578 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4579 &scorer, &Default::default(), &random_seed_bytes) {
4580 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4581 } else { panic!(); }
4585 // Now, attempt to route an exact amount we have should be fine.
4586 let route_params = RouteParameters::from_payment_params_and_value(
4587 payment_params.clone(), 10_000);
4588 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4589 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4590 assert_eq!(route.paths.len(), 1);
4591 let path = route.paths.last().unwrap();
4592 assert_eq!(path.hops.len(), 2);
4593 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4594 assert_eq!(path.final_value_msat(), 10_000);
4599 fn available_liquidity_last_hop_test() {
4600 // Check that available liquidity properly limits the path even when only
4601 // one of the latter hops is limited.
4602 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4603 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4604 let scorer = ln_test_utils::TestScorer::new();
4605 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4606 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4607 let config = UserConfig::default();
4608 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4609 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4612 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4613 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4614 // Total capacity: 50 sats.
4616 // Disable other potential paths.
4617 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4618 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4619 short_channel_id: 2,
4622 cltv_expiry_delta: 0,
4623 htlc_minimum_msat: 0,
4624 htlc_maximum_msat: 100_000,
4626 fee_proportional_millionths: 0,
4627 excess_data: Vec::new()
4629 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4630 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4631 short_channel_id: 7,
4634 cltv_expiry_delta: 0,
4635 htlc_minimum_msat: 0,
4636 htlc_maximum_msat: 100_000,
4638 fee_proportional_millionths: 0,
4639 excess_data: Vec::new()
4644 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4645 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4646 short_channel_id: 12,
4649 cltv_expiry_delta: 0,
4650 htlc_minimum_msat: 0,
4651 htlc_maximum_msat: 100_000,
4653 fee_proportional_millionths: 0,
4654 excess_data: Vec::new()
4656 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4657 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4658 short_channel_id: 13,
4661 cltv_expiry_delta: 0,
4662 htlc_minimum_msat: 0,
4663 htlc_maximum_msat: 100_000,
4665 fee_proportional_millionths: 0,
4666 excess_data: Vec::new()
4669 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4670 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4671 short_channel_id: 6,
4674 cltv_expiry_delta: 0,
4675 htlc_minimum_msat: 0,
4676 htlc_maximum_msat: 50_000,
4678 fee_proportional_millionths: 0,
4679 excess_data: Vec::new()
4681 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4682 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4683 short_channel_id: 11,
4686 cltv_expiry_delta: 0,
4687 htlc_minimum_msat: 0,
4688 htlc_maximum_msat: 100_000,
4690 fee_proportional_millionths: 0,
4691 excess_data: Vec::new()
4694 // Attempt to route more than available results in a failure.
4695 let route_params = RouteParameters::from_payment_params_and_value(
4696 payment_params.clone(), 60_000);
4697 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4698 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4699 &scorer, &Default::default(), &random_seed_bytes) {
4700 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4701 } else { panic!(); }
4705 // Now, attempt to route 49 sats (just a bit below the capacity).
4706 let route_params = RouteParameters::from_payment_params_and_value(
4707 payment_params.clone(), 49_000);
4708 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4709 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4710 assert_eq!(route.paths.len(), 1);
4711 let mut total_amount_paid_msat = 0;
4712 for path in &route.paths {
4713 assert_eq!(path.hops.len(), 4);
4714 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4715 total_amount_paid_msat += path.final_value_msat();
4717 assert_eq!(total_amount_paid_msat, 49_000);
4721 // Attempt to route an exact amount is also fine
4722 let route_params = RouteParameters::from_payment_params_and_value(
4723 payment_params, 50_000);
4724 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4725 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4726 assert_eq!(route.paths.len(), 1);
4727 let mut total_amount_paid_msat = 0;
4728 for path in &route.paths {
4729 assert_eq!(path.hops.len(), 4);
4730 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4731 total_amount_paid_msat += path.final_value_msat();
4733 assert_eq!(total_amount_paid_msat, 50_000);
4738 fn ignore_fee_first_hop_test() {
4739 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4740 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4741 let scorer = ln_test_utils::TestScorer::new();
4742 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4743 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4744 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4746 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4747 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4748 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4749 short_channel_id: 1,
4752 cltv_expiry_delta: 0,
4753 htlc_minimum_msat: 0,
4754 htlc_maximum_msat: 100_000,
4755 fee_base_msat: 1_000_000,
4756 fee_proportional_millionths: 0,
4757 excess_data: Vec::new()
4759 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4760 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4761 short_channel_id: 3,
4764 cltv_expiry_delta: 0,
4765 htlc_minimum_msat: 0,
4766 htlc_maximum_msat: 50_000,
4768 fee_proportional_millionths: 0,
4769 excess_data: Vec::new()
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(), 2);
4781 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4782 total_amount_paid_msat += path.final_value_msat();
4784 assert_eq!(total_amount_paid_msat, 50_000);
4789 fn simple_mpp_route_test() {
4790 let (secp_ctx, _, _, _, _) = build_graph();
4791 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4792 let config = UserConfig::default();
4793 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4794 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4796 do_simple_mpp_route_test(clear_payment_params);
4798 // MPP to a 1-hop blinded path for nodes[2]
4799 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
4800 let blinded_path = BlindedPath {
4801 introduction_node_id: nodes[2],
4802 blinding_point: ln_test_utils::pubkey(42),
4803 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4805 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4807 fee_proportional_millionths: 0,
4808 htlc_minimum_msat: 0,
4809 htlc_maximum_msat: 0,
4810 cltv_expiry_delta: 0,
4811 features: BlindedHopFeatures::empty(),
4813 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4814 .with_bolt12_features(bolt12_features.clone()).unwrap();
4815 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4817 // MPP to 3 2-hop blinded paths
4818 let mut blinded_path_node_0 = blinded_path.clone();
4819 blinded_path_node_0.introduction_node_id = nodes[0];
4820 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4821 let mut node_0_payinfo = blinded_payinfo.clone();
4822 node_0_payinfo.htlc_maximum_msat = 50_000;
4824 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4825 blinded_path_node_7.introduction_node_id = nodes[7];
4826 let mut node_7_payinfo = blinded_payinfo.clone();
4827 node_7_payinfo.htlc_maximum_msat = 60_000;
4829 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4830 blinded_path_node_1.introduction_node_id = nodes[1];
4831 let mut node_1_payinfo = blinded_payinfo.clone();
4832 node_1_payinfo.htlc_maximum_msat = 180_000;
4834 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4836 (node_0_payinfo, blinded_path_node_0),
4837 (node_7_payinfo, blinded_path_node_7),
4838 (node_1_payinfo, blinded_path_node_1)
4840 .with_bolt12_features(bolt12_features).unwrap();
4841 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4845 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4846 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4847 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4848 let scorer = ln_test_utils::TestScorer::new();
4849 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4850 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4852 // We need a route consisting of 3 paths:
4853 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4854 // To achieve this, the amount being transferred should be around
4855 // the total capacity of these 3 paths.
4857 // First, we set limits on these (previously unlimited) channels.
4858 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4860 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4861 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4862 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4863 short_channel_id: 1,
4866 cltv_expiry_delta: 0,
4867 htlc_minimum_msat: 0,
4868 htlc_maximum_msat: 100_000,
4870 fee_proportional_millionths: 0,
4871 excess_data: Vec::new()
4873 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4874 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4875 short_channel_id: 3,
4878 cltv_expiry_delta: 0,
4879 htlc_minimum_msat: 0,
4880 htlc_maximum_msat: 50_000,
4882 fee_proportional_millionths: 0,
4883 excess_data: Vec::new()
4886 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4887 // (total limit 60).
4888 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4889 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4890 short_channel_id: 12,
4893 cltv_expiry_delta: 0,
4894 htlc_minimum_msat: 0,
4895 htlc_maximum_msat: 60_000,
4897 fee_proportional_millionths: 0,
4898 excess_data: Vec::new()
4900 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4901 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4902 short_channel_id: 13,
4905 cltv_expiry_delta: 0,
4906 htlc_minimum_msat: 0,
4907 htlc_maximum_msat: 60_000,
4909 fee_proportional_millionths: 0,
4910 excess_data: Vec::new()
4913 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4914 // (total capacity 180 sats).
4915 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4916 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4917 short_channel_id: 2,
4920 cltv_expiry_delta: 0,
4921 htlc_minimum_msat: 0,
4922 htlc_maximum_msat: 200_000,
4924 fee_proportional_millionths: 0,
4925 excess_data: Vec::new()
4927 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4928 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4929 short_channel_id: 4,
4932 cltv_expiry_delta: 0,
4933 htlc_minimum_msat: 0,
4934 htlc_maximum_msat: 180_000,
4936 fee_proportional_millionths: 0,
4937 excess_data: Vec::new()
4941 // Attempt to route more than available results in a failure.
4942 let route_params = RouteParameters::from_payment_params_and_value(
4943 payment_params.clone(), 300_000);
4944 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4945 &our_id, &route_params, &network_graph.read_only(), None,
4946 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4947 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4948 } else { panic!(); }
4952 // Attempt to route while setting max_path_count to 0 results in a failure.
4953 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4954 let route_params = RouteParameters::from_payment_params_and_value(
4955 zero_payment_params, 100);
4956 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4957 &our_id, &route_params, &network_graph.read_only(), None,
4958 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4959 assert_eq!(err, "Can't find a route with no paths allowed.");
4960 } else { panic!(); }
4964 // Attempt to route while setting max_path_count to 3 results in a failure.
4965 // This is the case because the minimal_value_contribution_msat would require each path
4966 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4967 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4968 let route_params = RouteParameters::from_payment_params_and_value(
4969 fail_payment_params, 250_000);
4970 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4971 &our_id, &route_params, &network_graph.read_only(), None,
4972 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4973 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4974 } else { panic!(); }
4978 // Now, attempt to route 250 sats (just a bit below the capacity).
4979 // Our algorithm should provide us with these 3 paths.
4980 let route_params = RouteParameters::from_payment_params_and_value(
4981 payment_params.clone(), 250_000);
4982 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4983 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4984 assert_eq!(route.paths.len(), 3);
4985 let mut total_amount_paid_msat = 0;
4986 for path in &route.paths {
4987 if let Some(bt) = &path.blinded_tail {
4988 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4990 assert_eq!(path.hops.len(), 2);
4991 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4993 total_amount_paid_msat += path.final_value_msat();
4995 assert_eq!(total_amount_paid_msat, 250_000);
4999 // Attempt to route an exact amount is also fine
5000 let route_params = RouteParameters::from_payment_params_and_value(
5001 payment_params.clone(), 290_000);
5002 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5003 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5004 assert_eq!(route.paths.len(), 3);
5005 let mut total_amount_paid_msat = 0;
5006 for path in &route.paths {
5007 if payment_params.payee.blinded_route_hints().len() != 0 {
5008 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5009 if let Some(bt) = &path.blinded_tail {
5010 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5011 if bt.hops.len() > 1 {
5012 assert_eq!(path.hops.last().unwrap().pubkey,
5013 payment_params.payee.blinded_route_hints().iter()
5014 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5015 .map(|(_, p)| p.introduction_node_id).unwrap());
5017 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5020 assert_eq!(path.hops.len(), 2);
5021 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5023 total_amount_paid_msat += path.final_value_msat();
5025 assert_eq!(total_amount_paid_msat, 290_000);
5030 fn long_mpp_route_test() {
5031 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5032 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5033 let scorer = ln_test_utils::TestScorer::new();
5034 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5035 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5036 let config = UserConfig::default();
5037 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5038 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5041 // We need a route consisting of 3 paths:
5042 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5043 // Note that these paths overlap (channels 5, 12, 13).
5044 // We will route 300 sats.
5045 // Each path will have 100 sats capacity, those channels which
5046 // are used twice will have 200 sats capacity.
5048 // Disable other potential paths.
5049 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5050 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5051 short_channel_id: 2,
5054 cltv_expiry_delta: 0,
5055 htlc_minimum_msat: 0,
5056 htlc_maximum_msat: 100_000,
5058 fee_proportional_millionths: 0,
5059 excess_data: Vec::new()
5061 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5062 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5063 short_channel_id: 7,
5066 cltv_expiry_delta: 0,
5067 htlc_minimum_msat: 0,
5068 htlc_maximum_msat: 100_000,
5070 fee_proportional_millionths: 0,
5071 excess_data: Vec::new()
5074 // Path via {node0, node2} is channels {1, 3, 5}.
5075 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5076 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5077 short_channel_id: 1,
5080 cltv_expiry_delta: 0,
5081 htlc_minimum_msat: 0,
5082 htlc_maximum_msat: 100_000,
5084 fee_proportional_millionths: 0,
5085 excess_data: Vec::new()
5087 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5088 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5089 short_channel_id: 3,
5092 cltv_expiry_delta: 0,
5093 htlc_minimum_msat: 0,
5094 htlc_maximum_msat: 100_000,
5096 fee_proportional_millionths: 0,
5097 excess_data: Vec::new()
5100 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5101 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5102 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5103 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5104 short_channel_id: 5,
5107 cltv_expiry_delta: 0,
5108 htlc_minimum_msat: 0,
5109 htlc_maximum_msat: 200_000,
5111 fee_proportional_millionths: 0,
5112 excess_data: Vec::new()
5115 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5116 // Add 100 sats to the capacities of {12, 13}, because these channels
5117 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5118 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5119 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5120 short_channel_id: 12,
5123 cltv_expiry_delta: 0,
5124 htlc_minimum_msat: 0,
5125 htlc_maximum_msat: 200_000,
5127 fee_proportional_millionths: 0,
5128 excess_data: Vec::new()
5130 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5131 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5132 short_channel_id: 13,
5135 cltv_expiry_delta: 0,
5136 htlc_minimum_msat: 0,
5137 htlc_maximum_msat: 200_000,
5139 fee_proportional_millionths: 0,
5140 excess_data: Vec::new()
5143 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5144 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5145 short_channel_id: 6,
5148 cltv_expiry_delta: 0,
5149 htlc_minimum_msat: 0,
5150 htlc_maximum_msat: 100_000,
5152 fee_proportional_millionths: 0,
5153 excess_data: Vec::new()
5155 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5156 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5157 short_channel_id: 11,
5160 cltv_expiry_delta: 0,
5161 htlc_minimum_msat: 0,
5162 htlc_maximum_msat: 100_000,
5164 fee_proportional_millionths: 0,
5165 excess_data: Vec::new()
5168 // Path via {node7, node2} is channels {12, 13, 5}.
5169 // We already limited them to 200 sats (they are used twice for 100 sats).
5170 // Nothing to do here.
5173 // Attempt to route more than available results in a failure.
5174 let route_params = RouteParameters::from_payment_params_and_value(
5175 payment_params.clone(), 350_000);
5176 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5177 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5178 &scorer, &Default::default(), &random_seed_bytes) {
5179 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5180 } else { panic!(); }
5184 // Now, attempt to route 300 sats (exact amount we can route).
5185 // Our algorithm should provide us with these 3 paths, 100 sats each.
5186 let route_params = RouteParameters::from_payment_params_and_value(
5187 payment_params, 300_000);
5188 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5189 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5190 assert_eq!(route.paths.len(), 3);
5192 let mut total_amount_paid_msat = 0;
5193 for path in &route.paths {
5194 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5195 total_amount_paid_msat += path.final_value_msat();
5197 assert_eq!(total_amount_paid_msat, 300_000);
5203 fn mpp_cheaper_route_test() {
5204 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5205 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5206 let scorer = ln_test_utils::TestScorer::new();
5207 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5208 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5209 let config = UserConfig::default();
5210 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5211 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5214 // This test checks that if we have two cheaper paths and one more expensive path,
5215 // so that liquidity-wise any 2 of 3 combination is sufficient,
5216 // two cheaper paths will be taken.
5217 // These paths have equal available liquidity.
5219 // We need a combination of 3 paths:
5220 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5221 // Note that these paths overlap (channels 5, 12, 13).
5222 // Each path will have 100 sats capacity, those channels which
5223 // are used twice will have 200 sats capacity.
5225 // Disable other potential paths.
5226 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5227 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5228 short_channel_id: 2,
5231 cltv_expiry_delta: 0,
5232 htlc_minimum_msat: 0,
5233 htlc_maximum_msat: 100_000,
5235 fee_proportional_millionths: 0,
5236 excess_data: Vec::new()
5238 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5239 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5240 short_channel_id: 7,
5243 cltv_expiry_delta: 0,
5244 htlc_minimum_msat: 0,
5245 htlc_maximum_msat: 100_000,
5247 fee_proportional_millionths: 0,
5248 excess_data: Vec::new()
5251 // Path via {node0, node2} is channels {1, 3, 5}.
5252 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5253 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5254 short_channel_id: 1,
5257 cltv_expiry_delta: 0,
5258 htlc_minimum_msat: 0,
5259 htlc_maximum_msat: 100_000,
5261 fee_proportional_millionths: 0,
5262 excess_data: Vec::new()
5264 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5265 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5266 short_channel_id: 3,
5269 cltv_expiry_delta: 0,
5270 htlc_minimum_msat: 0,
5271 htlc_maximum_msat: 100_000,
5273 fee_proportional_millionths: 0,
5274 excess_data: Vec::new()
5277 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5278 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5279 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5280 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5281 short_channel_id: 5,
5284 cltv_expiry_delta: 0,
5285 htlc_minimum_msat: 0,
5286 htlc_maximum_msat: 200_000,
5288 fee_proportional_millionths: 0,
5289 excess_data: Vec::new()
5292 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5293 // Add 100 sats to the capacities of {12, 13}, because these channels
5294 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5295 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5296 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5297 short_channel_id: 12,
5300 cltv_expiry_delta: 0,
5301 htlc_minimum_msat: 0,
5302 htlc_maximum_msat: 200_000,
5304 fee_proportional_millionths: 0,
5305 excess_data: Vec::new()
5307 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5308 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5309 short_channel_id: 13,
5312 cltv_expiry_delta: 0,
5313 htlc_minimum_msat: 0,
5314 htlc_maximum_msat: 200_000,
5316 fee_proportional_millionths: 0,
5317 excess_data: Vec::new()
5320 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5321 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5322 short_channel_id: 6,
5325 cltv_expiry_delta: 0,
5326 htlc_minimum_msat: 0,
5327 htlc_maximum_msat: 100_000,
5328 fee_base_msat: 1_000,
5329 fee_proportional_millionths: 0,
5330 excess_data: Vec::new()
5332 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5333 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5334 short_channel_id: 11,
5337 cltv_expiry_delta: 0,
5338 htlc_minimum_msat: 0,
5339 htlc_maximum_msat: 100_000,
5341 fee_proportional_millionths: 0,
5342 excess_data: Vec::new()
5345 // Path via {node7, node2} is channels {12, 13, 5}.
5346 // We already limited them to 200 sats (they are used twice for 100 sats).
5347 // Nothing to do here.
5350 // Now, attempt to route 180 sats.
5351 // Our algorithm should provide us with these 2 paths.
5352 let route_params = RouteParameters::from_payment_params_and_value(
5353 payment_params, 180_000);
5354 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5355 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5356 assert_eq!(route.paths.len(), 2);
5358 let mut total_value_transferred_msat = 0;
5359 let mut total_paid_msat = 0;
5360 for path in &route.paths {
5361 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5362 total_value_transferred_msat += path.final_value_msat();
5363 for hop in &path.hops {
5364 total_paid_msat += hop.fee_msat;
5367 // If we paid fee, this would be higher.
5368 assert_eq!(total_value_transferred_msat, 180_000);
5369 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5370 assert_eq!(total_fees_paid, 0);
5375 fn fees_on_mpp_route_test() {
5376 // This test makes sure that MPP algorithm properly takes into account
5377 // fees charged on the channels, by making the fees impactful:
5378 // if the fee is not properly accounted for, the behavior is different.
5379 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5380 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5381 let scorer = ln_test_utils::TestScorer::new();
5382 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5383 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5384 let config = UserConfig::default();
5385 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5386 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5389 // We need a route consisting of 2 paths:
5390 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5391 // We will route 200 sats, Each path will have 100 sats capacity.
5393 // This test is not particularly stable: e.g.,
5394 // there's a way to route via {node0, node2, node4}.
5395 // It works while pathfinding is deterministic, but can be broken otherwise.
5396 // It's fine to ignore this concern for now.
5398 // Disable other potential paths.
5399 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5400 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5401 short_channel_id: 2,
5404 cltv_expiry_delta: 0,
5405 htlc_minimum_msat: 0,
5406 htlc_maximum_msat: 100_000,
5408 fee_proportional_millionths: 0,
5409 excess_data: Vec::new()
5412 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5413 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5414 short_channel_id: 7,
5417 cltv_expiry_delta: 0,
5418 htlc_minimum_msat: 0,
5419 htlc_maximum_msat: 100_000,
5421 fee_proportional_millionths: 0,
5422 excess_data: Vec::new()
5425 // Path via {node0, node2} is channels {1, 3, 5}.
5426 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5427 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5428 short_channel_id: 1,
5431 cltv_expiry_delta: 0,
5432 htlc_minimum_msat: 0,
5433 htlc_maximum_msat: 100_000,
5435 fee_proportional_millionths: 0,
5436 excess_data: Vec::new()
5438 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5439 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5440 short_channel_id: 3,
5443 cltv_expiry_delta: 0,
5444 htlc_minimum_msat: 0,
5445 htlc_maximum_msat: 100_000,
5447 fee_proportional_millionths: 0,
5448 excess_data: Vec::new()
5451 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5452 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5453 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5454 short_channel_id: 5,
5457 cltv_expiry_delta: 0,
5458 htlc_minimum_msat: 0,
5459 htlc_maximum_msat: 100_000,
5461 fee_proportional_millionths: 0,
5462 excess_data: Vec::new()
5465 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5466 // All channels should be 100 sats capacity. But for the fee experiment,
5467 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5468 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5469 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5470 // so no matter how large are other channels,
5471 // the whole path will be limited by 100 sats with just these 2 conditions:
5472 // - channel 12 capacity is 250 sats
5473 // - fee for channel 6 is 150 sats
5474 // Let's test this by enforcing these 2 conditions and removing other limits.
5475 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5476 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5477 short_channel_id: 12,
5480 cltv_expiry_delta: 0,
5481 htlc_minimum_msat: 0,
5482 htlc_maximum_msat: 250_000,
5484 fee_proportional_millionths: 0,
5485 excess_data: Vec::new()
5487 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5488 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5489 short_channel_id: 13,
5492 cltv_expiry_delta: 0,
5493 htlc_minimum_msat: 0,
5494 htlc_maximum_msat: MAX_VALUE_MSAT,
5496 fee_proportional_millionths: 0,
5497 excess_data: Vec::new()
5500 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5501 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5502 short_channel_id: 6,
5505 cltv_expiry_delta: 0,
5506 htlc_minimum_msat: 0,
5507 htlc_maximum_msat: MAX_VALUE_MSAT,
5508 fee_base_msat: 150_000,
5509 fee_proportional_millionths: 0,
5510 excess_data: Vec::new()
5512 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5513 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5514 short_channel_id: 11,
5517 cltv_expiry_delta: 0,
5518 htlc_minimum_msat: 0,
5519 htlc_maximum_msat: MAX_VALUE_MSAT,
5521 fee_proportional_millionths: 0,
5522 excess_data: Vec::new()
5526 // Attempt to route more than available results in a failure.
5527 let route_params = RouteParameters::from_payment_params_and_value(
5528 payment_params.clone(), 210_000);
5529 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5530 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5531 &scorer, &Default::default(), &random_seed_bytes) {
5532 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5533 } else { panic!(); }
5537 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5538 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5539 max_total_routing_fee_msat: Some(149_999) };
5540 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5541 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5542 &scorer, &Default::default(), &random_seed_bytes) {
5543 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5544 } else { panic!(); }
5548 // Now, attempt to route 200 sats (exact amount we can route).
5549 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5550 max_total_routing_fee_msat: Some(150_000) };
5551 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5552 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5553 assert_eq!(route.paths.len(), 2);
5555 let mut total_amount_paid_msat = 0;
5556 for path in &route.paths {
5557 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5558 total_amount_paid_msat += path.final_value_msat();
5560 assert_eq!(total_amount_paid_msat, 200_000);
5561 assert_eq!(route.get_total_fees(), 150_000);
5566 fn mpp_with_last_hops() {
5567 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5568 // via a single last-hop route hint, we'd fail to route if we first collected routes
5569 // totaling close but not quite enough to fund the full payment.
5571 // This was because we considered last-hop hints to have exactly the sought payment amount
5572 // instead of the amount we were trying to collect, needlessly limiting our path searching
5573 // at the very first hop.
5575 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5576 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5577 // to only have the remaining to-collect amount in available liquidity.
5579 // This bug appeared in production in some specific channel configurations.
5580 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5581 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5582 let scorer = ln_test_utils::TestScorer::new();
5583 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5584 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5585 let config = UserConfig::default();
5586 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5587 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5588 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5589 src_node_id: nodes[2],
5590 short_channel_id: 42,
5591 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5592 cltv_expiry_delta: 42,
5593 htlc_minimum_msat: None,
5594 htlc_maximum_msat: None,
5595 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5597 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5598 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5599 // would first use the no-fee route and then fail to find a path along the second route as
5600 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5601 // under 5% of our payment amount.
5602 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5603 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5604 short_channel_id: 1,
5607 cltv_expiry_delta: (5 << 4) | 5,
5608 htlc_minimum_msat: 0,
5609 htlc_maximum_msat: 99_000,
5610 fee_base_msat: u32::max_value(),
5611 fee_proportional_millionths: u32::max_value(),
5612 excess_data: Vec::new()
5614 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5615 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5616 short_channel_id: 2,
5619 cltv_expiry_delta: (5 << 4) | 3,
5620 htlc_minimum_msat: 0,
5621 htlc_maximum_msat: 99_000,
5622 fee_base_msat: u32::max_value(),
5623 fee_proportional_millionths: u32::max_value(),
5624 excess_data: Vec::new()
5626 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5627 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5628 short_channel_id: 4,
5631 cltv_expiry_delta: (4 << 4) | 1,
5632 htlc_minimum_msat: 0,
5633 htlc_maximum_msat: MAX_VALUE_MSAT,
5635 fee_proportional_millionths: 0,
5636 excess_data: Vec::new()
5638 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5639 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5640 short_channel_id: 13,
5642 flags: 0|2, // Channel disabled
5643 cltv_expiry_delta: (13 << 4) | 1,
5644 htlc_minimum_msat: 0,
5645 htlc_maximum_msat: MAX_VALUE_MSAT,
5647 fee_proportional_millionths: 2000000,
5648 excess_data: Vec::new()
5651 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5653 let route_params = RouteParameters::from_payment_params_and_value(
5654 payment_params, 100_000);
5655 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5656 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5657 assert_eq!(route.paths.len(), 2);
5658 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5659 // Paths are manually ordered ordered by SCID, so:
5660 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5661 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5662 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5663 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5664 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5665 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5666 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5667 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5668 assert_eq!(route.get_total_fees(), 1);
5669 assert_eq!(route.get_total_amount(), 100_000);
5673 fn drop_lowest_channel_mpp_route_test() {
5674 // This test checks that low-capacity channel is dropped when after
5675 // path finding we realize that we found more capacity than we need.
5676 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5677 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5678 let scorer = ln_test_utils::TestScorer::new();
5679 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5680 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5681 let config = UserConfig::default();
5682 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5683 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5685 .with_max_channel_saturation_power_of_half(0);
5687 // We need a route consisting of 3 paths:
5688 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5690 // The first and the second paths should be sufficient, but the third should be
5691 // cheaper, so that we select it but drop later.
5693 // First, we set limits on these (previously unlimited) channels.
5694 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5696 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5697 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5698 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5699 short_channel_id: 1,
5702 cltv_expiry_delta: 0,
5703 htlc_minimum_msat: 0,
5704 htlc_maximum_msat: 100_000,
5706 fee_proportional_millionths: 0,
5707 excess_data: Vec::new()
5709 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5710 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5711 short_channel_id: 3,
5714 cltv_expiry_delta: 0,
5715 htlc_minimum_msat: 0,
5716 htlc_maximum_msat: 50_000,
5718 fee_proportional_millionths: 0,
5719 excess_data: Vec::new()
5722 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5723 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5724 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5725 short_channel_id: 12,
5728 cltv_expiry_delta: 0,
5729 htlc_minimum_msat: 0,
5730 htlc_maximum_msat: 60_000,
5732 fee_proportional_millionths: 0,
5733 excess_data: Vec::new()
5735 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5736 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5737 short_channel_id: 13,
5740 cltv_expiry_delta: 0,
5741 htlc_minimum_msat: 0,
5742 htlc_maximum_msat: 60_000,
5744 fee_proportional_millionths: 0,
5745 excess_data: Vec::new()
5748 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5749 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5750 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5751 short_channel_id: 2,
5754 cltv_expiry_delta: 0,
5755 htlc_minimum_msat: 0,
5756 htlc_maximum_msat: 20_000,
5758 fee_proportional_millionths: 0,
5759 excess_data: Vec::new()
5761 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5762 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5763 short_channel_id: 4,
5766 cltv_expiry_delta: 0,
5767 htlc_minimum_msat: 0,
5768 htlc_maximum_msat: 20_000,
5770 fee_proportional_millionths: 0,
5771 excess_data: Vec::new()
5775 // Attempt to route more than available results in a failure.
5776 let route_params = RouteParameters::from_payment_params_and_value(
5777 payment_params.clone(), 150_000);
5778 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5779 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5780 &scorer, &Default::default(), &random_seed_bytes) {
5781 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5782 } else { panic!(); }
5786 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5787 // Our algorithm should provide us with these 3 paths.
5788 let route_params = RouteParameters::from_payment_params_and_value(
5789 payment_params.clone(), 125_000);
5790 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5791 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5792 assert_eq!(route.paths.len(), 3);
5793 let mut total_amount_paid_msat = 0;
5794 for path in &route.paths {
5795 assert_eq!(path.hops.len(), 2);
5796 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5797 total_amount_paid_msat += path.final_value_msat();
5799 assert_eq!(total_amount_paid_msat, 125_000);
5803 // Attempt to route without the last small cheap channel
5804 let route_params = RouteParameters::from_payment_params_and_value(
5805 payment_params, 90_000);
5806 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5807 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5808 assert_eq!(route.paths.len(), 2);
5809 let mut total_amount_paid_msat = 0;
5810 for path in &route.paths {
5811 assert_eq!(path.hops.len(), 2);
5812 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5813 total_amount_paid_msat += path.final_value_msat();
5815 assert_eq!(total_amount_paid_msat, 90_000);
5820 fn min_criteria_consistency() {
5821 // Test that we don't use an inconsistent metric between updating and walking nodes during
5822 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5823 // was updated with a different criterion from the heap sorting, resulting in loops in
5824 // calculated paths. We test for that specific case here.
5826 // We construct a network that looks like this:
5828 // node2 -1(3)2- node3
5832 // node1 -1(5)2- node4 -1(1)2- node6
5838 // We create a loop on the side of our real path - our destination is node 6, with a
5839 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5840 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5841 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5842 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5843 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5844 // "previous hop" being set to node 3, creating a loop in the path.
5845 let secp_ctx = Secp256k1::new();
5846 let logger = Arc::new(ln_test_utils::TestLogger::new());
5847 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5848 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5849 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5850 let scorer = ln_test_utils::TestScorer::new();
5851 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5852 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5853 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5855 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5856 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5857 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5858 short_channel_id: 6,
5861 cltv_expiry_delta: (6 << 4) | 0,
5862 htlc_minimum_msat: 0,
5863 htlc_maximum_msat: MAX_VALUE_MSAT,
5865 fee_proportional_millionths: 0,
5866 excess_data: Vec::new()
5868 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5870 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5871 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5872 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5873 short_channel_id: 5,
5876 cltv_expiry_delta: (5 << 4) | 0,
5877 htlc_minimum_msat: 0,
5878 htlc_maximum_msat: MAX_VALUE_MSAT,
5880 fee_proportional_millionths: 0,
5881 excess_data: Vec::new()
5883 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5885 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5886 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5887 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5888 short_channel_id: 4,
5891 cltv_expiry_delta: (4 << 4) | 0,
5892 htlc_minimum_msat: 0,
5893 htlc_maximum_msat: MAX_VALUE_MSAT,
5895 fee_proportional_millionths: 0,
5896 excess_data: Vec::new()
5898 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5900 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5901 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5902 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5903 short_channel_id: 3,
5906 cltv_expiry_delta: (3 << 4) | 0,
5907 htlc_minimum_msat: 0,
5908 htlc_maximum_msat: MAX_VALUE_MSAT,
5910 fee_proportional_millionths: 0,
5911 excess_data: Vec::new()
5913 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5915 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5916 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5917 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5918 short_channel_id: 2,
5921 cltv_expiry_delta: (2 << 4) | 0,
5922 htlc_minimum_msat: 0,
5923 htlc_maximum_msat: MAX_VALUE_MSAT,
5925 fee_proportional_millionths: 0,
5926 excess_data: Vec::new()
5929 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5930 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5931 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5932 short_channel_id: 1,
5935 cltv_expiry_delta: (1 << 4) | 0,
5936 htlc_minimum_msat: 100,
5937 htlc_maximum_msat: MAX_VALUE_MSAT,
5939 fee_proportional_millionths: 0,
5940 excess_data: Vec::new()
5942 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5945 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5946 let route_params = RouteParameters::from_payment_params_and_value(
5947 payment_params, 10_000);
5948 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5949 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5950 assert_eq!(route.paths.len(), 1);
5951 assert_eq!(route.paths[0].hops.len(), 3);
5953 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5954 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5955 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5956 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5957 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5958 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5960 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5961 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5962 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5963 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5964 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5965 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5967 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5968 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5969 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5970 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5971 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5972 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5978 fn exact_fee_liquidity_limit() {
5979 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5980 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5981 // we calculated fees on a higher value, resulting in us ignoring such paths.
5982 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5983 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5984 let scorer = ln_test_utils::TestScorer::new();
5985 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5986 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5987 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5989 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5991 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5992 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5993 short_channel_id: 2,
5996 cltv_expiry_delta: 0,
5997 htlc_minimum_msat: 0,
5998 htlc_maximum_msat: 85_000,
6000 fee_proportional_millionths: 0,
6001 excess_data: Vec::new()
6004 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6005 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6006 short_channel_id: 12,
6009 cltv_expiry_delta: (4 << 4) | 1,
6010 htlc_minimum_msat: 0,
6011 htlc_maximum_msat: 270_000,
6013 fee_proportional_millionths: 1000000,
6014 excess_data: Vec::new()
6018 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6019 // 200% fee charged channel 13 in the 1-to-2 direction.
6020 let mut route_params = RouteParameters::from_payment_params_and_value(
6021 payment_params, 90_000);
6022 route_params.max_total_routing_fee_msat = Some(90_000*2);
6023 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6024 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6025 assert_eq!(route.paths.len(), 1);
6026 assert_eq!(route.paths[0].hops.len(), 2);
6028 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6029 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6030 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6031 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6032 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6033 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6035 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6036 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6037 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6038 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6039 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6040 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6045 fn htlc_max_reduction_below_min() {
6046 // Test that if, while walking the graph, we reduce the value being sent to meet an
6047 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6048 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6049 // resulting in us thinking there is no possible path, even if other paths exist.
6050 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6051 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6052 let scorer = ln_test_utils::TestScorer::new();
6053 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6054 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6055 let config = UserConfig::default();
6056 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6057 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6060 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6061 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6062 // then try to send 90_000.
6063 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6064 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6065 short_channel_id: 2,
6068 cltv_expiry_delta: 0,
6069 htlc_minimum_msat: 0,
6070 htlc_maximum_msat: 80_000,
6072 fee_proportional_millionths: 0,
6073 excess_data: Vec::new()
6075 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6076 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6077 short_channel_id: 4,
6080 cltv_expiry_delta: (4 << 4) | 1,
6081 htlc_minimum_msat: 90_000,
6082 htlc_maximum_msat: MAX_VALUE_MSAT,
6084 fee_proportional_millionths: 0,
6085 excess_data: Vec::new()
6089 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6090 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6091 // expensive) channels 12-13 path.
6092 let mut route_params = RouteParameters::from_payment_params_and_value(
6093 payment_params, 90_000);
6094 route_params.max_total_routing_fee_msat = Some(90_000*2);
6095 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6096 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6097 assert_eq!(route.paths.len(), 1);
6098 assert_eq!(route.paths[0].hops.len(), 2);
6100 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6101 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6102 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6103 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6104 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6105 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6107 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6108 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6109 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6110 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6111 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6112 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6117 fn multiple_direct_first_hops() {
6118 // Previously we'd only ever considered one first hop path per counterparty.
6119 // However, as we don't restrict users to one channel per peer, we really need to support
6120 // looking at all first hop paths.
6121 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6122 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6123 // route over multiple channels with the same first hop.
6124 let secp_ctx = Secp256k1::new();
6125 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6126 let logger = Arc::new(ln_test_utils::TestLogger::new());
6127 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6128 let scorer = ln_test_utils::TestScorer::new();
6129 let config = UserConfig::default();
6130 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6131 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6133 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6134 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6137 let route_params = RouteParameters::from_payment_params_and_value(
6138 payment_params.clone(), 100_000);
6139 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6140 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6141 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6142 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6143 assert_eq!(route.paths.len(), 1);
6144 assert_eq!(route.paths[0].hops.len(), 1);
6146 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6147 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6148 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6151 let route_params = RouteParameters::from_payment_params_and_value(
6152 payment_params.clone(), 100_000);
6153 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6154 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6155 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6156 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6157 assert_eq!(route.paths.len(), 2);
6158 assert_eq!(route.paths[0].hops.len(), 1);
6159 assert_eq!(route.paths[1].hops.len(), 1);
6161 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6162 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6164 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6165 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6167 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6168 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6172 // If we have a bunch of outbound channels to the same node, where most are not
6173 // sufficient to pay the full payment, but one is, we should default to just using the
6174 // one single channel that has sufficient balance, avoiding MPP.
6176 // If we have several options above the 3xpayment value threshold, we should pick the
6177 // smallest of them, avoiding further fragmenting our available outbound balance to
6179 let route_params = RouteParameters::from_payment_params_and_value(
6180 payment_params, 100_000);
6181 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6182 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6183 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6184 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6185 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6186 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6187 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6188 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6189 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6190 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6191 assert_eq!(route.paths.len(), 1);
6192 assert_eq!(route.paths[0].hops.len(), 1);
6194 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6195 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6196 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6201 fn prefers_shorter_route_with_higher_fees() {
6202 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6203 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6204 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6206 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6207 let scorer = ln_test_utils::TestScorer::new();
6208 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6209 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6210 let route_params = RouteParameters::from_payment_params_and_value(
6211 payment_params.clone(), 100);
6212 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6213 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6214 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6216 assert_eq!(route.get_total_fees(), 100);
6217 assert_eq!(route.get_total_amount(), 100);
6218 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6220 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6221 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6222 let scorer = FixedPenaltyScorer::with_penalty(100);
6223 let route_params = RouteParameters::from_payment_params_and_value(
6224 payment_params, 100);
6225 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6226 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6227 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6229 assert_eq!(route.get_total_fees(), 300);
6230 assert_eq!(route.get_total_amount(), 100);
6231 assert_eq!(path, vec![2, 4, 7, 10]);
6234 struct BadChannelScorer {
6235 short_channel_id: u64,
6239 impl Writeable for BadChannelScorer {
6240 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6242 impl ScoreLookUp for BadChannelScorer {
6243 type ScoreParams = ();
6244 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6245 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6249 struct BadNodeScorer {
6254 impl Writeable for BadNodeScorer {
6255 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6258 impl ScoreLookUp for BadNodeScorer {
6259 type ScoreParams = ();
6260 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6261 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6266 fn avoids_routing_through_bad_channels_and_nodes() {
6267 let (secp_ctx, network, _, _, logger) = build_graph();
6268 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6269 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6270 let network_graph = network.read_only();
6272 // A path to nodes[6] exists when no penalties are applied to any channel.
6273 let scorer = ln_test_utils::TestScorer::new();
6274 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6275 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6276 let route_params = RouteParameters::from_payment_params_and_value(
6277 payment_params, 100);
6278 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6279 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6280 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6282 assert_eq!(route.get_total_fees(), 100);
6283 assert_eq!(route.get_total_amount(), 100);
6284 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6286 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6287 let scorer = BadChannelScorer { short_channel_id: 6 };
6288 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6289 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6290 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6292 assert_eq!(route.get_total_fees(), 300);
6293 assert_eq!(route.get_total_amount(), 100);
6294 assert_eq!(path, vec![2, 4, 7, 10]);
6296 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6297 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6298 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6299 &scorer, &Default::default(), &random_seed_bytes) {
6300 Err(LightningError { err, .. } ) => {
6301 assert_eq!(err, "Failed to find a path to the given destination");
6303 Ok(_) => panic!("Expected error"),
6308 fn total_fees_single_path() {
6310 paths: vec![Path { hops: vec![
6312 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6313 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6314 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6317 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6318 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6319 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6322 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6323 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6324 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6326 ], blinded_tail: None }],
6330 assert_eq!(route.get_total_fees(), 250);
6331 assert_eq!(route.get_total_amount(), 225);
6335 fn total_fees_multi_path() {
6337 paths: vec![Path { hops: vec![
6339 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6340 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6341 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6344 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6345 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6346 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6348 ], blinded_tail: None }, Path { hops: vec![
6350 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6351 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6352 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6355 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6356 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6357 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6359 ], blinded_tail: None }],
6363 assert_eq!(route.get_total_fees(), 200);
6364 assert_eq!(route.get_total_amount(), 300);
6368 fn total_empty_route_no_panic() {
6369 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6370 // would both panic if the route was completely empty. We test to ensure they return 0
6371 // here, even though its somewhat nonsensical as a route.
6372 let route = Route { paths: Vec::new(), route_params: None };
6374 assert_eq!(route.get_total_fees(), 0);
6375 assert_eq!(route.get_total_amount(), 0);
6379 fn limits_total_cltv_delta() {
6380 let (secp_ctx, network, _, _, logger) = build_graph();
6381 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6382 let network_graph = network.read_only();
6384 let scorer = ln_test_utils::TestScorer::new();
6386 // Make sure that generally there is at least one route available
6387 let feasible_max_total_cltv_delta = 1008;
6388 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6389 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6390 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6391 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6392 let route_params = RouteParameters::from_payment_params_and_value(
6393 feasible_payment_params, 100);
6394 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6395 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6396 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6397 assert_ne!(path.len(), 0);
6399 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6400 let fail_max_total_cltv_delta = 23;
6401 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6402 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6403 let route_params = RouteParameters::from_payment_params_and_value(
6404 fail_payment_params, 100);
6405 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6406 &Default::default(), &random_seed_bytes)
6408 Err(LightningError { err, .. } ) => {
6409 assert_eq!(err, "Failed to find a path to the given destination");
6411 Ok(_) => panic!("Expected error"),
6416 fn avoids_recently_failed_paths() {
6417 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6418 // randomly inserting channels into it until we can't find a route anymore.
6419 let (secp_ctx, network, _, _, logger) = build_graph();
6420 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6421 let network_graph = network.read_only();
6423 let scorer = ln_test_utils::TestScorer::new();
6424 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6425 .with_max_path_count(1);
6426 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6427 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6429 // We should be able to find a route initially, and then after we fail a few random
6430 // channels eventually we won't be able to any longer.
6431 let route_params = RouteParameters::from_payment_params_and_value(
6432 payment_params.clone(), 100);
6433 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6434 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6436 let route_params = RouteParameters::from_payment_params_and_value(
6437 payment_params.clone(), 100);
6438 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6439 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6441 for chan in route.paths[0].hops.iter() {
6442 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6444 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6445 % route.paths[0].hops.len();
6446 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6452 fn limits_path_length() {
6453 let (secp_ctx, network, _, _, logger) = build_line_graph();
6454 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6455 let network_graph = network.read_only();
6457 let scorer = ln_test_utils::TestScorer::new();
6458 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6459 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6461 // First check we can actually create a long route on this graph.
6462 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6463 let route_params = RouteParameters::from_payment_params_and_value(
6464 feasible_payment_params, 100);
6465 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6466 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6467 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6468 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6470 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6471 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6472 let route_params = RouteParameters::from_payment_params_and_value(
6473 fail_payment_params, 100);
6474 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6475 &Default::default(), &random_seed_bytes)
6477 Err(LightningError { err, .. } ) => {
6478 assert_eq!(err, "Failed to find a path to the given destination");
6480 Ok(_) => panic!("Expected error"),
6485 fn adds_and_limits_cltv_offset() {
6486 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6487 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6489 let scorer = ln_test_utils::TestScorer::new();
6491 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6492 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6493 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6494 let route_params = RouteParameters::from_payment_params_and_value(
6495 payment_params.clone(), 100);
6496 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6497 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6498 assert_eq!(route.paths.len(), 1);
6500 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6502 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6503 let mut route_default = route.clone();
6504 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6505 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6506 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6507 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6508 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6510 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6511 let mut route_limited = route.clone();
6512 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6513 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6514 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6515 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6516 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6520 fn adds_plausible_cltv_offset() {
6521 let (secp_ctx, network, _, _, logger) = build_graph();
6522 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6523 let network_graph = network.read_only();
6524 let network_nodes = network_graph.nodes();
6525 let network_channels = network_graph.channels();
6526 let scorer = ln_test_utils::TestScorer::new();
6527 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6528 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6529 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6531 let route_params = RouteParameters::from_payment_params_and_value(
6532 payment_params.clone(), 100);
6533 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6534 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6535 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6537 let mut path_plausibility = vec![];
6539 for p in route.paths {
6540 // 1. Select random observation point
6541 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6542 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6544 prng.process_in_place(&mut random_bytes);
6545 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6546 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6548 // 2. Calculate what CLTV expiry delta we would observe there
6549 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6551 // 3. Starting from the observation point, find candidate paths
6552 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6553 candidates.push_back((observation_point, vec![]));
6555 let mut found_plausible_candidate = false;
6557 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6558 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6559 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6560 found_plausible_candidate = true;
6561 break 'candidate_loop;
6565 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6566 for channel_id in &cur_node.channels {
6567 if let Some(channel_info) = network_channels.get(&channel_id) {
6568 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6569 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6570 if cur_path_cltv_deltas.iter().sum::<u32>()
6571 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6572 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6573 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6574 candidates.push_back((*next_id, new_path_cltv_deltas));
6582 path_plausibility.push(found_plausible_candidate);
6584 assert!(path_plausibility.iter().all(|x| *x));
6588 fn builds_correct_path_from_hops() {
6589 let (secp_ctx, network, _, _, logger) = build_graph();
6590 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6591 let network_graph = network.read_only();
6593 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6594 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6596 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6597 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6598 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6599 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6600 Arc::clone(&logger), &random_seed_bytes).unwrap();
6601 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6602 assert_eq!(hops.len(), route.paths[0].hops.len());
6603 for (idx, hop_pubkey) in hops.iter().enumerate() {
6604 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6609 fn avoids_saturating_channels() {
6610 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6611 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6612 let decay_params = ProbabilisticScoringDecayParameters::default();
6613 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6615 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6616 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6617 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6618 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6619 short_channel_id: 4,
6622 cltv_expiry_delta: (4 << 4) | 1,
6623 htlc_minimum_msat: 0,
6624 htlc_maximum_msat: 250_000_000,
6626 fee_proportional_millionths: 0,
6627 excess_data: Vec::new()
6629 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6630 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6631 short_channel_id: 13,
6634 cltv_expiry_delta: (13 << 4) | 1,
6635 htlc_minimum_msat: 0,
6636 htlc_maximum_msat: 250_000_000,
6638 fee_proportional_millionths: 0,
6639 excess_data: Vec::new()
6642 let config = UserConfig::default();
6643 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6644 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6646 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6647 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6648 // 100,000 sats is less than the available liquidity on each channel, set above.
6649 let route_params = RouteParameters::from_payment_params_and_value(
6650 payment_params, 100_000_000);
6651 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6652 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6653 assert_eq!(route.paths.len(), 2);
6654 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6655 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6658 #[cfg(not(feature = "no-std"))]
6659 pub(super) fn random_init_seed() -> u64 {
6660 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6661 use core::hash::{BuildHasher, Hasher};
6662 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6663 println!("Using seed of {}", seed);
6668 #[cfg(not(feature = "no-std"))]
6669 fn generate_routes() {
6670 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6672 let logger = ln_test_utils::TestLogger::new();
6673 let graph = match super::bench_utils::read_network_graph(&logger) {
6681 let params = ProbabilisticScoringFeeParameters::default();
6682 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6683 let features = super::Bolt11InvoiceFeatures::empty();
6685 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6689 #[cfg(not(feature = "no-std"))]
6690 fn generate_routes_mpp() {
6691 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6693 let logger = ln_test_utils::TestLogger::new();
6694 let graph = match super::bench_utils::read_network_graph(&logger) {
6702 let params = ProbabilisticScoringFeeParameters::default();
6703 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6704 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6706 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6710 #[cfg(not(feature = "no-std"))]
6711 fn generate_large_mpp_routes() {
6712 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6714 let logger = ln_test_utils::TestLogger::new();
6715 let graph = match super::bench_utils::read_network_graph(&logger) {
6723 let params = ProbabilisticScoringFeeParameters::default();
6724 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6725 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6727 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6731 fn honors_manual_penalties() {
6732 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6733 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6735 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6736 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6738 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6739 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6741 // First check set manual penalties are returned by the scorer.
6742 let usage = ChannelUsage {
6744 inflight_htlc_msat: 0,
6745 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6747 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6748 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6749 let network_graph = network_graph.read_only();
6750 let channels = network_graph.channels();
6751 let channel = channels.get(&5).unwrap();
6752 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
6753 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop {
6755 short_channel_id: 5,
6757 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
6759 // Then check we can get a normal route
6760 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6761 let route_params = RouteParameters::from_payment_params_and_value(
6762 payment_params, 100);
6763 let route = get_route(&our_id, &route_params, &network_graph, None,
6764 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6765 assert!(route.is_ok());
6767 // Then check that we can't get a route if we ban an intermediate node.
6768 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6769 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6770 assert!(route.is_err());
6772 // Finally make sure we can route again, when we remove the ban.
6773 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6774 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6775 assert!(route.is_ok());
6779 fn abide_by_route_hint_max_htlc() {
6780 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6781 // params in the final route.
6782 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6783 let netgraph = network_graph.read_only();
6784 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6785 let scorer = ln_test_utils::TestScorer::new();
6786 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6787 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6788 let config = UserConfig::default();
6790 let max_htlc_msat = 50_000;
6791 let route_hint_1 = RouteHint(vec![RouteHintHop {
6792 src_node_id: nodes[2],
6793 short_channel_id: 42,
6796 proportional_millionths: 0,
6798 cltv_expiry_delta: 10,
6799 htlc_minimum_msat: None,
6800 htlc_maximum_msat: Some(max_htlc_msat),
6802 let dest_node_id = ln_test_utils::pubkey(42);
6803 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6804 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6805 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6808 // Make sure we'll error if our route hints don't have enough liquidity according to their
6809 // htlc_maximum_msat.
6810 let mut route_params = RouteParameters::from_payment_params_and_value(
6811 payment_params, max_htlc_msat + 1);
6812 route_params.max_total_routing_fee_msat = None;
6813 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6814 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6817 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6818 } else { panic!(); }
6820 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6821 let mut route_hint_2 = route_hint_1.clone();
6822 route_hint_2.0[0].short_channel_id = 43;
6823 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6824 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6825 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6827 let mut route_params = RouteParameters::from_payment_params_and_value(
6828 payment_params, max_htlc_msat + 1);
6829 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
6830 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6831 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6832 assert_eq!(route.paths.len(), 2);
6833 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6834 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6838 fn direct_channel_to_hints_with_max_htlc() {
6839 // Check that if we have a first hop channel peer that's connected to multiple provided route
6840 // hints, that we properly split the payment between the route hints if needed.
6841 let logger = Arc::new(ln_test_utils::TestLogger::new());
6842 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6843 let scorer = ln_test_utils::TestScorer::new();
6844 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6845 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6846 let config = UserConfig::default();
6848 let our_node_id = ln_test_utils::pubkey(42);
6849 let intermed_node_id = ln_test_utils::pubkey(43);
6850 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6852 let amt_msat = 900_000;
6853 let max_htlc_msat = 500_000;
6854 let route_hint_1 = RouteHint(vec![RouteHintHop {
6855 src_node_id: intermed_node_id,
6856 short_channel_id: 44,
6859 proportional_millionths: 0,
6861 cltv_expiry_delta: 10,
6862 htlc_minimum_msat: None,
6863 htlc_maximum_msat: Some(max_htlc_msat),
6865 src_node_id: intermed_node_id,
6866 short_channel_id: 45,
6869 proportional_millionths: 0,
6871 cltv_expiry_delta: 10,
6872 htlc_minimum_msat: None,
6873 // Check that later route hint max htlcs don't override earlier ones
6874 htlc_maximum_msat: Some(max_htlc_msat - 50),
6876 let mut route_hint_2 = route_hint_1.clone();
6877 route_hint_2.0[0].short_channel_id = 46;
6878 route_hint_2.0[1].short_channel_id = 47;
6879 let dest_node_id = ln_test_utils::pubkey(44);
6880 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6881 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6882 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6885 let route_params = RouteParameters::from_payment_params_and_value(
6886 payment_params, amt_msat);
6887 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6888 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6889 &Default::default(), &random_seed_bytes).unwrap();
6890 assert_eq!(route.paths.len(), 2);
6891 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6892 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6893 assert_eq!(route.get_total_amount(), amt_msat);
6895 // Re-run but with two first hop channels connected to the same route hint peers that must be
6897 let first_hops = vec![
6898 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6899 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6901 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6902 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6903 &Default::default(), &random_seed_bytes).unwrap();
6904 assert_eq!(route.paths.len(), 2);
6905 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6906 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6907 assert_eq!(route.get_total_amount(), amt_msat);
6909 // Make sure this works for blinded route hints.
6910 let blinded_path = BlindedPath {
6911 introduction_node_id: intermed_node_id,
6912 blinding_point: ln_test_utils::pubkey(42),
6914 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6915 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6918 let blinded_payinfo = BlindedPayInfo {
6920 fee_proportional_millionths: 0,
6921 htlc_minimum_msat: 1,
6922 htlc_maximum_msat: max_htlc_msat,
6923 cltv_expiry_delta: 10,
6924 features: BlindedHopFeatures::empty(),
6926 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
6927 let payment_params = PaymentParameters::blinded(vec![
6928 (blinded_payinfo.clone(), blinded_path.clone()),
6929 (blinded_payinfo.clone(), blinded_path.clone())])
6930 .with_bolt12_features(bolt12_features).unwrap();
6931 let route_params = RouteParameters::from_payment_params_and_value(
6932 payment_params, amt_msat);
6933 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6934 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6935 &Default::default(), &random_seed_bytes).unwrap();
6936 assert_eq!(route.paths.len(), 2);
6937 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6938 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6939 assert_eq!(route.get_total_amount(), amt_msat);
6943 fn blinded_route_ser() {
6944 let blinded_path_1 = BlindedPath {
6945 introduction_node_id: ln_test_utils::pubkey(42),
6946 blinding_point: ln_test_utils::pubkey(43),
6948 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6949 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6952 let blinded_path_2 = BlindedPath {
6953 introduction_node_id: ln_test_utils::pubkey(46),
6954 blinding_point: ln_test_utils::pubkey(47),
6956 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6957 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6960 // (De)serialize a Route with 1 blinded path out of two total paths.
6961 let mut route = Route { paths: vec![Path {
6962 hops: vec![RouteHop {
6963 pubkey: ln_test_utils::pubkey(50),
6964 node_features: NodeFeatures::empty(),
6965 short_channel_id: 42,
6966 channel_features: ChannelFeatures::empty(),
6968 cltv_expiry_delta: 0,
6969 maybe_announced_channel: true,
6971 blinded_tail: Some(BlindedTail {
6972 hops: blinded_path_1.blinded_hops,
6973 blinding_point: blinded_path_1.blinding_point,
6974 excess_final_cltv_expiry_delta: 40,
6975 final_value_msat: 100,
6977 hops: vec![RouteHop {
6978 pubkey: ln_test_utils::pubkey(51),
6979 node_features: NodeFeatures::empty(),
6980 short_channel_id: 43,
6981 channel_features: ChannelFeatures::empty(),
6983 cltv_expiry_delta: 0,
6984 maybe_announced_channel: true,
6985 }], blinded_tail: None }],
6988 let encoded_route = route.encode();
6989 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6990 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6991 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6993 // (De)serialize a Route with two paths, each containing a blinded tail.
6994 route.paths[1].blinded_tail = Some(BlindedTail {
6995 hops: blinded_path_2.blinded_hops,
6996 blinding_point: blinded_path_2.blinding_point,
6997 excess_final_cltv_expiry_delta: 41,
6998 final_value_msat: 101,
7000 let encoded_route = route.encode();
7001 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7002 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7003 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7007 fn blinded_path_inflight_processing() {
7008 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7009 // account for the blinded tail's final amount_msat.
7010 let mut inflight_htlcs = InFlightHtlcs::new();
7011 let blinded_path = BlindedPath {
7012 introduction_node_id: ln_test_utils::pubkey(43),
7013 blinding_point: ln_test_utils::pubkey(48),
7014 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7017 hops: vec![RouteHop {
7018 pubkey: ln_test_utils::pubkey(42),
7019 node_features: NodeFeatures::empty(),
7020 short_channel_id: 42,
7021 channel_features: ChannelFeatures::empty(),
7023 cltv_expiry_delta: 0,
7024 maybe_announced_channel: false,
7027 pubkey: blinded_path.introduction_node_id,
7028 node_features: NodeFeatures::empty(),
7029 short_channel_id: 43,
7030 channel_features: ChannelFeatures::empty(),
7032 cltv_expiry_delta: 0,
7033 maybe_announced_channel: false,
7035 blinded_tail: Some(BlindedTail {
7036 hops: blinded_path.blinded_hops,
7037 blinding_point: blinded_path.blinding_point,
7038 excess_final_cltv_expiry_delta: 0,
7039 final_value_msat: 200,
7042 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7043 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7044 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7048 fn blinded_path_cltv_shadow_offset() {
7049 // Make sure we add a shadow offset when sending to blinded paths.
7050 let blinded_path = BlindedPath {
7051 introduction_node_id: ln_test_utils::pubkey(43),
7052 blinding_point: ln_test_utils::pubkey(44),
7054 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7055 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7058 let mut route = Route { paths: vec![Path {
7059 hops: vec![RouteHop {
7060 pubkey: ln_test_utils::pubkey(42),
7061 node_features: NodeFeatures::empty(),
7062 short_channel_id: 42,
7063 channel_features: ChannelFeatures::empty(),
7065 cltv_expiry_delta: 0,
7066 maybe_announced_channel: false,
7069 pubkey: blinded_path.introduction_node_id,
7070 node_features: NodeFeatures::empty(),
7071 short_channel_id: 43,
7072 channel_features: ChannelFeatures::empty(),
7074 cltv_expiry_delta: 0,
7075 maybe_announced_channel: false,
7078 blinded_tail: Some(BlindedTail {
7079 hops: blinded_path.blinded_hops,
7080 blinding_point: blinded_path.blinding_point,
7081 excess_final_cltv_expiry_delta: 0,
7082 final_value_msat: 200,
7084 }], route_params: None};
7086 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7087 let (_, network_graph, _, _, _) = build_line_graph();
7088 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7089 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7090 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7094 fn simple_blinded_route_hints() {
7095 do_simple_blinded_route_hints(1);
7096 do_simple_blinded_route_hints(2);
7097 do_simple_blinded_route_hints(3);
7100 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7101 // Check that we can generate a route to a blinded path with the expected hops.
7102 let (secp_ctx, network, _, _, logger) = build_graph();
7103 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7104 let network_graph = network.read_only();
7106 let scorer = ln_test_utils::TestScorer::new();
7107 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7108 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7110 let mut blinded_path = BlindedPath {
7111 introduction_node_id: nodes[2],
7112 blinding_point: ln_test_utils::pubkey(42),
7113 blinded_hops: Vec::with_capacity(num_blinded_hops),
7115 for i in 0..num_blinded_hops {
7116 blinded_path.blinded_hops.push(
7117 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7120 let blinded_payinfo = BlindedPayInfo {
7122 fee_proportional_millionths: 500,
7123 htlc_minimum_msat: 1000,
7124 htlc_maximum_msat: 100_000_000,
7125 cltv_expiry_delta: 15,
7126 features: BlindedHopFeatures::empty(),
7129 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7130 let route_params = RouteParameters::from_payment_params_and_value(
7131 payment_params, 1001);
7132 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7133 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7134 assert_eq!(route.paths.len(), 1);
7135 assert_eq!(route.paths[0].hops.len(), 2);
7137 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7138 assert_eq!(tail.hops, blinded_path.blinded_hops);
7139 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7140 assert_eq!(tail.final_value_msat, 1001);
7142 let final_hop = route.paths[0].hops.last().unwrap();
7143 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7144 if tail.hops.len() > 1 {
7145 assert_eq!(final_hop.fee_msat,
7146 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7147 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7149 assert_eq!(final_hop.fee_msat, 0);
7150 assert_eq!(final_hop.cltv_expiry_delta, 0);
7155 fn blinded_path_routing_errors() {
7156 // Check that we can generate a route to a blinded path with the expected hops.
7157 let (secp_ctx, network, _, _, logger) = build_graph();
7158 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7159 let network_graph = network.read_only();
7161 let scorer = ln_test_utils::TestScorer::new();
7162 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7163 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7165 let mut invalid_blinded_path = BlindedPath {
7166 introduction_node_id: nodes[2],
7167 blinding_point: ln_test_utils::pubkey(42),
7169 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7172 let blinded_payinfo = BlindedPayInfo {
7174 fee_proportional_millionths: 500,
7175 htlc_minimum_msat: 1000,
7176 htlc_maximum_msat: 100_000_000,
7177 cltv_expiry_delta: 15,
7178 features: BlindedHopFeatures::empty(),
7181 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7182 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7183 let payment_params = PaymentParameters::blinded(vec![
7184 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7185 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7186 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7187 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7188 &scorer, &Default::default(), &random_seed_bytes)
7190 Err(LightningError { err, .. }) => {
7191 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7193 _ => panic!("Expected error")
7196 invalid_blinded_path.introduction_node_id = our_id;
7197 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7198 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7199 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7200 &Default::default(), &random_seed_bytes)
7202 Err(LightningError { err, .. }) => {
7203 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7205 _ => panic!("Expected error")
7208 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7209 invalid_blinded_path.blinded_hops.clear();
7210 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7211 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7212 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7213 &Default::default(), &random_seed_bytes)
7215 Err(LightningError { err, .. }) => {
7216 assert_eq!(err, "0-hop blinded path provided");
7218 _ => panic!("Expected error")
7223 fn matching_intro_node_paths_provided() {
7224 // Check that if multiple blinded paths with the same intro node are provided in payment
7225 // parameters, we'll return the correct paths in the resulting MPP route.
7226 let (secp_ctx, network, _, _, logger) = build_graph();
7227 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7228 let network_graph = network.read_only();
7230 let scorer = ln_test_utils::TestScorer::new();
7231 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7232 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7233 let config = UserConfig::default();
7235 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7236 let blinded_path_1 = BlindedPath {
7237 introduction_node_id: nodes[2],
7238 blinding_point: ln_test_utils::pubkey(42),
7240 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7241 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7244 let blinded_payinfo_1 = BlindedPayInfo {
7246 fee_proportional_millionths: 0,
7247 htlc_minimum_msat: 0,
7248 htlc_maximum_msat: 30_000,
7249 cltv_expiry_delta: 0,
7250 features: BlindedHopFeatures::empty(),
7253 let mut blinded_path_2 = blinded_path_1.clone();
7254 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7255 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7256 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7258 let blinded_hints = vec![
7259 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7260 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7262 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7263 .with_bolt12_features(bolt12_features).unwrap();
7265 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7266 route_params.max_total_routing_fee_msat = Some(100_000);
7267 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7268 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7269 assert_eq!(route.paths.len(), 2);
7270 let mut total_amount_paid_msat = 0;
7271 for path in route.paths.into_iter() {
7272 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7273 if let Some(bt) = &path.blinded_tail {
7274 assert_eq!(bt.blinding_point,
7275 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7276 .map(|(_, bp)| bp.blinding_point).unwrap());
7277 } else { panic!(); }
7278 total_amount_paid_msat += path.final_value_msat();
7280 assert_eq!(total_amount_paid_msat, 100_000);
7284 fn direct_to_intro_node() {
7285 // This previously caused a debug panic in the router when asserting
7286 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7287 // direct channels we failed to account for the fee charged for use of the blinded path.
7290 // node0 -1(1)2 - node1
7291 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7292 // doesn't account for the blinded path fee.
7294 let secp_ctx = Secp256k1::new();
7295 let logger = Arc::new(ln_test_utils::TestLogger::new());
7296 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7297 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7298 let scorer = ln_test_utils::TestScorer::new();
7299 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7300 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7302 let amt_msat = 10_000_000;
7303 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7304 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7305 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7306 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7307 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7308 short_channel_id: 1,
7311 cltv_expiry_delta: 42,
7312 htlc_minimum_msat: 1_000,
7313 htlc_maximum_msat: 10_000_000,
7315 fee_proportional_millionths: 0,
7316 excess_data: Vec::new()
7318 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7319 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7320 short_channel_id: 1,
7323 cltv_expiry_delta: 42,
7324 htlc_minimum_msat: 1_000,
7325 htlc_maximum_msat: 10_000_000,
7327 fee_proportional_millionths: 0,
7328 excess_data: Vec::new()
7330 let first_hops = vec![
7331 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7333 let blinded_path = BlindedPath {
7334 introduction_node_id: nodes[1],
7335 blinding_point: ln_test_utils::pubkey(42),
7337 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7338 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7341 let blinded_payinfo = BlindedPayInfo {
7342 fee_base_msat: 1000,
7343 fee_proportional_millionths: 0,
7344 htlc_minimum_msat: 1000,
7345 htlc_maximum_msat: MAX_VALUE_MSAT,
7346 cltv_expiry_delta: 0,
7347 features: BlindedHopFeatures::empty(),
7349 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7351 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7353 let netgraph = network_graph.read_only();
7354 let route_params = RouteParameters::from_payment_params_and_value(
7355 payment_params.clone(), amt_msat);
7356 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7357 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7358 &Default::default(), &random_seed_bytes) {
7359 assert_eq!(err, "Failed to find a path to the given destination");
7360 } else { panic!("Expected error") }
7362 // Sending an exact amount accounting for the blinded path fee works.
7363 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7364 let route_params = RouteParameters::from_payment_params_and_value(
7365 payment_params, amt_minus_blinded_path_fee);
7366 let route = get_route(&nodes[0], &route_params, &netgraph,
7367 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7368 &Default::default(), &random_seed_bytes).unwrap();
7369 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7370 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7374 fn direct_to_matching_intro_nodes() {
7375 // This previously caused us to enter `unreachable` code in the following situation:
7376 // 1. We add a route candidate for intro_node contributing a high amount
7377 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7378 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7379 // amount, and update our route candidate for intro_node for the lower amount
7380 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7381 // lower contribution amount, but fail (this was previously caused by failure to account for
7382 // blinded path fees when adding first_hop<>intro_node candidates)
7383 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7384 // candidate still thinks its path is contributing the original higher amount. This caused us
7385 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7387 let secp_ctx = Secp256k1::new();
7388 let logger = Arc::new(ln_test_utils::TestLogger::new());
7389 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7390 let scorer = ln_test_utils::TestScorer::new();
7391 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7392 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7393 let config = UserConfig::default();
7395 // Values are taken from the fuzz input that uncovered this panic.
7396 let amt_msat = 21_7020_5185_1403_2640;
7397 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7398 let first_hops = vec![
7399 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7400 18446744073709551615)];
7402 let blinded_path = BlindedPath {
7403 introduction_node_id: nodes[1],
7404 blinding_point: ln_test_utils::pubkey(42),
7406 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7407 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7410 let blinded_payinfo = BlindedPayInfo {
7411 fee_base_msat: 5046_2720,
7412 fee_proportional_millionths: 0,
7413 htlc_minimum_msat: 4503_5996_2737_0496,
7414 htlc_maximum_msat: 45_0359_9627_3704_9600,
7415 cltv_expiry_delta: 0,
7416 features: BlindedHopFeatures::empty(),
7418 let mut blinded_hints = vec![
7419 (blinded_payinfo.clone(), blinded_path.clone()),
7420 (blinded_payinfo.clone(), blinded_path.clone()),
7422 blinded_hints[1].0.fee_base_msat = 419_4304;
7423 blinded_hints[1].0.fee_proportional_millionths = 257;
7424 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7425 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7426 blinded_hints[1].0.cltv_expiry_delta = 0;
7428 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7429 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7430 .with_bolt12_features(bolt12_features).unwrap();
7432 let netgraph = network_graph.read_only();
7433 let route_params = RouteParameters::from_payment_params_and_value(
7434 payment_params, amt_msat);
7435 let route = get_route(&nodes[0], &route_params, &netgraph,
7436 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7437 &Default::default(), &random_seed_bytes).unwrap();
7438 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7439 assert_eq!(route.get_total_amount(), amt_msat);
7443 fn we_are_intro_node_candidate_hops() {
7444 // This previously led to a panic in the router because we'd generate a Path with only a
7445 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7446 // where the origin node is the intro node. We now fully disallow considering candidate hops
7447 // where the origin node is the intro node.
7448 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7449 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7450 let scorer = ln_test_utils::TestScorer::new();
7451 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7452 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7453 let config = UserConfig::default();
7455 // Values are taken from the fuzz input that uncovered this panic.
7456 let amt_msat = 21_7020_5185_1423_0019;
7458 let blinded_path = BlindedPath {
7459 introduction_node_id: our_id,
7460 blinding_point: ln_test_utils::pubkey(42),
7462 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7463 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7466 let blinded_payinfo = BlindedPayInfo {
7467 fee_base_msat: 5052_9027,
7468 fee_proportional_millionths: 0,
7469 htlc_minimum_msat: 21_7020_5185_1423_0019,
7470 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7471 cltv_expiry_delta: 0,
7472 features: BlindedHopFeatures::empty(),
7474 let mut blinded_hints = vec![
7475 (blinded_payinfo.clone(), blinded_path.clone()),
7476 (blinded_payinfo.clone(), blinded_path.clone()),
7478 blinded_hints[1].1.introduction_node_id = nodes[6];
7480 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7481 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7482 .with_bolt12_features(bolt12_features.clone()).unwrap();
7484 let netgraph = network_graph.read_only();
7485 let route_params = RouteParameters::from_payment_params_and_value(
7486 payment_params, amt_msat);
7487 if let Err(LightningError { err, .. }) = get_route(
7488 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7490 assert_eq!(err, "Failed to find a path to the given destination");
7495 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7496 // This previously led to a debug panic in the router because we'd find an invalid Path with
7497 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7498 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7499 // the payment, when it was intended to only include the final value of the payment.
7500 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7501 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7502 let scorer = ln_test_utils::TestScorer::new();
7503 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7504 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7505 let config = UserConfig::default();
7507 // Values are taken from the fuzz input that uncovered this panic.
7508 let amt_msat = 21_7020_5185_1423_0019;
7510 let blinded_path = BlindedPath {
7511 introduction_node_id: our_id,
7512 blinding_point: ln_test_utils::pubkey(42),
7514 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7515 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7518 let blinded_payinfo = BlindedPayInfo {
7519 fee_base_msat: 10_4425_1395,
7520 fee_proportional_millionths: 0,
7521 htlc_minimum_msat: 21_7301_9934_9094_0931,
7522 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7523 cltv_expiry_delta: 0,
7524 features: BlindedHopFeatures::empty(),
7526 let mut blinded_hints = vec![
7527 (blinded_payinfo.clone(), blinded_path.clone()),
7528 (blinded_payinfo.clone(), blinded_path.clone()),
7529 (blinded_payinfo.clone(), blinded_path.clone()),
7531 blinded_hints[1].0.fee_base_msat = 5052_9027;
7532 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7533 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7535 blinded_hints[2].1.introduction_node_id = nodes[6];
7537 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7538 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7539 .with_bolt12_features(bolt12_features.clone()).unwrap();
7541 let netgraph = network_graph.read_only();
7542 let route_params = RouteParameters::from_payment_params_and_value(
7543 payment_params, amt_msat);
7544 if let Err(LightningError { err, .. }) = get_route(
7545 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7547 assert_eq!(err, "Failed to find a path to the given destination");
7552 fn min_htlc_overpay_violates_max_htlc() {
7553 do_min_htlc_overpay_violates_max_htlc(true);
7554 do_min_htlc_overpay_violates_max_htlc(false);
7556 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7557 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7558 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7559 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7560 // that the used liquidity for a hop was less than its available liquidity limit.
7561 let secp_ctx = Secp256k1::new();
7562 let logger = Arc::new(ln_test_utils::TestLogger::new());
7563 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7564 let scorer = ln_test_utils::TestScorer::new();
7565 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7566 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7567 let config = UserConfig::default();
7569 // Values are taken from the fuzz input that uncovered this panic.
7570 let amt_msat = 7_4009_8048;
7571 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7572 let first_hop_outbound_capacity = 2_7345_2000;
7573 let first_hops = vec![get_channel_details(
7574 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7575 first_hop_outbound_capacity
7578 let base_fee = 1_6778_3453;
7579 let htlc_min = 2_5165_8240;
7580 let payment_params = if blinded_payee {
7581 let blinded_path = BlindedPath {
7582 introduction_node_id: nodes[0],
7583 blinding_point: ln_test_utils::pubkey(42),
7585 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7586 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7589 let blinded_payinfo = BlindedPayInfo {
7590 fee_base_msat: base_fee,
7591 fee_proportional_millionths: 0,
7592 htlc_minimum_msat: htlc_min,
7593 htlc_maximum_msat: htlc_min * 1000,
7594 cltv_expiry_delta: 0,
7595 features: BlindedHopFeatures::empty(),
7597 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7598 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7599 .with_bolt12_features(bolt12_features.clone()).unwrap()
7601 let route_hint = RouteHint(vec![RouteHintHop {
7602 src_node_id: nodes[0],
7603 short_channel_id: 42,
7605 base_msat: base_fee,
7606 proportional_millionths: 0,
7608 cltv_expiry_delta: 10,
7609 htlc_minimum_msat: Some(htlc_min),
7610 htlc_maximum_msat: None,
7613 PaymentParameters::from_node_id(nodes[1], 42)
7614 .with_route_hints(vec![route_hint]).unwrap()
7615 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7618 let netgraph = network_graph.read_only();
7619 let route_params = RouteParameters::from_payment_params_and_value(
7620 payment_params, amt_msat);
7621 if let Err(LightningError { err, .. }) = get_route(
7622 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7623 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7625 assert_eq!(err, "Failed to find a path to the given destination");
7630 fn previously_used_liquidity_violates_max_htlc() {
7631 do_previously_used_liquidity_violates_max_htlc(true);
7632 do_previously_used_liquidity_violates_max_htlc(false);
7635 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7636 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7637 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7638 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7639 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7640 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7641 let secp_ctx = Secp256k1::new();
7642 let logger = Arc::new(ln_test_utils::TestLogger::new());
7643 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7644 let scorer = ln_test_utils::TestScorer::new();
7645 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7646 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7647 let config = UserConfig::default();
7649 // Values are taken from the fuzz input that uncovered this panic.
7650 let amt_msat = 52_4288;
7651 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7652 let first_hops = vec![get_channel_details(
7653 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7654 ), get_channel_details(
7655 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7658 let base_fees = [0, 425_9840, 0, 0];
7659 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7660 let payment_params = if blinded_payee {
7661 let blinded_path = BlindedPath {
7662 introduction_node_id: nodes[0],
7663 blinding_point: ln_test_utils::pubkey(42),
7665 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7666 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7669 let mut blinded_hints = Vec::new();
7670 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7671 blinded_hints.push((BlindedPayInfo {
7672 fee_base_msat: *base_fee,
7673 fee_proportional_millionths: 0,
7674 htlc_minimum_msat: *htlc_min,
7675 htlc_maximum_msat: htlc_min * 100,
7676 cltv_expiry_delta: 10,
7677 features: BlindedHopFeatures::empty(),
7678 }, blinded_path.clone()));
7680 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7681 PaymentParameters::blinded(blinded_hints.clone())
7682 .with_bolt12_features(bolt12_features.clone()).unwrap()
7684 let mut route_hints = Vec::new();
7685 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7686 route_hints.push(RouteHint(vec![RouteHintHop {
7687 src_node_id: nodes[0],
7688 short_channel_id: 42 + idx as u64,
7690 base_msat: *base_fee,
7691 proportional_millionths: 0,
7693 cltv_expiry_delta: 10,
7694 htlc_minimum_msat: Some(*htlc_min),
7695 htlc_maximum_msat: Some(htlc_min * 100),
7698 PaymentParameters::from_node_id(nodes[1], 42)
7699 .with_route_hints(route_hints).unwrap()
7700 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7703 let netgraph = network_graph.read_only();
7704 let route_params = RouteParameters::from_payment_params_and_value(
7705 payment_params, amt_msat);
7707 let route = get_route(
7708 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7709 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7711 assert_eq!(route.paths.len(), 1);
7712 assert_eq!(route.get_total_amount(), amt_msat);
7716 fn candidate_path_min() {
7717 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7718 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7719 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7720 // would add a connecting first_hop node that did not have enough contribution amount, leading
7721 // to a debug panic upon invalid path construction.
7722 let secp_ctx = Secp256k1::new();
7723 let logger = Arc::new(ln_test_utils::TestLogger::new());
7724 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7725 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7726 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7727 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7728 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7729 let config = UserConfig::default();
7731 // Values are taken from the fuzz input that uncovered this panic.
7732 let amt_msat = 7_4009_8048;
7733 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7734 let first_hops = vec![get_channel_details(
7735 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7738 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7739 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7740 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7741 short_channel_id: 6,
7744 cltv_expiry_delta: (6 << 4) | 0,
7745 htlc_minimum_msat: 0,
7746 htlc_maximum_msat: MAX_VALUE_MSAT,
7748 fee_proportional_millionths: 0,
7749 excess_data: Vec::new()
7751 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
7753 let htlc_min = 2_5165_8240;
7754 let blinded_hints = vec![
7756 fee_base_msat: 1_6778_3453,
7757 fee_proportional_millionths: 0,
7758 htlc_minimum_msat: htlc_min,
7759 htlc_maximum_msat: htlc_min * 100,
7760 cltv_expiry_delta: 10,
7761 features: BlindedHopFeatures::empty(),
7763 introduction_node_id: nodes[0],
7764 blinding_point: ln_test_utils::pubkey(42),
7766 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7767 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7771 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7772 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7773 .with_bolt12_features(bolt12_features.clone()).unwrap();
7774 let route_params = RouteParameters::from_payment_params_and_value(
7775 payment_params, amt_msat);
7776 let netgraph = network_graph.read_only();
7778 if let Err(LightningError { err, .. }) = get_route(
7779 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7780 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7783 assert_eq!(err, "Failed to find a path to the given destination");
7788 fn path_contribution_includes_min_htlc_overpay() {
7789 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
7790 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
7791 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
7792 // selection, both tested here.
7793 let secp_ctx = Secp256k1::new();
7794 let logger = Arc::new(ln_test_utils::TestLogger::new());
7795 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7796 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7797 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7798 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7799 let config = UserConfig::default();
7801 // Values are taken from the fuzz input that uncovered this panic.
7802 let amt_msat = 562_0000;
7803 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7804 let first_hops = vec![
7805 get_channel_details(
7806 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
7810 let htlc_mins = [49_0000, 1125_0000];
7811 let payment_params = {
7812 let blinded_path = BlindedPath {
7813 introduction_node_id: nodes[0],
7814 blinding_point: ln_test_utils::pubkey(42),
7816 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7817 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7820 let mut blinded_hints = Vec::new();
7821 for htlc_min in htlc_mins.iter() {
7822 blinded_hints.push((BlindedPayInfo {
7824 fee_proportional_millionths: 0,
7825 htlc_minimum_msat: *htlc_min,
7826 htlc_maximum_msat: *htlc_min * 100,
7827 cltv_expiry_delta: 10,
7828 features: BlindedHopFeatures::empty(),
7829 }, blinded_path.clone()));
7831 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7832 PaymentParameters::blinded(blinded_hints.clone())
7833 .with_bolt12_features(bolt12_features.clone()).unwrap()
7836 let netgraph = network_graph.read_only();
7837 let route_params = RouteParameters::from_payment_params_and_value(
7838 payment_params, amt_msat);
7839 let route = get_route(
7840 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7841 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7844 assert_eq!(route.paths.len(), 1);
7845 assert_eq!(route.get_total_amount(), amt_msat);
7849 fn first_hop_preferred_over_hint() {
7850 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
7851 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
7852 let secp_ctx = Secp256k1::new();
7853 let logger = Arc::new(ln_test_utils::TestLogger::new());
7854 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7855 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7856 let scorer = ln_test_utils::TestScorer::new();
7857 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7858 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7859 let config = UserConfig::default();
7861 let amt_msat = 1_000_000;
7862 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
7864 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
7865 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7866 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
7867 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7868 short_channel_id: 1,
7871 cltv_expiry_delta: 42,
7872 htlc_minimum_msat: 1_000,
7873 htlc_maximum_msat: 10_000_000,
7875 fee_proportional_millionths: 0,
7876 excess_data: Vec::new()
7878 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7879 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7880 short_channel_id: 1,
7883 cltv_expiry_delta: 42,
7884 htlc_minimum_msat: 1_000,
7885 htlc_maximum_msat: 10_000_000,
7887 fee_proportional_millionths: 0,
7888 excess_data: Vec::new()
7891 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7892 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
7893 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7894 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7895 short_channel_id: 2,
7898 cltv_expiry_delta: 42,
7899 htlc_minimum_msat: 1_000,
7900 htlc_maximum_msat: 10_000_000,
7902 fee_proportional_millionths: 0,
7903 excess_data: Vec::new()
7905 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7906 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7907 short_channel_id: 2,
7910 cltv_expiry_delta: 42,
7911 htlc_minimum_msat: 1_000,
7912 htlc_maximum_msat: 10_000_000,
7914 fee_proportional_millionths: 0,
7915 excess_data: Vec::new()
7918 let dest_node_id = nodes[2];
7920 let route_hint = RouteHint(vec![RouteHintHop {
7921 src_node_id: our_node_id,
7922 short_channel_id: 44,
7925 proportional_millionths: 0,
7927 cltv_expiry_delta: 10,
7928 htlc_minimum_msat: None,
7929 htlc_maximum_msat: Some(5_000_000),
7932 src_node_id: nodes[0],
7933 short_channel_id: 45,
7936 proportional_millionths: 0,
7938 cltv_expiry_delta: 10,
7939 htlc_minimum_msat: None,
7940 htlc_maximum_msat: None,
7943 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7944 .with_route_hints(vec![route_hint]).unwrap()
7945 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
7946 let route_params = RouteParameters::from_payment_params_and_value(
7947 payment_params, amt_msat);
7949 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
7951 let first_hop = get_channel_details(Some(1), nodes[0],
7952 channelmanager::provided_init_features(&config), 999_999);
7953 let first_hops = vec![first_hop];
7955 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
7956 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7957 &Default::default(), &random_seed_bytes).unwrap();
7958 assert_eq!(route.paths.len(), 1);
7959 assert_eq!(route.get_total_amount(), amt_msat);
7960 assert_eq!(route.paths[0].hops.len(), 2);
7961 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
7962 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
7963 assert_eq!(route.get_total_fees(), 123);
7965 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
7966 // for a first hop channel.
7967 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
7968 first_hop.outbound_scid_alias = Some(44);
7969 let first_hops = vec![first_hop];
7971 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
7972 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7973 &Default::default(), &random_seed_bytes);
7974 assert!(route_res.is_err());
7976 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
7977 // use the cheaper second hop of the route hint.
7978 let mut first_hop = get_channel_details(Some(1), nodes[0],
7979 channelmanager::provided_init_features(&config), 10_000_000);
7980 first_hop.outbound_scid_alias = Some(44);
7981 let first_hops = vec![first_hop];
7983 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
7984 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7985 &Default::default(), &random_seed_bytes).unwrap();
7986 assert_eq!(route.paths.len(), 1);
7987 assert_eq!(route.get_total_amount(), amt_msat);
7988 assert_eq!(route.paths[0].hops.len(), 2);
7989 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
7990 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
7991 assert_eq!(route.get_total_fees(), 123);
7995 fn allow_us_being_first_hint() {
7996 // Check that we consider a route hint even if we are the src of the first hop.
7997 let secp_ctx = Secp256k1::new();
7998 let logger = Arc::new(ln_test_utils::TestLogger::new());
7999 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8000 let scorer = ln_test_utils::TestScorer::new();
8001 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8002 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8003 let config = UserConfig::default();
8005 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8007 let amt_msat = 1_000_000;
8008 let dest_node_id = nodes[1];
8010 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8011 let first_hops = vec![first_hop];
8013 let route_hint = RouteHint(vec![RouteHintHop {
8014 src_node_id: our_node_id,
8015 short_channel_id: 44,
8018 proportional_millionths: 0,
8020 cltv_expiry_delta: 10,
8021 htlc_minimum_msat: None,
8022 htlc_maximum_msat: None,
8025 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8026 .with_route_hints(vec![route_hint]).unwrap()
8027 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8029 let route_params = RouteParameters::from_payment_params_and_value(
8030 payment_params, amt_msat);
8033 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8034 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8035 &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.get_total_fees(), 0);
8040 assert_eq!(route.paths[0].hops.len(), 1);
8042 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8046 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8047 pub(crate) mod bench_utils {
8051 use bitcoin::hashes::Hash;
8052 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8054 use crate::chain::transaction::OutPoint;
8055 use crate::routing::scoring::ScoreUpdate;
8056 use crate::sign::{EntropySource, KeysManager};
8057 use crate::ln::ChannelId;
8058 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8059 use crate::ln::features::Bolt11InvoiceFeatures;
8060 use crate::routing::gossip::NetworkGraph;
8061 use crate::util::config::UserConfig;
8062 use crate::util::ser::ReadableArgs;
8063 use crate::util::test_utils::TestLogger;
8065 /// Tries to open a network graph file, or panics with a URL to fetch it.
8066 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8067 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8068 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8069 .or_else(|_| { // Fall back to guessing based on the binary location
8070 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8071 let mut path = std::env::current_exe().unwrap();
8072 path.pop(); // lightning-...
8074 path.pop(); // debug
8075 path.pop(); // target
8076 path.push("lightning");
8077 path.push("net_graph-2023-01-18.bin");
8080 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8081 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8082 let mut path = std::env::current_exe().unwrap();
8083 path.pop(); // bench...
8085 path.pop(); // debug
8086 path.pop(); // target
8087 path.pop(); // bench
8088 path.push("lightning");
8089 path.push("net_graph-2023-01-18.bin");
8092 .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");
8093 #[cfg(require_route_graph_test)]
8094 return Ok(res.unwrap());
8095 #[cfg(not(require_route_graph_test))]
8099 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8100 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8103 pub(crate) fn payer_pubkey() -> PublicKey {
8104 let secp_ctx = Secp256k1::new();
8105 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8109 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8111 channel_id: ChannelId::new_zero(),
8112 counterparty: ChannelCounterparty {
8113 features: channelmanager::provided_init_features(&UserConfig::default()),
8115 unspendable_punishment_reserve: 0,
8116 forwarding_info: None,
8117 outbound_htlc_minimum_msat: None,
8118 outbound_htlc_maximum_msat: None,
8120 funding_txo: Some(OutPoint {
8121 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8124 short_channel_id: Some(1),
8125 inbound_scid_alias: None,
8126 outbound_scid_alias: None,
8127 channel_value_satoshis: 10_000_000_000,
8129 balance_msat: 10_000_000_000,
8130 outbound_capacity_msat: 10_000_000_000,
8131 next_outbound_htlc_minimum_msat: 0,
8132 next_outbound_htlc_limit_msat: 10_000_000_000,
8133 inbound_capacity_msat: 0,
8134 unspendable_punishment_reserve: None,
8135 confirmations_required: None,
8136 confirmations: None,
8137 force_close_spend_delay: None,
8139 is_channel_ready: true,
8142 inbound_htlc_minimum_msat: None,
8143 inbound_htlc_maximum_msat: None,
8145 feerate_sat_per_1000_weight: None,
8146 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8150 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8151 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8152 starting_amount: u64, route_count: usize,
8153 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8154 let payer = payer_pubkey();
8155 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8156 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8158 let nodes = graph.read_only().nodes().clone();
8159 let mut route_endpoints = Vec::new();
8160 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8161 // with some routes we picked being un-routable.
8162 for _ in 0..route_count * 3 / 2 {
8164 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8165 let src = PublicKey::from_slice(nodes.unordered_keys()
8166 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8167 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8168 let dst = PublicKey::from_slice(nodes.unordered_keys()
8169 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8170 let params = PaymentParameters::from_node_id(dst, 42)
8171 .with_bolt11_features(features.clone()).unwrap();
8172 let first_hop = first_hop(src);
8173 let amt_msat = starting_amount + seed % 1_000_000;
8174 let route_params = RouteParameters::from_payment_params_and_value(
8175 params.clone(), amt_msat);
8177 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8178 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8180 // ...and seed the scorer with success and failure data...
8181 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8182 let mut score_amt = seed % 1_000_000_000;
8184 // Generate fail/success paths for a wider range of potential amounts with
8185 // MPP enabled to give us a chance to apply penalties for more potential
8187 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8188 let params = PaymentParameters::from_node_id(dst, 42)
8189 .with_bolt11_features(mpp_features).unwrap();
8190 let route_params = RouteParameters::from_payment_params_and_value(
8191 params.clone(), score_amt);
8192 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8193 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8194 &random_seed_bytes);
8195 if let Ok(route) = route_res {
8196 for path in route.paths {
8197 if seed & 0x80 == 0 {
8198 scorer.payment_path_successful(&path);
8200 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8201 scorer.payment_path_failed(&path, short_channel_id);
8203 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8207 // If we couldn't find a path with a higer amount, reduce and try again.
8211 route_endpoints.push((first_hop, params, amt_msat));
8217 // Because we've changed channel scores, it's possible we'll take different routes to the
8218 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8219 // requires a too-high CLTV delta.
8220 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8221 let route_params = RouteParameters::from_payment_params_and_value(
8222 params.clone(), *amt_msat);
8223 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8224 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8226 route_endpoints.truncate(route_count);
8227 assert_eq!(route_endpoints.len(), route_count);
8235 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8236 use crate::sign::{EntropySource, KeysManager};
8237 use crate::ln::channelmanager;
8238 use crate::ln::features::Bolt11InvoiceFeatures;
8239 use crate::routing::gossip::NetworkGraph;
8240 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8241 use crate::util::config::UserConfig;
8242 use crate::util::logger::{Logger, Record};
8243 use crate::util::test_utils::TestLogger;
8245 use criterion::Criterion;
8247 struct DummyLogger {}
8248 impl Logger for DummyLogger {
8249 fn log(&self, _record: Record) {}
8252 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8253 let logger = TestLogger::new();
8254 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8255 let scorer = FixedPenaltyScorer::with_penalty(0);
8256 generate_routes(bench, &network_graph, scorer, &Default::default(),
8257 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8260 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8261 let logger = TestLogger::new();
8262 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8263 let scorer = FixedPenaltyScorer::with_penalty(0);
8264 generate_routes(bench, &network_graph, scorer, &Default::default(),
8265 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8266 "generate_mpp_routes_with_zero_penalty_scorer");
8269 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8270 let logger = TestLogger::new();
8271 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8272 let params = ProbabilisticScoringFeeParameters::default();
8273 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8274 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8275 "generate_routes_with_probabilistic_scorer");
8278 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8279 let logger = TestLogger::new();
8280 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8281 let params = ProbabilisticScoringFeeParameters::default();
8282 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8283 generate_routes(bench, &network_graph, scorer, ¶ms,
8284 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8285 "generate_mpp_routes_with_probabilistic_scorer");
8288 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8289 let logger = TestLogger::new();
8290 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8291 let params = ProbabilisticScoringFeeParameters::default();
8292 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8293 generate_routes(bench, &network_graph, scorer, ¶ms,
8294 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8295 "generate_large_mpp_routes_with_probabilistic_scorer");
8298 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8299 let logger = TestLogger::new();
8300 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8301 let mut params = ProbabilisticScoringFeeParameters::default();
8302 params.linear_success_probability = false;
8303 let scorer = ProbabilisticScorer::new(
8304 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8305 generate_routes(bench, &network_graph, scorer, ¶ms,
8306 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8307 "generate_routes_with_nonlinear_probabilistic_scorer");
8310 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8311 let logger = TestLogger::new();
8312 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8313 let mut params = ProbabilisticScoringFeeParameters::default();
8314 params.linear_success_probability = false;
8315 let scorer = ProbabilisticScorer::new(
8316 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8317 generate_routes(bench, &network_graph, scorer, ¶ms,
8318 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8319 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8322 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8323 let logger = TestLogger::new();
8324 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8325 let mut params = ProbabilisticScoringFeeParameters::default();
8326 params.linear_success_probability = false;
8327 let scorer = ProbabilisticScorer::new(
8328 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8329 generate_routes(bench, &network_graph, scorer, ¶ms,
8330 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8331 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8334 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8335 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8336 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8337 bench_name: &'static str,
8339 let payer = bench_utils::payer_pubkey();
8340 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8341 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8343 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8344 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8346 // ...then benchmark finding paths between the nodes we learned.
8348 bench.bench_function(bench_name, |b| b.iter(|| {
8349 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8350 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8351 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8352 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());