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, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
134 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
135 source, target, short_channel_id
137 let usage = ChannelUsage {
138 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
142 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
144 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
149 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
150 /// in-use channel liquidity.
152 pub struct InFlightHtlcs(
153 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
154 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
155 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
157 HashMap<(u64, bool), u64>
161 /// Constructs an empty `InFlightHtlcs`.
162 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
164 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
165 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
166 if path.hops.is_empty() { return };
168 let mut cumulative_msat = 0;
169 if let Some(tail) = &path.blinded_tail {
170 cumulative_msat += tail.final_value_msat;
173 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
174 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
175 // the router excludes the payer node. In the following lines, the payer's information is
176 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
177 // in our sliding window of two.
178 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
179 .map(|hop| hop.pubkey)
180 .chain(core::iter::once(payer_node_id));
182 // Taking the reversed vector from above, we zip it with just the reversed hops list to
183 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
184 // the total amount sent.
185 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
186 cumulative_msat += next_hop.fee_msat;
188 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
189 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
190 .or_insert(cumulative_msat);
194 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
196 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
198 .entry((channel_scid, source < target))
199 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
200 .or_insert(used_msat);
203 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
205 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
206 self.0.get(&(channel_scid, source < target)).map(|v| *v)
210 impl Writeable for InFlightHtlcs {
211 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
214 impl Readable for InFlightHtlcs {
215 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
216 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
217 Ok(Self(infight_map))
221 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
222 /// that leads to it.
223 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
224 pub struct RouteHop {
225 /// The node_id of the node at this hop.
226 pub pubkey: PublicKey,
227 /// The node_announcement features of the node at this hop. For the last hop, these may be
228 /// amended to match the features present in the invoice this node generated.
229 pub node_features: NodeFeatures,
230 /// The channel that should be used from the previous hop to reach this node.
231 pub short_channel_id: u64,
232 /// The channel_announcement features of the channel that should be used from the previous hop
233 /// to reach this node.
234 pub channel_features: ChannelFeatures,
235 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
236 /// If this is the last hop in [`Path::hops`]:
237 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
238 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
240 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
242 /// The CLTV delta added for this hop.
243 /// If this is the last hop in [`Path::hops`]:
244 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
245 /// * otherwise, this is the CLTV delta expected at the destination
247 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
248 pub cltv_expiry_delta: u32,
249 /// Indicates whether this hop is possibly announced in the public network graph.
251 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
252 /// either know for sure it's announced in the public graph, or if any public channels exist
253 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
254 /// the channel to be unannounced.
256 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
257 pub maybe_announced_channel: bool,
260 impl_writeable_tlv_based!(RouteHop, {
261 (0, pubkey, required),
262 (1, maybe_announced_channel, (default_value, true)),
263 (2, node_features, required),
264 (4, short_channel_id, required),
265 (6, channel_features, required),
266 (8, fee_msat, required),
267 (10, cltv_expiry_delta, required),
270 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
271 /// their [`Bolt12Invoice`].
273 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
274 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
275 pub struct BlindedTail {
276 /// The hops of the [`BlindedPath`] provided by the recipient.
278 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
279 pub hops: Vec<BlindedHop>,
280 /// The blinding point of the [`BlindedPath`] provided by the recipient.
282 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
283 pub blinding_point: PublicKey,
284 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
285 /// inferring the destination. May be 0.
286 pub excess_final_cltv_expiry_delta: u32,
287 /// The total amount paid on this [`Path`], excluding the fees.
288 pub final_value_msat: u64,
291 impl_writeable_tlv_based!(BlindedTail, {
292 (0, hops, required_vec),
293 (2, blinding_point, required),
294 (4, excess_final_cltv_expiry_delta, required),
295 (6, final_value_msat, required),
298 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
299 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
300 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
302 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
303 pub hops: Vec<RouteHop>,
304 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
305 pub blinded_tail: Option<BlindedTail>,
309 /// Gets the fees for a given path, excluding any excess paid to the recipient.
310 pub fn fee_msat(&self) -> u64 {
311 match &self.blinded_tail {
312 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
314 // Do not count last hop of each path since that's the full value of the payment
315 self.hops.split_last().map_or(0,
316 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
321 /// Gets the total amount paid on this [`Path`], excluding the fees.
322 pub fn final_value_msat(&self) -> u64 {
323 match &self.blinded_tail {
324 Some(blinded_tail) => blinded_tail.final_value_msat,
325 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
329 /// Gets the final hop's CLTV expiry delta.
330 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
331 match &self.blinded_tail {
333 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
338 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
339 /// it can take multiple paths. Each path is composed of one or more hops through the network.
340 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
342 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
343 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
345 pub paths: Vec<Path>,
346 /// The `route_params` parameter passed to [`find_route`].
348 /// This is used by `ChannelManager` to track information which may be required for retries.
350 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
351 pub route_params: Option<RouteParameters>,
355 /// Returns the total amount of fees paid on this [`Route`].
357 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
358 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
359 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
361 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
362 pub fn get_total_fees(&self) -> u64 {
363 let overpaid_value_msat = self.route_params.as_ref()
364 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
365 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
368 /// Returns the total amount paid on this [`Route`], excluding the fees.
370 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
371 /// we had to reach the [`htlc_minimum_msat`] limits.
373 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
374 pub fn get_total_amount(&self) -> u64 {
375 self.paths.iter().map(|path| path.final_value_msat()).sum()
379 impl fmt::Display for Route {
380 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
381 log_route!(self).fmt(f)
385 const SERIALIZATION_VERSION: u8 = 1;
386 const MIN_SERIALIZATION_VERSION: u8 = 1;
388 impl Writeable for Route {
389 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
390 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
391 (self.paths.len() as u64).write(writer)?;
392 let mut blinded_tails = Vec::new();
393 for path in self.paths.iter() {
394 (path.hops.len() as u8).write(writer)?;
395 for (idx, hop) in path.hops.iter().enumerate() {
397 if let Some(blinded_tail) = &path.blinded_tail {
398 if blinded_tails.is_empty() {
399 blinded_tails = Vec::with_capacity(path.hops.len());
401 blinded_tails.push(None);
404 blinded_tails.push(Some(blinded_tail));
405 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
408 write_tlv_fields!(writer, {
409 // For compatibility with LDK versions prior to 0.0.117, we take the individual
410 // RouteParameters' fields and reconstruct them on read.
411 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
412 (2, blinded_tails, optional_vec),
413 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
414 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
420 impl Readable for Route {
421 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
422 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
423 let path_count: u64 = Readable::read(reader)?;
424 if path_count == 0 { return Err(DecodeError::InvalidValue); }
425 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
426 let mut min_final_cltv_expiry_delta = u32::max_value();
427 for _ in 0..path_count {
428 let hop_count: u8 = Readable::read(reader)?;
429 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
430 for _ in 0..hop_count {
431 hops.push(Readable::read(reader)?);
433 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
434 min_final_cltv_expiry_delta =
435 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
436 paths.push(Path { hops, blinded_tail: None });
438 _init_and_read_len_prefixed_tlv_fields!(reader, {
439 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
440 (2, blinded_tails, optional_vec),
441 (3, final_value_msat, option),
442 (5, max_total_routing_fee_msat, option)
444 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
445 if blinded_tails.len() != 0 {
446 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
447 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
448 path.blinded_tail = blinded_tail_opt;
452 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
453 let route_params = match (payment_params, final_value_msat) {
454 (Some(payment_params), Some(final_value_msat)) => {
455 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
460 Ok(Route { paths, route_params })
464 /// Parameters needed to find a [`Route`].
466 /// Passed to [`find_route`] and [`build_route_from_hops`].
467 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
468 pub struct RouteParameters {
469 /// The parameters of the failed payment path.
470 pub payment_params: PaymentParameters,
472 /// The amount in msats sent on the failed payment path.
473 pub final_value_msat: u64,
475 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
477 /// This limit also applies to the total fees that may arise while retrying failed payment
480 /// Note that values below a few sats may result in some paths being spuriously ignored.
481 pub max_total_routing_fee_msat: Option<u64>,
484 impl RouteParameters {
485 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
487 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
488 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
489 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
493 impl Writeable for RouteParameters {
494 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
495 write_tlv_fields!(writer, {
496 (0, self.payment_params, required),
497 (1, self.max_total_routing_fee_msat, option),
498 (2, self.final_value_msat, required),
499 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
500 // `RouteParameters` directly. For compatibility, we write it here.
501 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
507 impl Readable for RouteParameters {
508 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
509 _init_and_read_len_prefixed_tlv_fields!(reader, {
510 (0, payment_params, (required: ReadableArgs, 0)),
511 (1, max_total_routing_fee_msat, option),
512 (2, final_value_msat, required),
513 (4, final_cltv_delta, option),
515 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
516 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
517 if final_cltv_expiry_delta == &0 {
518 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
523 final_value_msat: final_value_msat.0.unwrap(),
524 max_total_routing_fee_msat,
529 /// Maximum total CTLV difference we allow for a full payment path.
530 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
532 /// Maximum number of paths we allow an (MPP) payment to have.
533 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
534 // limits, but for now more than 10 paths likely carries too much one-path failure.
535 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
537 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
539 // The median hop CLTV expiry delta currently seen in the network.
540 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
542 // During routing, we only consider paths shorter than our maximum length estimate.
543 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
544 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
545 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
547 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
548 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
549 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
550 // (payment_secret and total_msat) = 93 bytes for the final hop.
551 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
552 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
553 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
555 /// Information used to route a payment.
556 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
557 pub struct PaymentParameters {
558 /// Information about the payee, such as their features and route hints for their channels.
561 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
562 pub expiry_time: Option<u64>,
564 /// The maximum total CLTV delta we accept for the route.
565 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
566 pub max_total_cltv_expiry_delta: u32,
568 /// The maximum number of paths that may be used by (MPP) payments.
569 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
570 pub max_path_count: u8,
572 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
573 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
574 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
575 /// increasing failure probability for those paths.
577 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
578 /// restriction have been found. While paths which meet this criteria will be searched for, it
579 /// is ultimately up to the scorer to select them over other paths.
581 /// A value of 0 will allow payments up to and including a channel's total announced usable
582 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
585 pub max_channel_saturation_power_of_half: u8,
587 /// A list of SCIDs which this payment was previously attempted over and which caused the
588 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
590 pub previously_failed_channels: Vec<u64>,
593 impl Writeable for PaymentParameters {
594 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
595 let mut clear_hints = &vec![];
596 let mut blinded_hints = &vec![];
598 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
599 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
601 write_tlv_fields!(writer, {
602 (0, self.payee.node_id(), option),
603 (1, self.max_total_cltv_expiry_delta, required),
604 (2, self.payee.features(), option),
605 (3, self.max_path_count, required),
606 (4, *clear_hints, required_vec),
607 (5, self.max_channel_saturation_power_of_half, required),
608 (6, self.expiry_time, option),
609 (7, self.previously_failed_channels, required_vec),
610 (8, *blinded_hints, optional_vec),
611 (9, self.payee.final_cltv_expiry_delta(), option),
617 impl ReadableArgs<u32> for PaymentParameters {
618 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
619 _init_and_read_len_prefixed_tlv_fields!(reader, {
620 (0, payee_pubkey, option),
621 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
622 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
623 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
624 (4, clear_route_hints, required_vec),
625 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
626 (6, expiry_time, option),
627 (7, previously_failed_channels, optional_vec),
628 (8, blinded_route_hints, optional_vec),
629 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
631 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
632 let payee = if blinded_route_hints.len() != 0 {
633 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
635 route_hints: blinded_route_hints,
636 features: features.and_then(|f: Features| f.bolt12()),
640 route_hints: clear_route_hints,
641 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
642 features: features.and_then(|f| f.bolt11()),
643 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
647 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
648 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
650 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
652 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
658 impl PaymentParameters {
659 /// Creates a payee with the node id of the given `pubkey`.
661 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
663 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
665 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
667 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
668 max_path_count: DEFAULT_MAX_PATH_COUNT,
669 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
670 previously_failed_channels: Vec::new(),
674 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
676 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
679 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
680 /// whether your router will be allowed to find a multi-part route for this payment. If you
681 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
682 /// [`RecipientOnionFields::secret_only`].
684 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
685 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
686 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
687 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
688 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
691 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
692 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
693 /// [`PaymentParameters::expiry_time`].
694 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
695 Self::blinded(invoice.payment_paths().to_vec())
696 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
697 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
700 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
701 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
703 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
705 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
706 max_path_count: DEFAULT_MAX_PATH_COUNT,
707 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
708 previously_failed_channels: Vec::new(),
712 /// Includes the payee's features. Errors if the parameters were not initialized with
713 /// [`PaymentParameters::from_bolt12_invoice`].
715 /// This is not exported to bindings users since bindings don't support move semantics
716 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
718 Payee::Clear { .. } => Err(()),
719 Payee::Blinded { route_hints, .. } =>
720 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
724 /// Includes the payee's features. Errors if the parameters were initialized with
725 /// [`PaymentParameters::from_bolt12_invoice`].
727 /// This is not exported to bindings users since bindings don't support move semantics
728 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
730 Payee::Blinded { .. } => Err(()),
731 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
733 payee: Payee::Clear {
734 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
740 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
741 /// [`PaymentParameters::from_bolt12_invoice`].
743 /// This is not exported to bindings users since bindings don't support move semantics
744 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
746 Payee::Blinded { .. } => Err(()),
747 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
749 payee: Payee::Clear {
750 route_hints, node_id, features, final_cltv_expiry_delta,
756 /// Includes a payment expiration in seconds relative to the UNIX epoch.
758 /// This is not exported to bindings users since bindings don't support move semantics
759 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
760 Self { expiry_time: Some(expiry_time), ..self }
763 /// Includes a limit for the total CLTV expiry delta which is considered during routing
765 /// This is not exported to bindings users since bindings don't support move semantics
766 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
767 Self { max_total_cltv_expiry_delta, ..self }
770 /// Includes a limit for the maximum number of payment paths that may be used.
772 /// This is not exported to bindings users since bindings don't support move semantics
773 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
774 Self { max_path_count, ..self }
777 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
778 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
780 /// This is not exported to bindings users since bindings don't support move semantics
781 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
782 Self { max_channel_saturation_power_of_half, ..self }
786 /// The recipient of a payment, differing based on whether they've hidden their identity with route
788 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
790 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
791 /// will be included in the final [`Route`].
793 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
795 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
796 /// Features supported by the payee.
798 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
800 features: Option<Bolt12InvoiceFeatures>,
802 /// The recipient included these route hints in their BOLT11 invoice.
804 /// The node id of the payee.
806 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
807 route_hints: Vec<RouteHint>,
808 /// Features supported by the payee.
810 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
811 /// does not contain any features.
813 /// [`for_keysend`]: PaymentParameters::for_keysend
814 features: Option<Bolt11InvoiceFeatures>,
815 /// The minimum CLTV delta at the end of the route. This value must not be zero.
816 final_cltv_expiry_delta: u32,
821 fn node_id(&self) -> Option<PublicKey> {
823 Self::Clear { node_id, .. } => Some(*node_id),
827 fn node_features(&self) -> Option<NodeFeatures> {
829 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
830 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
833 fn supports_basic_mpp(&self) -> bool {
835 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
836 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
839 fn features(&self) -> Option<FeaturesRef> {
841 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
842 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
845 fn final_cltv_expiry_delta(&self) -> Option<u32> {
847 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
851 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
853 Self::Blinded { route_hints, .. } => &route_hints[..],
854 Self::Clear { .. } => &[]
858 fn unblinded_route_hints(&self) -> &[RouteHint] {
860 Self::Blinded { .. } => &[],
861 Self::Clear { route_hints, .. } => &route_hints[..]
866 enum FeaturesRef<'a> {
867 Bolt11(&'a Bolt11InvoiceFeatures),
868 Bolt12(&'a Bolt12InvoiceFeatures),
871 Bolt11(Bolt11InvoiceFeatures),
872 Bolt12(Bolt12InvoiceFeatures),
876 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
878 Self::Bolt12(f) => Some(f),
882 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
884 Self::Bolt11(f) => Some(f),
890 impl<'a> Writeable for FeaturesRef<'a> {
891 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
893 Self::Bolt11(f) => Ok(f.write(w)?),
894 Self::Bolt12(f) => Ok(f.write(w)?),
899 impl ReadableArgs<bool> for Features {
900 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
901 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
902 Ok(Self::Bolt12(Readable::read(reader)?))
906 /// A list of hops along a payment path terminating with a channel to the recipient.
907 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
908 pub struct RouteHint(pub Vec<RouteHintHop>);
910 impl Writeable for RouteHint {
911 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
912 (self.0.len() as u64).write(writer)?;
913 for hop in self.0.iter() {
920 impl Readable for RouteHint {
921 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
922 let hop_count: u64 = Readable::read(reader)?;
923 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
924 for _ in 0..hop_count {
925 hops.push(Readable::read(reader)?);
931 /// A channel descriptor for a hop along a payment path.
932 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
933 pub struct RouteHintHop {
934 /// The node_id of the non-target end of the route
935 pub src_node_id: PublicKey,
936 /// The short_channel_id of this channel
937 pub short_channel_id: u64,
938 /// The fees which must be paid to use this channel
939 pub fees: RoutingFees,
940 /// The difference in CLTV values between this node and the next node.
941 pub cltv_expiry_delta: u16,
942 /// The minimum value, in msat, which must be relayed to the next hop.
943 pub htlc_minimum_msat: Option<u64>,
944 /// The maximum value in msat available for routing with a single HTLC.
945 pub htlc_maximum_msat: Option<u64>,
948 impl_writeable_tlv_based!(RouteHintHop, {
949 (0, src_node_id, required),
950 (1, htlc_minimum_msat, option),
951 (2, short_channel_id, required),
952 (3, htlc_maximum_msat, option),
954 (6, cltv_expiry_delta, required),
957 #[derive(Eq, PartialEq)]
958 struct RouteGraphNode {
960 lowest_fee_to_node: u64,
961 total_cltv_delta: u32,
962 // The maximum value a yet-to-be-constructed payment path might flow through this node.
963 // This value is upper-bounded by us by:
964 // - how much is needed for a path being constructed
965 // - how much value can channels following this node (up to the destination) can contribute,
966 // considering their capacity and fees
967 value_contribution_msat: u64,
968 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
969 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
970 path_htlc_minimum_msat: u64,
971 /// All penalties incurred from this hop on the way to the destination, as calculated using
973 path_penalty_msat: u64,
974 /// The number of hops walked up to this node.
975 path_length_to_node: u8,
978 impl cmp::Ord for RouteGraphNode {
979 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
980 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
981 .saturating_add(other.path_penalty_msat);
982 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
983 .saturating_add(self.path_penalty_msat);
984 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
988 impl cmp::PartialOrd for RouteGraphNode {
989 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
990 Some(self.cmp(other))
994 /// A wrapper around the various hop representations.
996 /// Can be used to examine the properties of a hop,
997 /// potentially to decide whether to include it in a route.
998 #[derive(Clone, Debug)]
999 pub enum CandidateRouteHop<'a> {
1000 /// A hop from the payer, where the outbound liquidity is known.
1002 /// Channel details of the first hop
1003 /// [`ChannelDetails::get_outbound_payment_scid`] is assumed
1004 /// to always return `Some(scid)`
1005 /// this assumption is checked in [`find_route`] method.
1006 details: &'a ChannelDetails,
1007 /// The node id of the payer.
1009 /// Can be accessed via `source` method.
1012 /// A hop found in the [`ReadOnlyNetworkGraph`],
1013 /// where the channel capacity may be unknown.
1015 /// channel info of the hop.
1016 info: DirectedChannelInfo<'a>,
1017 /// short_channel_id of the channel.
1018 short_channel_id: u64,
1020 /// A hop to the payee found in the BOLT 11 payment invoice,
1021 /// though not necessarily a direct
1024 /// Hint provides information about a private hop,
1025 /// needed while routing through a private
1027 hint: &'a RouteHintHop,
1028 /// Node id of the next hop in route.
1029 target_node_id: NodeId
1031 /// The payee's identity is concealed behind
1032 /// blinded paths provided in a BOLT 12 invoice.
1034 /// Hint provides information about a blinded hop,
1035 /// needed while routing through a blinded path.
1036 /// `BlindedPayInfo` provides information needed about the
1037 /// payment while routing through a blinded path.
1038 /// `BlindedPath` is the blinded path to the destination.
1039 hint: &'a (BlindedPayInfo, BlindedPath),
1040 /// Index of the hint in the original list of blinded hints.
1041 /// Provided to uniquely identify a hop as we are
1045 /// Similar to [`Self::Blinded`], but the path here
1046 /// has 1 blinded hop. `BlindedPayInfo` provided
1047 /// for 1-hop blinded paths is ignored
1048 /// because it is meant to apply to the hops *between* the
1049 /// introduction node and the destination.
1050 /// Useful for tracking that we need to include a blinded
1051 /// path at the end of our [`Route`].
1053 /// Hint provides information about a single blinded hop,
1054 /// needed while routing through a one hop blinded path.
1055 /// `BlindedPayInfo` is ignored here.
1056 /// `BlindedPath` is the blinded path to the destination.
1057 hint: &'a (BlindedPayInfo, BlindedPath),
1058 /// Index of the hint in the original list of blinded hints.
1059 /// Provided to uniquely identify a hop as we are route building.
1064 impl<'a> CandidateRouteHop<'a> {
1065 /// Returns short_channel_id if known.
1066 /// For `FirstHop` we assume [`ChannelDetails::get_outbound_payment_scid`] is always set, this assumption is checked in
1067 /// [`find_route`] method.
1068 /// For `Blinded` and `OneHopBlinded` we return `None` because next hop is not known.
1069 pub fn short_channel_id(&self) -> Option<u64> {
1071 CandidateRouteHop::FirstHop { details, .. } => Some(details.get_outbound_payment_scid().unwrap()),
1072 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1073 CandidateRouteHop::PrivateHop { hint, .. } => Some(hint.short_channel_id),
1074 CandidateRouteHop::Blinded { .. } => None,
1075 CandidateRouteHop::OneHopBlinded { .. } => None,
1079 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1080 fn features(&self) -> ChannelFeatures {
1082 CandidateRouteHop::FirstHop { details, .. } => details.counterparty.features.to_context(),
1083 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1084 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1085 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1086 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1090 /// Returns cltv_expiry_delta for this hop.
1091 pub fn cltv_expiry_delta(&self) -> u32 {
1093 CandidateRouteHop::FirstHop { .. } => 0,
1094 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1095 CandidateRouteHop::PrivateHop { hint, .. } => hint.cltv_expiry_delta as u32,
1096 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1097 CandidateRouteHop::OneHopBlinded { .. } => 0,
1101 /// Returns the htlc_minimum_msat for this hop.
1102 pub fn htlc_minimum_msat(&self) -> u64 {
1104 CandidateRouteHop::FirstHop { details, .. } => details.next_outbound_htlc_minimum_msat,
1105 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1106 CandidateRouteHop::PrivateHop { hint, .. } => hint.htlc_minimum_msat.unwrap_or(0),
1107 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1108 CandidateRouteHop::OneHopBlinded { .. } => 0,
1112 /// Returns the fees for this hop.
1113 pub fn fees(&self) -> RoutingFees {
1115 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1116 base_msat: 0, proportional_millionths: 0,
1118 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1119 CandidateRouteHop::PrivateHop { hint, .. } => hint.fees,
1120 CandidateRouteHop::Blinded { hint, .. } => {
1122 base_msat: hint.0.fee_base_msat,
1123 proportional_millionths: hint.0.fee_proportional_millionths
1126 CandidateRouteHop::OneHopBlinded { .. } =>
1127 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1131 fn effective_capacity(&self) -> EffectiveCapacity {
1133 CandidateRouteHop::FirstHop { details, .. } => EffectiveCapacity::ExactLiquidity {
1134 liquidity_msat: details.next_outbound_htlc_limit_msat,
1136 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1137 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. } =>
1138 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1139 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. } =>
1140 EffectiveCapacity::Infinite,
1141 CandidateRouteHop::Blinded { hint, .. } =>
1142 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1143 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1147 /// Returns the id of this hop.
1148 /// For `Blinded` and `OneHopBlinded` we return `CandidateHopId::Blinded` with `hint_idx` because we don't know the channel id.
1149 /// For any other option we return `CandidateHopId::Clear` because we know the channel id and the direction.
1150 pub fn id(&self) -> CandidateHopId {
1152 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1153 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1154 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1157 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1159 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1165 /// Returns the source node id of current hop.
1167 /// Source node id refers to the hop forwarding the payment.
1169 /// For `FirstHop` we return payer's node id.
1170 pub fn source(&self) -> NodeId {
1172 CandidateRouteHop::FirstHop { node_id, .. } => *node_id,
1173 CandidateRouteHop::PublicHop { info, .. } => *info.source(),
1174 CandidateRouteHop::PrivateHop { hint, .. } => hint.src_node_id.into(),
1175 CandidateRouteHop::Blinded { hint, .. } => hint.1.introduction_node_id.into(),
1176 CandidateRouteHop::OneHopBlinded { hint, .. } => hint.1.introduction_node_id.into()
1179 /// Returns the target node id of this hop, if known.
1181 /// Target node id refers to the hop receiving the payment.
1183 /// For `Blinded` and `OneHopBlinded` we return `None` because next hop is blinded.
1184 pub fn target(&self) -> Option<NodeId> {
1186 CandidateRouteHop::FirstHop { details, .. } => Some(details.counterparty.node_id.into()),
1187 CandidateRouteHop::PublicHop { info, .. } => Some(*info.target()),
1188 CandidateRouteHop::PrivateHop { target_node_id, .. } => Some(*target_node_id),
1189 CandidateRouteHop::Blinded { .. } => None,
1190 CandidateRouteHop::OneHopBlinded { .. } => None,
1195 /// A wrapper around the various hop id representations.
1197 /// `CandidateHopId::Clear` is used to identify a hop with a known short channel id and direction.
1198 /// `CandidateHopId::Blinded` is used to identify a blinded hop `hint_idx`.
1199 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1200 pub enum CandidateHopId {
1201 /// Contains (scid, src_node_id < target_node_id)
1203 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1208 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1209 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1211 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1212 EffectiveCapacity::Infinite => u64::max_value(),
1213 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1214 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1215 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1216 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1217 // expected to have been generated from up-to-date capacity information.
1218 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1219 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1220 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1224 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1225 -> bool where I1::Item: PartialEq<I2::Item> {
1227 let a = iter_a.next();
1228 let b = iter_b.next();
1229 if a.is_none() && b.is_none() { return true; }
1230 if a.is_none() || b.is_none() { return false; }
1231 if a.unwrap().ne(&b.unwrap()) { return false; }
1235 /// It's useful to keep track of the hops associated with the fees required to use them,
1236 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1237 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1238 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1240 struct PathBuildingHop<'a> {
1241 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1242 // is a larger refactor and will require careful performance analysis.
1244 candidate: CandidateRouteHop<'a>,
1247 /// All the fees paid *after* this channel on the way to the destination
1248 next_hops_fee_msat: u64,
1249 /// Fee paid for the use of the current channel (see candidate.fees()).
1250 /// The value will be actually deducted from the counterparty balance on the previous link.
1251 hop_use_fee_msat: u64,
1252 /// Used to compare channels when choosing the for routing.
1253 /// Includes paying for the use of a hop and the following hops, as well as
1254 /// an estimated cost of reaching this hop.
1255 /// Might get stale when fees are recomputed. Primarily for internal use.
1256 total_fee_msat: u64,
1257 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1258 /// walk and may be invalid thereafter.
1259 path_htlc_minimum_msat: u64,
1260 /// All penalties incurred from this channel on the way to the destination, as calculated using
1261 /// channel scoring.
1262 path_penalty_msat: u64,
1263 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1264 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1265 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1266 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1267 /// avoid processing them again.
1268 was_processed: bool,
1269 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1270 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1271 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1272 // value_contribution_msat, which requires tracking it here. See comments below where it is
1273 // used for more info.
1274 value_contribution_msat: u64,
1277 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1278 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1279 let mut debug_struct = f.debug_struct("PathBuildingHop");
1281 .field("node_id", &self.node_id)
1282 .field("short_channel_id", &self.candidate.short_channel_id())
1283 .field("total_fee_msat", &self.total_fee_msat)
1284 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1285 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1286 .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)))
1287 .field("path_penalty_msat", &self.path_penalty_msat)
1288 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1289 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1290 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1291 let debug_struct = debug_struct
1292 .field("value_contribution_msat", &self.value_contribution_msat);
1293 debug_struct.finish()
1297 // Instantiated with a list of hops with correct data in them collected during path finding,
1298 // an instance of this struct should be further modified only via given methods.
1300 struct PaymentPath<'a> {
1301 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1304 impl<'a> PaymentPath<'a> {
1305 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1306 fn get_value_msat(&self) -> u64 {
1307 self.hops.last().unwrap().0.fee_msat
1310 fn get_path_penalty_msat(&self) -> u64 {
1311 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1314 fn get_total_fee_paid_msat(&self) -> u64 {
1315 if self.hops.len() < 1 {
1319 // Can't use next_hops_fee_msat because it gets outdated.
1320 for (i, (hop, _)) in self.hops.iter().enumerate() {
1321 if i != self.hops.len() - 1 {
1322 result += hop.fee_msat;
1328 fn get_cost_msat(&self) -> u64 {
1329 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1332 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1333 // to change fees may result in an inconsistency.
1335 // Sometimes we call this function right after constructing a path which is inconsistent in
1336 // that it the value being transferred has decreased while we were doing path finding, leading
1337 // to the fees being paid not lining up with the actual limits.
1339 // Note that this function is not aware of the available_liquidity limit, and thus does not
1340 // support increasing the value being transferred beyond what was selected during the initial
1343 // Returns the amount that this path contributes to the total payment value, which may be greater
1344 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1345 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1346 let mut extra_contribution_msat = 0;
1347 let mut total_fee_paid_msat = 0 as u64;
1348 for i in (0..self.hops.len()).rev() {
1349 let last_hop = i == self.hops.len() - 1;
1351 // For non-last-hop, this value will represent the fees paid on the current hop. It
1352 // will consist of the fees for the use of the next hop, and extra fees to match
1353 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1354 let mut cur_hop_fees_msat = 0;
1356 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1359 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1360 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1361 cur_hop.path_penalty_msat += extra_contribution_msat;
1362 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1363 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1364 // set it too high just to maliciously take more fees by exploiting this
1365 // match htlc_minimum_msat logic.
1366 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1367 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1368 // Note that there is a risk that *previous hops* (those closer to us, as we go
1369 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1371 // This might make us end up with a broken route, although this should be super-rare
1372 // in practice, both because of how healthy channels look like, and how we pick
1373 // channels in add_entry.
1374 // Also, this can't be exploited more heavily than *announce a free path and fail
1376 cur_hop_transferred_amount_msat += extra_fees_msat;
1378 // We remember and return the extra fees on the final hop to allow accounting for
1379 // them in the path's value contribution.
1381 extra_contribution_msat = extra_fees_msat;
1383 total_fee_paid_msat += extra_fees_msat;
1384 cur_hop_fees_msat += extra_fees_msat;
1389 // Final hop is a special case: it usually has just value_msat (by design), but also
1390 // it still could overpay for the htlc_minimum_msat.
1391 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1393 // Propagate updated fees for the use of the channels to one hop back, where they
1394 // will be actually paid (fee_msat). The last hop is handled above separately.
1395 cur_hop.fee_msat = cur_hop_fees_msat;
1398 // Fee for the use of the current hop which will be deducted on the previous hop.
1399 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1400 // this channel is free for us.
1402 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1403 cur_hop.hop_use_fee_msat = new_fee;
1404 total_fee_paid_msat += new_fee;
1406 // It should not be possible because this function is called only to reduce the
1407 // value. In that case, compute_fee was already called with the same fees for
1408 // larger amount and there was no overflow.
1413 value_msat + extra_contribution_msat
1418 /// Calculate the fees required to route the given amount over a channel with the given fees.
1419 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1420 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1421 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1425 /// Calculate the fees required to route the given amount over a channel with the given fees,
1426 /// saturating to [`u64::max_value`].
1427 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1428 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1429 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1430 .saturating_add(channel_fees.base_msat as u64)
1433 /// The default `features` we assume for a node in a route, when no `features` are known about that
1436 /// Default features are:
1437 /// * variable_length_onion_optional
1438 fn default_node_features() -> NodeFeatures {
1439 let mut features = NodeFeatures::empty();
1440 features.set_variable_length_onion_optional();
1444 struct LoggedPayeePubkey(Option<PublicKey>);
1445 impl fmt::Display for LoggedPayeePubkey {
1446 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1449 "payee node id ".fmt(f)?;
1453 "blinded payee".fmt(f)
1459 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1460 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1461 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1463 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1464 "blinded route hint with introduction node id ".fmt(f)?;
1465 hint.1.introduction_node_id.fmt(f)?;
1466 " and blinding point ".fmt(f)?;
1467 hint.1.blinding_point.fmt(f)
1469 CandidateRouteHop::FirstHop { .. } => {
1470 "first hop with SCID ".fmt(f)?;
1471 self.0.short_channel_id().unwrap().fmt(f)
1473 CandidateRouteHop::PrivateHop { .. } => {
1474 "route hint with SCID ".fmt(f)?;
1475 self.0.short_channel_id().unwrap().fmt(f)
1479 self.0.short_channel_id().unwrap().fmt(f)
1486 fn sort_first_hop_channels(
1487 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1488 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1490 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1491 // most like to use.
1493 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1494 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1497 // Second, because simply always sorting in descending order would always use our largest
1498 // available outbound capacity, needlessly fragmenting our available channel capacities,
1499 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1500 // which have enough, but not too much, capacity for the payment.
1502 // Available outbound balances factor in liquidity already reserved for previously found paths.
1503 channels.sort_unstable_by(|chan_a, chan_b| {
1504 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1505 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1506 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1507 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1508 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1509 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1510 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1511 // Sort in descending order
1512 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1514 // Sort in ascending order
1515 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1520 /// Finds a route from us (payer) to the given target node (payee).
1522 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1523 /// in the given [`RouteParameters::payment_params`].
1524 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1526 /// Private routing paths between a public node and the target may be included in the `payee` field
1527 /// of [`RouteParameters::payment_params`].
1529 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1530 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1531 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1533 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1534 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1535 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1539 /// Panics if first_hops contains channels without `short_channel_id`s;
1540 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1542 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1543 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1544 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1545 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1546 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1547 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1548 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1549 ) -> Result<Route, LightningError>
1550 where L::Target: Logger, GL::Target: Logger {
1551 let graph_lock = network_graph.read_only();
1552 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1553 scorer, score_params, random_seed_bytes)?;
1554 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1558 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1559 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1560 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1561 _random_seed_bytes: &[u8; 32]
1562 ) -> Result<Route, LightningError>
1563 where L::Target: Logger {
1565 let payment_params = &route_params.payment_params;
1566 let final_value_msat = route_params.final_value_msat;
1567 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1568 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1569 // so use a dummy id for this in the blinded case.
1570 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1571 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1572 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1573 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1574 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1576 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1577 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1579 if our_node_id == maybe_dummy_payee_node_id {
1580 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1583 if final_value_msat > MAX_VALUE_MSAT {
1584 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1587 if final_value_msat == 0 {
1588 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1591 match &payment_params.payee {
1592 Payee::Clear { route_hints, node_id, .. } => {
1593 for route in route_hints.iter() {
1594 for hop in &route.0 {
1595 if hop.src_node_id == *node_id {
1596 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1601 Payee::Blinded { route_hints, .. } => {
1602 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1603 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});
1605 for (_, blinded_path) in route_hints.iter() {
1606 if blinded_path.blinded_hops.len() == 0 {
1607 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1608 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1609 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1610 } else if blinded_path.blinded_hops.len() == 1 &&
1611 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1612 && p.introduction_node_id != blinded_path.introduction_node_id)
1614 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1619 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1620 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1621 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});
1624 // The general routing idea is the following:
1625 // 1. Fill first/last hops communicated by the caller.
1626 // 2. Attempt to construct a path from payer to payee for transferring
1627 // any ~sufficient (described later) value.
1628 // If succeed, remember which channels were used and how much liquidity they have available,
1629 // so that future paths don't rely on the same liquidity.
1630 // 3. Proceed to the next step if:
1631 // - we hit the recommended target value;
1632 // - OR if we could not construct a new path. Any next attempt will fail too.
1633 // Otherwise, repeat step 2.
1634 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1635 // (not recommended value).
1636 // 5. If yes, proceed. If not, fail routing.
1637 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1638 // transferred up to the transfer target value.
1639 // 7. Reduce the value of the last path until we are sending only the target value.
1640 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1641 // them so that we're not sending two HTLCs along the same path.
1643 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1644 // distance from the payee
1646 // We are not a faithful Dijkstra's implementation because we can change values which impact
1647 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1648 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1649 // the value we are currently attempting to send over a path, we simply reduce the value being
1650 // sent along the path for any hops after that channel. This may imply that later fees (which
1651 // we've already tabulated) are lower because a smaller value is passing through the channels
1652 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1653 // channels which were selected earlier (and which may still be used for other paths without a
1654 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1657 // One potentially problematic case for this algorithm would be if there are many
1658 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1659 // graph walking), we may never find a path which is not liquidity-limited and has lower
1660 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1661 // Because we only consider paths with at least 5% of the total value being sent, the damage
1662 // from such a case should be limited, however this could be further reduced in the future by
1663 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1664 // limits for the purposes of fee calculation.
1666 // Alternatively, we could store more detailed path information in the heap (targets, below)
1667 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1668 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1669 // and practically (as we would need to store dynamically-allocated path information in heap
1670 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1671 // results of such an algorithm would likely be biased towards lower-value paths.
1673 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1674 // outside of our current search value, running a path search more times to gather candidate
1675 // paths at different values. While this may be acceptable, further path searches may increase
1676 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1677 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1678 // the same time, remaining generic across different payment values.
1680 let network_channels = network_graph.channels();
1681 let network_nodes = network_graph.nodes();
1683 if payment_params.max_path_count == 0 {
1684 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1687 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1688 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1690 let allow_mpp = if payment_params.max_path_count == 1 {
1692 } else if payment_params.payee.supports_basic_mpp() {
1694 } else if let Some(payee) = payee_node_id_opt {
1695 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1696 |info| info.features.supports_basic_mpp()))
1699 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1701 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1702 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1703 if allow_mpp { "with" } else { "without" },
1704 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1705 max_total_routing_fee_msat);
1708 // Prepare the data we'll use for payee-to-payer search by
1709 // inserting first hops suggested by the caller as targets.
1710 // Our search will then attempt to reach them while traversing from the payee node.
1711 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1712 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1713 if let Some(hops) = first_hops {
1715 if chan.get_outbound_payment_scid().is_none() {
1716 panic!("first_hops should be filled in with usable channels, not pending ones");
1718 if chan.counterparty.node_id == *our_node_pubkey {
1719 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1722 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1723 .or_insert(Vec::new())
1726 if first_hop_targets.is_empty() {
1727 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1731 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1732 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1733 // adding duplicate entries when we find a better path to a given node.
1734 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1736 // Map from node_id to information about the best current path to that node, including feerate
1738 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1740 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1741 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1742 // htlc_minimum with extra fees while still finding a cheaper path.
1743 let mut hit_minimum_limit;
1745 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1746 // We start with a path_value of the exact amount we want, and if that generates a route we may
1747 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1748 // amount we want in total across paths, selecting the best subset at the end.
1749 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1750 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1751 let mut path_value_msat = final_value_msat;
1753 // Routing Fragmentation Mitigation heuristic:
1755 // Routing fragmentation across many payment paths increases the overall routing
1756 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1757 // Taking too many smaller paths also increases the chance of payment failure.
1758 // Thus to avoid this effect, we require from our collected links to provide
1759 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1760 // This requirement is currently set to be 1/max_path_count of the payment
1761 // value to ensure we only ever return routes that do not violate this limit.
1762 let minimal_value_contribution_msat: u64 = if allow_mpp {
1763 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1768 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1769 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1770 // drop the requirement by setting this to 0.
1771 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1773 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1774 // determine if the channel can be used by additional MPP paths or to inform path finding
1775 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1776 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1778 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1779 HashMap::with_capacity(network_nodes.len());
1781 // Keeping track of how much value we already collected across other paths. Helps to decide
1782 // when we want to stop looking for new paths.
1783 let mut already_collected_value_msat = 0;
1785 for (_, channels) in first_hop_targets.iter_mut() {
1786 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1790 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1791 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1793 // Remember how many candidates we ignored to allow for some logging afterwards.
1794 let mut num_ignored_value_contribution: u32 = 0;
1795 let mut num_ignored_path_length_limit: u32 = 0;
1796 let mut num_ignored_cltv_delta_limit: u32 = 0;
1797 let mut num_ignored_previously_failed: u32 = 0;
1798 let mut num_ignored_total_fee_limit: u32 = 0;
1799 let mut num_ignored_avoid_overpayment: u32 = 0;
1800 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
1802 macro_rules! add_entry {
1803 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
1804 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1805 // since that value has to be transferred over this channel.
1806 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
1807 ( $candidate: expr, $next_hops_fee_msat: expr,
1808 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1809 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1810 // We "return" whether we updated the path at the end, and how much we can route via
1811 // this channel, via this:
1812 let mut hop_contribution_amt_msat = None;
1813 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1814 // practice these cases should be caught earlier:
1815 // - for regular channels at channel announcement (TODO)
1816 // - for first and last hops early in get_route
1817 let src_node_id = $candidate.source();
1818 let dest_node_id = $candidate.target().unwrap_or(maybe_dummy_payee_node_id);
1819 if src_node_id != dest_node_id {
1820 let scid_opt = $candidate.short_channel_id();
1821 let effective_capacity = $candidate.effective_capacity();
1822 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1824 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1825 // It may be misleading because we might later choose to reduce the value transferred
1826 // over these channels, and the channel which was insufficient might become sufficient.
1827 // Worst case: we drop a good channel here because it can't cover the high following
1828 // fees caused by one expensive channel, but then this channel could have been used
1829 // if the amount being transferred over this path is lower.
1830 // We do this for now, but this is a subject for removal.
1831 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1832 let used_liquidity_msat = used_liquidities
1833 .get(&$candidate.id())
1834 .map_or(0, |used_liquidity_msat| {
1835 available_value_contribution_msat = available_value_contribution_msat
1836 .saturating_sub(*used_liquidity_msat);
1837 *used_liquidity_msat
1840 // Verify the liquidity offered by this channel complies to the minimal contribution.
1841 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1842 // Do not consider candidate hops that would exceed the maximum path length.
1843 let path_length_to_node = $next_hops_path_length + 1;
1844 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1846 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1847 // In order to already account for some of the privacy enhancing random CLTV
1848 // expiry delta offset we add on top later, we subtract a rough estimate
1849 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1850 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1851 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1852 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1853 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1854 .saturating_add($candidate.cltv_expiry_delta());
1855 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1857 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1858 // Includes paying fees for the use of the following channels.
1859 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1860 Some(result) => result,
1861 // Can't overflow due to how the values were computed right above.
1862 None => unreachable!(),
1864 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1865 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1866 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1868 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1869 let may_overpay_to_meet_path_minimum_msat =
1870 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1871 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
1872 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1873 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
1875 let payment_failed_on_this_channel = scid_opt.map_or(false,
1876 |scid| payment_params.previously_failed_channels.contains(&scid));
1878 let (should_log_candidate, first_hop_details) = match $candidate {
1879 CandidateRouteHop::FirstHop { details, .. } => (true, Some(details)),
1880 CandidateRouteHop::PrivateHop { .. } => (true, None),
1881 CandidateRouteHop::Blinded { .. } => (true, None),
1882 CandidateRouteHop::OneHopBlinded { .. } => (true, None),
1886 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1887 // bother considering this channel. If retrying with recommended_value_msat may
1888 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1889 // around again with a higher amount.
1890 if !contributes_sufficient_value {
1891 if should_log_candidate {
1892 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1894 if let Some(details) = first_hop_details {
1896 "First hop candidate next_outbound_htlc_limit_msat: {}",
1897 details.next_outbound_htlc_limit_msat,
1901 num_ignored_value_contribution += 1;
1902 } else if exceeds_max_path_length {
1903 if should_log_candidate {
1904 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1906 num_ignored_path_length_limit += 1;
1907 } else if exceeds_cltv_delta_limit {
1908 if should_log_candidate {
1909 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1911 if let Some(_) = first_hop_details {
1913 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
1914 hop_total_cltv_delta,
1915 max_total_cltv_expiry_delta,
1919 num_ignored_cltv_delta_limit += 1;
1920 } else if payment_failed_on_this_channel {
1921 if should_log_candidate {
1922 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1924 num_ignored_previously_failed += 1;
1925 } else if may_overpay_to_meet_path_minimum_msat {
1926 if should_log_candidate {
1928 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
1929 LoggedCandidateHop(&$candidate));
1931 if let Some(details) = first_hop_details {
1933 "First hop candidate next_outbound_htlc_minimum_msat: {}",
1934 details.next_outbound_htlc_minimum_msat,
1938 num_ignored_avoid_overpayment += 1;
1939 hit_minimum_limit = true;
1940 } else if over_path_minimum_msat {
1941 // Note that low contribution here (limited by available_liquidity_msat)
1942 // might violate htlc_minimum_msat on the hops which are next along the
1943 // payment path (upstream to the payee). To avoid that, we recompute
1944 // path fees knowing the final path contribution after constructing it.
1945 let curr_min = cmp::max(
1946 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
1948 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
1949 .saturating_add(curr_min);
1950 let hm_entry = dist.entry(src_node_id);
1951 let old_entry = hm_entry.or_insert_with(|| {
1952 // If there was previously no known way to access the source node
1953 // (recall it goes payee-to-payer) of short_channel_id, first add a
1954 // semi-dummy record just to compute the fees to reach the source node.
1955 // This will affect our decision on selecting short_channel_id
1956 // as a way to reach the $candidate.target() node.
1958 node_id: dest_node_id.clone(),
1959 candidate: $candidate.clone(),
1961 next_hops_fee_msat: u64::max_value(),
1962 hop_use_fee_msat: u64::max_value(),
1963 total_fee_msat: u64::max_value(),
1964 path_htlc_minimum_msat,
1965 path_penalty_msat: u64::max_value(),
1966 was_processed: false,
1967 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1968 value_contribution_msat,
1972 #[allow(unused_mut)] // We only use the mut in cfg(test)
1973 let mut should_process = !old_entry.was_processed;
1974 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1976 // In test/fuzzing builds, we do extra checks to make sure the skipping
1977 // of already-seen nodes only happens in cases we expect (see below).
1978 if !should_process { should_process = true; }
1982 let mut hop_use_fee_msat = 0;
1983 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1985 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1986 // will have the same effective-fee
1987 if src_node_id != our_node_id {
1988 // Note that `u64::max_value` means we'll always fail the
1989 // `old_entry.total_fee_msat > total_fee_msat` check below
1990 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1991 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1994 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
1995 if total_fee_msat > max_total_routing_fee_msat {
1996 if should_log_candidate {
1997 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
1999 if let Some(_) = first_hop_details {
2001 "First hop candidate routing fee: {}. Limit: {}",
2003 max_total_routing_fee_msat,
2007 num_ignored_total_fee_limit += 1;
2009 let channel_usage = ChannelUsage {
2010 amount_msat: amount_to_transfer_over_msat,
2011 inflight_htlc_msat: used_liquidity_msat,
2014 let channel_penalty_msat = scid_opt.map_or(0,
2015 |scid| scorer.channel_penalty_msat(scid, &src_node_id, &dest_node_id,
2016 channel_usage, score_params));
2017 let path_penalty_msat = $next_hops_path_penalty_msat
2018 .saturating_add(channel_penalty_msat);
2019 let new_graph_node = RouteGraphNode {
2020 node_id: src_node_id,
2021 lowest_fee_to_node: total_fee_msat,
2022 total_cltv_delta: hop_total_cltv_delta,
2023 value_contribution_msat,
2024 path_htlc_minimum_msat,
2026 path_length_to_node,
2029 // Update the way of reaching $candidate.source()
2030 // with the given short_channel_id (from $candidate.target()),
2031 // if this way is cheaper than the already known
2032 // (considering the cost to "reach" this channel from the route destination,
2033 // the cost of using this channel,
2034 // and the cost of routing to the source node of this channel).
2035 // Also, consider that htlc_minimum_msat_difference, because we might end up
2036 // paying it. Consider the following exploit:
2037 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2038 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2039 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2040 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2042 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2043 // but it may require additional tracking - we don't want to double-count
2044 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2045 // can't use something that may decrease on future hops.
2046 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2047 .saturating_add(old_entry.path_penalty_msat);
2048 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2049 .saturating_add(path_penalty_msat);
2051 if !old_entry.was_processed && new_cost < old_cost {
2052 targets.push(new_graph_node);
2053 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2054 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2055 old_entry.total_fee_msat = total_fee_msat;
2056 old_entry.node_id = dest_node_id;
2057 old_entry.candidate = $candidate.clone();
2058 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2059 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2060 old_entry.path_penalty_msat = path_penalty_msat;
2061 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2063 old_entry.value_contribution_msat = value_contribution_msat;
2065 hop_contribution_amt_msat = Some(value_contribution_msat);
2066 } else if old_entry.was_processed && new_cost < old_cost {
2067 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2069 // If we're skipping processing a node which was previously
2070 // processed even though we found another path to it with a
2071 // cheaper fee, check that it was because the second path we
2072 // found (which we are processing now) has a lower value
2073 // contribution due to an HTLC minimum limit.
2075 // e.g. take a graph with two paths from node 1 to node 2, one
2076 // through channel A, and one through channel B. Channel A and
2077 // B are both in the to-process heap, with their scores set by
2078 // a higher htlc_minimum than fee.
2079 // Channel A is processed first, and the channels onwards from
2080 // node 1 are added to the to-process heap. Thereafter, we pop
2081 // Channel B off of the heap, note that it has a much more
2082 // restrictive htlc_maximum_msat, and recalculate the fees for
2083 // all of node 1's channels using the new, reduced, amount.
2085 // This would be bogus - we'd be selecting a higher-fee path
2086 // with a lower htlc_maximum_msat instead of the one we'd
2087 // already decided to use.
2088 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2090 value_contribution_msat + path_penalty_msat <
2091 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2098 if should_log_candidate {
2100 "Ignoring {} due to its htlc_minimum_msat limit.",
2101 LoggedCandidateHop(&$candidate));
2103 if let Some(details) = first_hop_details {
2105 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2106 details.next_outbound_htlc_minimum_msat,
2110 num_ignored_htlc_minimum_msat_limit += 1;
2114 hop_contribution_amt_msat
2118 let default_node_features = default_node_features();
2120 // Find ways (channels with destination) to reach a given node and store them
2121 // in the corresponding data structures (routing graph etc).
2122 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2123 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2124 // This data can later be helpful to optimize routing (pay lower fees).
2125 macro_rules! add_entries_to_cheapest_to_target_node {
2126 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
2127 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
2128 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2129 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2130 let was_processed = elem.was_processed;
2131 elem.was_processed = true;
2134 // Entries are added to dist in add_entry!() when there is a channel from a node.
2135 // Because there are no channels from payee, it will not have a dist entry at this point.
2136 // If we're processing any other node, it is always be the result of a channel from it.
2137 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2142 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2143 for details in first_channels {
2144 let candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id };
2145 add_entry!(&candidate, $fee_to_target_msat,
2146 $next_hops_value_contribution,
2147 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
2148 $next_hops_cltv_delta, $next_hops_path_length);
2152 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2155 &default_node_features
2158 if !features.requires_unknown_bits() {
2159 for chan_id in $node.channels.iter() {
2160 let chan = network_channels.get(chan_id).unwrap();
2161 if !chan.features.requires_unknown_bits() {
2162 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2163 if first_hops.is_none() || *source != our_node_id {
2164 if directed_channel.direction().enabled {
2165 let candidate = CandidateRouteHop::PublicHop {
2166 info: directed_channel,
2167 short_channel_id: *chan_id,
2169 add_entry!(&candidate,
2170 $fee_to_target_msat,
2171 $next_hops_value_contribution,
2172 $next_hops_path_htlc_minimum_msat,
2173 $next_hops_path_penalty_msat,
2174 $next_hops_cltv_delta, $next_hops_path_length);
2185 let mut payment_paths = Vec::<PaymentPath>::new();
2187 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2188 'paths_collection: loop {
2189 // For every new path, start from scratch, except for used_liquidities, which
2190 // helps to avoid reusing previously selected paths in future iterations.
2193 hit_minimum_limit = false;
2195 // If first hop is a private channel and the only way to reach the payee, this is the only
2196 // place where it could be added.
2197 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2198 for details in first_channels {
2199 let candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id };
2200 let added = add_entry!(&candidate, 0, path_value_msat,
2201 0, 0u64, 0, 0).is_some();
2202 log_trace!(logger, "{} direct route to payee via {}",
2203 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2207 // Add the payee as a target, so that the payee-to-payer
2208 // search algorithm knows what to start with.
2209 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2210 // The payee is not in our network graph, so nothing to add here.
2211 // There is still a chance of reaching them via last_hops though,
2212 // so don't yet fail the payment here.
2213 // If not, targets.pop() will not even let us enter the loop in step 2.
2216 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2221 // If a caller provided us with last hops, add them to routing targets. Since this happens
2222 // earlier than general path finding, they will be somewhat prioritized, although currently
2223 // it matters only if the fees are exactly the same.
2224 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2225 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2226 let have_intro_node_in_graph =
2227 // Only add the hops in this route to our candidate set if either
2228 // we have a direct channel to the first hop or the first hop is
2229 // in the regular network graph.
2230 first_hop_targets.get(&intro_node_id).is_some() ||
2231 network_nodes.get(&intro_node_id).is_some();
2232 if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2233 let candidate = if hint.1.blinded_hops.len() == 1 {
2234 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2235 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2236 let mut path_contribution_msat = path_value_msat;
2237 if let Some(hop_used_msat) = add_entry!(&candidate,
2238 0, path_contribution_msat, 0, 0_u64, 0, 0)
2240 path_contribution_msat = hop_used_msat;
2242 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2243 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2245 for details in first_channels {
2246 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2247 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2251 let path_min = candidate.htlc_minimum_msat().saturating_add(
2252 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2253 add_entry!(&first_hop_candidate, blinded_path_fee,
2254 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2255 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2259 for route in payment_params.payee.unblinded_route_hints().iter()
2260 .filter(|route| !route.0.is_empty())
2262 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2263 let first_hop_src_is_reachable =
2264 // Only add the hops in this route to our candidate set if either we are part of
2265 // the first hop, we have a direct channel to the first hop, or the first hop is in
2266 // the regular network graph.
2267 our_node_id == first_hop_src_id ||
2268 first_hop_targets.get(&first_hop_src_id).is_some() ||
2269 network_nodes.get(&first_hop_src_id).is_some();
2270 if first_hop_src_is_reachable {
2271 // We start building the path from reverse, i.e., from payee
2272 // to the first RouteHintHop in the path.
2273 let hop_iter = route.0.iter().rev();
2274 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2275 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2276 let mut hop_used = true;
2277 let mut aggregate_next_hops_fee_msat: u64 = 0;
2278 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2279 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2280 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2281 let mut aggregate_next_hops_path_length: u8 = 0;
2282 let mut aggregate_path_contribution_msat = path_value_msat;
2284 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2285 let source = NodeId::from_pubkey(&hop.src_node_id);
2286 let target = NodeId::from_pubkey(&prev_hop_id);
2288 if let Some(first_channels) = first_hop_targets.get(&target) {
2289 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2290 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2291 hop.short_channel_id);
2296 let candidate = network_channels
2297 .get(&hop.short_channel_id)
2298 .and_then(|channel| channel.as_directed_to(&target))
2299 .map(|(info, _)| CandidateRouteHop::PublicHop {
2301 short_channel_id: hop.short_channel_id,
2303 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop, target_node_id: target });
2305 if let Some(hop_used_msat) = add_entry!(&candidate,
2306 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2307 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2308 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2310 aggregate_path_contribution_msat = hop_used_msat;
2312 // If this hop was not used then there is no use checking the preceding
2313 // hops in the RouteHint. We can break by just searching for a direct
2314 // channel between last checked hop and first_hop_targets.
2318 let used_liquidity_msat = used_liquidities
2319 .get(&candidate.id()).copied()
2321 let channel_usage = ChannelUsage {
2322 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2323 inflight_htlc_msat: used_liquidity_msat,
2324 effective_capacity: candidate.effective_capacity(),
2326 let channel_penalty_msat = scorer.channel_penalty_msat(
2327 hop.short_channel_id, &source, &target, channel_usage, score_params
2329 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2330 .saturating_add(channel_penalty_msat);
2332 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2333 .saturating_add(hop.cltv_expiry_delta as u32);
2335 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2338 // Searching for a direct channel between last checked hop and first_hop_targets
2339 if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2340 sort_first_hop_channels(first_channels, &used_liquidities,
2341 recommended_value_msat, our_node_pubkey);
2342 for details in first_channels {
2343 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2344 add_entry!(&first_hop_candidate,
2345 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2346 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2347 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2355 // In the next values of the iterator, the aggregate fees already reflects
2356 // the sum of value sent from payer (final_value_msat) and routing fees
2357 // for the last node in the RouteHint. We need to just add the fees to
2358 // route through the current node so that the preceding node (next iteration)
2360 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2361 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2362 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2364 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2365 // this route hint's source node to forward said min over this channel.
2366 aggregate_next_hops_path_htlc_minimum_msat = {
2367 let curr_htlc_min = cmp::max(
2368 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2370 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2371 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2374 if idx == route.0.len() - 1 {
2375 // The last hop in this iterator is the first hop in
2376 // overall RouteHint.
2377 // If this hop connects to a node with which we have a direct channel,
2378 // ignore the network graph and, if the last hop was added, add our
2379 // direct channel to the candidate set.
2381 // Note that we *must* check if the last hop was added as `add_entry`
2382 // always assumes that the third argument is a node to which we have a
2384 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2385 sort_first_hop_channels(first_channels, &used_liquidities,
2386 recommended_value_msat, our_node_pubkey);
2387 for details in first_channels {
2388 let first_hop_candidate = CandidateRouteHop::FirstHop { details, node_id: our_node_id};
2389 add_entry!(&first_hop_candidate,
2390 aggregate_next_hops_fee_msat,
2391 aggregate_path_contribution_msat,
2392 aggregate_next_hops_path_htlc_minimum_msat,
2393 aggregate_next_hops_path_penalty_msat,
2394 aggregate_next_hops_cltv_delta,
2395 aggregate_next_hops_path_length);
2403 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2405 // At this point, targets are filled with the data from first and
2406 // last hops communicated by the caller, and the payment receiver.
2407 let mut found_new_path = false;
2410 // If this loop terminates due the exhaustion of targets, two situations are possible:
2411 // - not enough outgoing liquidity:
2412 // 0 < already_collected_value_msat < final_value_msat
2413 // - enough outgoing liquidity:
2414 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2415 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2416 // paths_collection will be stopped because found_new_path==false.
2417 // This is not necessarily a routing failure.
2418 '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() {
2420 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2421 // traversing the graph and arrange the path out of what we found.
2422 if node_id == our_node_id {
2423 let mut new_entry = dist.remove(&our_node_id).unwrap();
2424 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2427 let mut features_set = false;
2428 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2429 for details in first_channels {
2430 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2431 if details.get_outbound_payment_scid().unwrap() == scid {
2432 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2433 features_set = true;
2440 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2441 if let Some(node_info) = node.announcement_info.as_ref() {
2442 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2444 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2447 // We can fill in features for everything except hops which were
2448 // provided via the invoice we're paying. We could guess based on the
2449 // recipient's features but for now we simply avoid guessing at all.
2453 // Means we succesfully traversed from the payer to the payee, now
2454 // save this path for the payment route. Also, update the liquidity
2455 // remaining on the used hops, so that we take them into account
2456 // while looking for more paths.
2457 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2461 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2462 Some(payment_hop) => payment_hop,
2463 // We can't arrive at None because, if we ever add an entry to targets,
2464 // we also fill in the entry in dist (see add_entry!).
2465 None => unreachable!(),
2467 // We "propagate" the fees one hop backward (topologically) here,
2468 // so that fees paid for a HTLC forwarding on the current channel are
2469 // associated with the previous channel (where they will be subtracted).
2470 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2471 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2473 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2474 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2476 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2477 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2479 let mut payment_path = PaymentPath {hops: ordered_hops};
2481 // We could have possibly constructed a slightly inconsistent path: since we reduce
2482 // value being transferred along the way, we could have violated htlc_minimum_msat
2483 // on some channels we already passed (assuming dest->source direction). Here, we
2484 // recompute the fees again, so that if that's the case, we match the currently
2485 // underpaid htlc_minimum_msat with fees.
2486 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2487 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2488 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2490 // Since a path allows to transfer as much value as
2491 // the smallest channel it has ("bottleneck"), we should recompute
2492 // the fees so sender HTLC don't overpay fees when traversing
2493 // larger channels than the bottleneck. This may happen because
2494 // when we were selecting those channels we were not aware how much value
2495 // this path will transfer, and the relative fee for them
2496 // might have been computed considering a larger value.
2497 // Remember that we used these channels so that we don't rely
2498 // on the same liquidity in future paths.
2499 let mut prevented_redundant_path_selection = false;
2500 for (hop, _) in payment_path.hops.iter() {
2501 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2502 let used_liquidity_msat = used_liquidities
2503 .entry(hop.candidate.id())
2504 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2505 .or_insert(spent_on_hop_msat);
2506 let hop_capacity = hop.candidate.effective_capacity();
2507 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2508 if *used_liquidity_msat == hop_max_msat {
2509 // If this path used all of this channel's available liquidity, we know
2510 // this path will not be selected again in the next loop iteration.
2511 prevented_redundant_path_selection = true;
2513 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2515 if !prevented_redundant_path_selection {
2516 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2517 // we'll probably end up picking the same path again on the next iteration.
2518 // Decrease the available liquidity of a hop in the middle of the path.
2519 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2520 let exhausted = u64::max_value();
2522 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2523 LoggedCandidateHop(victim_candidate));
2524 if let Some(scid) = victim_candidate.short_channel_id() {
2525 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2526 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2530 // Track the total amount all our collected paths allow to send so that we know
2531 // when to stop looking for more paths
2532 already_collected_value_msat += value_contribution_msat;
2534 payment_paths.push(payment_path);
2535 found_new_path = true;
2536 break 'path_construction;
2539 // If we found a path back to the payee, we shouldn't try to process it again. This is
2540 // the equivalent of the `elem.was_processed` check in
2541 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2542 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2544 // Otherwise, since the current target node is not us,
2545 // keep "unrolling" the payment graph from payee to payer by
2546 // finding a way to reach the current target from the payer side.
2547 match network_nodes.get(&node_id) {
2550 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2551 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2552 total_cltv_delta, path_length_to_node);
2558 if !found_new_path && channel_saturation_pow_half != 0 {
2559 channel_saturation_pow_half = 0;
2560 continue 'paths_collection;
2562 // If we don't support MPP, no use trying to gather more value ever.
2563 break 'paths_collection;
2567 // Stop either when the recommended value is reached or if no new path was found in this
2569 // In the latter case, making another path finding attempt won't help,
2570 // because we deterministically terminated the search due to low liquidity.
2571 if !found_new_path && channel_saturation_pow_half != 0 {
2572 channel_saturation_pow_half = 0;
2573 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2574 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2575 path_value_msat = recommended_value_msat;
2576 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2577 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2578 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2579 break 'paths_collection;
2580 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2581 // Further, if this was our first walk of the graph, and we weren't limited by an
2582 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2583 // limited by an htlc_minimum_msat value, find another path with a higher value,
2584 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2585 // still keeping a lower total fee than this path.
2586 if !hit_minimum_limit {
2587 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2588 break 'paths_collection;
2590 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.");
2591 path_value_msat = recommended_value_msat;
2595 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2596 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2597 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2598 num_ignored_total_fee_limit;
2599 if num_ignored_total > 0 {
2601 "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.",
2602 num_ignored_value_contribution, num_ignored_path_length_limit,
2603 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2604 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2605 num_ignored_total_fee_limit, num_ignored_total);
2609 if payment_paths.len() == 0 {
2610 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2613 if already_collected_value_msat < final_value_msat {
2614 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2618 let mut selected_route = payment_paths;
2620 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2621 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2623 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2624 // the value they contribute towards the payment amount.
2625 // We sort in descending order as we will remove from the front in `retain`, next.
2626 selected_route.sort_unstable_by(|a, b|
2627 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2628 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2631 // We should make sure that at least 1 path left.
2632 let mut paths_left = selected_route.len();
2633 selected_route.retain(|path| {
2634 if paths_left == 1 {
2637 let path_value_msat = path.get_value_msat();
2638 if path_value_msat <= overpaid_value_msat {
2639 overpaid_value_msat -= path_value_msat;
2645 debug_assert!(selected_route.len() > 0);
2647 if overpaid_value_msat != 0 {
2649 // Now, subtract the remaining overpaid value from the most-expensive path.
2650 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2651 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2652 selected_route.sort_unstable_by(|a, b| {
2653 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2654 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2655 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2657 let expensive_payment_path = selected_route.first_mut().unwrap();
2659 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2660 // can't go negative.
2661 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2662 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2666 // Sort by the path itself and combine redundant paths.
2667 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2668 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2670 selected_route.sort_unstable_by_key(|path| {
2671 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2672 debug_assert!(path.hops.len() <= key.len());
2673 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2678 for idx in 0..(selected_route.len() - 1) {
2679 if idx + 1 >= selected_route.len() { break; }
2680 if iter_equal(selected_route[idx].hops.iter().map(|h| (h.0.candidate.id(), h.0.node_id)),
2681 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.node_id))) {
2682 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2683 selected_route[idx].update_value_and_recompute_fees(new_value);
2684 selected_route.remove(idx + 1);
2688 let mut paths = Vec::new();
2689 for payment_path in selected_route {
2690 let mut hops = Vec::with_capacity(payment_path.hops.len());
2691 for (hop, node_features) in payment_path.hops.iter()
2692 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2694 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2695 // If we sourced the hop from the graph we're sure the target node is announced.
2697 } else if let CandidateRouteHop::FirstHop { details, .. } = hop.candidate {
2698 // If this is a first hop we also know if it's announced.
2701 // If we sourced it any other way, we double-check the network graph to see if
2702 // there are announced channels between the endpoints. If so, the hop might be
2703 // referring to any of the announced channels, as its `short_channel_id` might be
2704 // an alias, in which case we don't take any chances here.
2705 network_graph.node(&hop.node_id).map_or(false, |hop_node|
2706 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2707 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
2711 hops.push(RouteHop {
2712 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)})?,
2713 node_features: node_features.clone(),
2714 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2715 channel_features: hop.candidate.features(),
2716 fee_msat: hop.fee_msat,
2717 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2718 maybe_announced_channel,
2721 let mut final_cltv_delta = final_cltv_expiry_delta;
2722 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2723 if let Some(blinded_path) = h.candidate.blinded_path() {
2724 final_cltv_delta = h.candidate.cltv_expiry_delta();
2726 hops: blinded_path.blinded_hops.clone(),
2727 blinding_point: blinded_path.blinding_point,
2728 excess_final_cltv_expiry_delta: 0,
2729 final_value_msat: h.fee_msat,
2733 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2734 // applicable for the previous hop.
2735 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2736 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2739 paths.push(Path { hops, blinded_tail });
2741 // Make sure we would never create a route with more paths than we allow.
2742 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2744 if let Some(node_features) = payment_params.payee.node_features() {
2745 for path in paths.iter_mut() {
2746 path.hops.last_mut().unwrap().node_features = node_features.clone();
2750 let route = Route { paths, route_params: Some(route_params.clone()) };
2752 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2753 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2754 if route.get_total_fees() > max_total_routing_fee_msat {
2755 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2756 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2760 log_info!(logger, "Got route: {}", log_route!(route));
2764 // When an adversarial intermediary node observes a payment, it may be able to infer its
2765 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2766 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2767 // payment path by adding a randomized 'shadow route' offset to the final hop.
2768 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2769 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2771 let network_channels = network_graph.channels();
2772 let network_nodes = network_graph.nodes();
2774 for path in route.paths.iter_mut() {
2775 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2777 // Remember the last three nodes of the random walk and avoid looping back on them.
2778 // Init with the last three nodes from the actual path, if possible.
2779 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2780 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2781 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2783 // Choose the last publicly known node as the starting point for the random walk.
2784 let mut cur_hop: Option<NodeId> = None;
2785 let mut path_nonce = [0u8; 12];
2786 if let Some(starting_hop) = path.hops.iter().rev()
2787 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2788 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2789 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2792 // Init PRNG with the path-dependant nonce, which is static for private paths.
2793 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2794 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2796 // Pick a random path length in [1 .. 3]
2797 prng.process_in_place(&mut random_path_bytes);
2798 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2800 for random_hop in 0..random_walk_length {
2801 // If we don't find a suitable offset in the public network graph, we default to
2802 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2803 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2805 if let Some(cur_node_id) = cur_hop {
2806 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2807 // Randomly choose the next unvisited hop.
2808 prng.process_in_place(&mut random_path_bytes);
2809 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2810 .checked_rem(cur_node.channels.len())
2811 .and_then(|index| cur_node.channels.get(index))
2812 .and_then(|id| network_channels.get(id)) {
2813 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2814 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2815 nodes_to_avoid[random_hop] = *next_id;
2816 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2817 cur_hop = Some(*next_id);
2824 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2825 .checked_add(random_hop_offset)
2826 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2829 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2830 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2831 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2833 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2834 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2835 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2836 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2837 max_path_offset = cmp::max(
2838 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2839 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2840 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2842 // Add 'shadow' CLTV offset to the final hop
2843 if let Some(tail) = path.blinded_tail.as_mut() {
2844 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2845 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2847 if let Some(last_hop) = path.hops.last_mut() {
2848 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2849 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2854 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2855 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2857 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2858 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2859 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2860 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2861 ) -> Result<Route, LightningError>
2862 where L::Target: Logger, GL::Target: Logger {
2863 let graph_lock = network_graph.read_only();
2864 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2865 &graph_lock, logger, random_seed_bytes)?;
2866 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2870 fn build_route_from_hops_internal<L: Deref>(
2871 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2872 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2873 ) -> Result<Route, LightningError> where L::Target: Logger {
2876 our_node_id: NodeId,
2877 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2880 impl ScoreLookUp for HopScorer {
2881 type ScoreParams = ();
2882 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2883 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2885 let mut cur_id = self.our_node_id;
2886 for i in 0..self.hop_ids.len() {
2887 if let Some(next_id) = self.hop_ids[i] {
2888 if cur_id == *source && next_id == *target {
2900 impl<'a> Writeable for HopScorer {
2902 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2907 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2908 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2911 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2912 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2913 for i in 0..hops.len() {
2914 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2917 let scorer = HopScorer { our_node_id, hop_ids };
2919 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2924 use crate::blinded_path::{BlindedHop, BlindedPath};
2925 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2926 use crate::routing::utxo::UtxoResult;
2927 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2928 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2929 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2930 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2931 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2932 use crate::chain::transaction::OutPoint;
2933 use crate::sign::EntropySource;
2934 use crate::ln::ChannelId;
2935 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2936 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2937 use crate::ln::channelmanager;
2938 use crate::offers::invoice::BlindedPayInfo;
2939 use crate::util::config::UserConfig;
2940 use crate::util::test_utils as ln_test_utils;
2941 use crate::util::chacha20::ChaCha20;
2942 use crate::util::ser::{Readable, Writeable};
2944 use crate::util::ser::Writer;
2946 use bitcoin::hashes::Hash;
2947 use bitcoin::network::constants::Network;
2948 use bitcoin::blockdata::constants::ChainHash;
2949 use bitcoin::blockdata::script::Builder;
2950 use bitcoin::blockdata::opcodes;
2951 use bitcoin::blockdata::transaction::TxOut;
2952 use bitcoin::hashes::hex::FromHex;
2953 use bitcoin::secp256k1::{PublicKey,SecretKey};
2954 use bitcoin::secp256k1::Secp256k1;
2956 use crate::io::Cursor;
2957 use crate::prelude::*;
2958 use crate::sync::Arc;
2960 use core::convert::TryInto;
2962 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2963 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2964 channelmanager::ChannelDetails {
2965 channel_id: ChannelId::new_zero(),
2966 counterparty: channelmanager::ChannelCounterparty {
2969 unspendable_punishment_reserve: 0,
2970 forwarding_info: None,
2971 outbound_htlc_minimum_msat: None,
2972 outbound_htlc_maximum_msat: None,
2974 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2977 outbound_scid_alias: None,
2978 inbound_scid_alias: None,
2979 channel_value_satoshis: 0,
2982 outbound_capacity_msat,
2983 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2984 next_outbound_htlc_minimum_msat: 0,
2985 inbound_capacity_msat: 42,
2986 unspendable_punishment_reserve: None,
2987 confirmations_required: None,
2988 confirmations: None,
2989 force_close_spend_delay: None,
2990 is_outbound: true, is_channel_ready: true,
2991 is_usable: true, is_public: true,
2992 inbound_htlc_minimum_msat: None,
2993 inbound_htlc_maximum_msat: None,
2995 feerate_sat_per_1000_weight: None,
2996 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3001 fn simple_route_test() {
3002 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3003 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3004 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3005 let scorer = ln_test_utils::TestScorer::new();
3006 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3007 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3009 // Simple route to 2 via 1
3011 let route_params = RouteParameters::from_payment_params_and_value(
3012 payment_params.clone(), 0);
3013 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3014 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3015 &Default::default(), &random_seed_bytes) {
3016 assert_eq!(err, "Cannot send a payment of 0 msat");
3017 } else { panic!(); }
3019 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3020 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3021 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3022 assert_eq!(route.paths[0].hops.len(), 2);
3024 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3025 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3026 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3027 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3028 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3029 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3031 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3032 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3033 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3034 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3035 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3036 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3040 fn invalid_first_hop_test() {
3041 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3042 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3043 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3044 let scorer = ln_test_utils::TestScorer::new();
3045 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3046 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3048 // Simple route to 2 via 1
3050 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3052 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3053 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3054 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3055 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3056 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3057 } else { panic!(); }
3059 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3060 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3061 assert_eq!(route.paths[0].hops.len(), 2);
3065 fn htlc_minimum_test() {
3066 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3067 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3068 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3069 let scorer = ln_test_utils::TestScorer::new();
3070 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3071 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3073 // Simple route to 2 via 1
3075 // Disable other paths
3076 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3077 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3078 short_channel_id: 12,
3080 flags: 2, // to disable
3081 cltv_expiry_delta: 0,
3082 htlc_minimum_msat: 0,
3083 htlc_maximum_msat: MAX_VALUE_MSAT,
3085 fee_proportional_millionths: 0,
3086 excess_data: Vec::new()
3088 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3089 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3090 short_channel_id: 3,
3092 flags: 2, // to disable
3093 cltv_expiry_delta: 0,
3094 htlc_minimum_msat: 0,
3095 htlc_maximum_msat: MAX_VALUE_MSAT,
3097 fee_proportional_millionths: 0,
3098 excess_data: Vec::new()
3100 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3101 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3102 short_channel_id: 13,
3104 flags: 2, // to disable
3105 cltv_expiry_delta: 0,
3106 htlc_minimum_msat: 0,
3107 htlc_maximum_msat: MAX_VALUE_MSAT,
3109 fee_proportional_millionths: 0,
3110 excess_data: Vec::new()
3112 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3113 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3114 short_channel_id: 6,
3116 flags: 2, // to disable
3117 cltv_expiry_delta: 0,
3118 htlc_minimum_msat: 0,
3119 htlc_maximum_msat: MAX_VALUE_MSAT,
3121 fee_proportional_millionths: 0,
3122 excess_data: Vec::new()
3124 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3125 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3126 short_channel_id: 7,
3128 flags: 2, // to disable
3129 cltv_expiry_delta: 0,
3130 htlc_minimum_msat: 0,
3131 htlc_maximum_msat: MAX_VALUE_MSAT,
3133 fee_proportional_millionths: 0,
3134 excess_data: Vec::new()
3137 // Check against amount_to_transfer_over_msat.
3138 // Set minimal HTLC of 200_000_000 msat.
3139 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3140 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3141 short_channel_id: 2,
3144 cltv_expiry_delta: 0,
3145 htlc_minimum_msat: 200_000_000,
3146 htlc_maximum_msat: MAX_VALUE_MSAT,
3148 fee_proportional_millionths: 0,
3149 excess_data: Vec::new()
3152 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3154 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3155 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3156 short_channel_id: 4,
3159 cltv_expiry_delta: 0,
3160 htlc_minimum_msat: 0,
3161 htlc_maximum_msat: 199_999_999,
3163 fee_proportional_millionths: 0,
3164 excess_data: Vec::new()
3167 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3168 let route_params = RouteParameters::from_payment_params_and_value(
3169 payment_params, 199_999_999);
3170 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3171 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3172 &Default::default(), &random_seed_bytes) {
3173 assert_eq!(err, "Failed to find a path to the given destination");
3174 } else { panic!(); }
3176 // Lift the restriction on the first hop.
3177 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3178 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3179 short_channel_id: 2,
3182 cltv_expiry_delta: 0,
3183 htlc_minimum_msat: 0,
3184 htlc_maximum_msat: MAX_VALUE_MSAT,
3186 fee_proportional_millionths: 0,
3187 excess_data: Vec::new()
3190 // A payment above the minimum should pass
3191 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3192 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3193 assert_eq!(route.paths[0].hops.len(), 2);
3197 fn htlc_minimum_overpay_test() {
3198 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3199 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3200 let config = UserConfig::default();
3201 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3202 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3204 let scorer = ln_test_utils::TestScorer::new();
3205 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3206 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3208 // A route to node#2 via two paths.
3209 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3210 // Thus, they can't send 60 without overpaying.
3211 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3212 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3213 short_channel_id: 2,
3216 cltv_expiry_delta: 0,
3217 htlc_minimum_msat: 35_000,
3218 htlc_maximum_msat: 40_000,
3220 fee_proportional_millionths: 0,
3221 excess_data: Vec::new()
3223 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3224 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3225 short_channel_id: 12,
3228 cltv_expiry_delta: 0,
3229 htlc_minimum_msat: 35_000,
3230 htlc_maximum_msat: 40_000,
3232 fee_proportional_millionths: 0,
3233 excess_data: Vec::new()
3237 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3238 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3239 short_channel_id: 13,
3242 cltv_expiry_delta: 0,
3243 htlc_minimum_msat: 0,
3244 htlc_maximum_msat: MAX_VALUE_MSAT,
3246 fee_proportional_millionths: 0,
3247 excess_data: Vec::new()
3249 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3250 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3251 short_channel_id: 4,
3254 cltv_expiry_delta: 0,
3255 htlc_minimum_msat: 0,
3256 htlc_maximum_msat: MAX_VALUE_MSAT,
3258 fee_proportional_millionths: 0,
3259 excess_data: Vec::new()
3262 // Disable other paths
3263 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3264 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3265 short_channel_id: 1,
3267 flags: 2, // to disable
3268 cltv_expiry_delta: 0,
3269 htlc_minimum_msat: 0,
3270 htlc_maximum_msat: MAX_VALUE_MSAT,
3272 fee_proportional_millionths: 0,
3273 excess_data: Vec::new()
3276 let mut route_params = RouteParameters::from_payment_params_and_value(
3277 payment_params.clone(), 60_000);
3278 route_params.max_total_routing_fee_msat = Some(15_000);
3279 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3280 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3281 // Overpay fees to hit htlc_minimum_msat.
3282 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3283 // TODO: this could be better balanced to overpay 10k and not 15k.
3284 assert_eq!(overpaid_fees, 15_000);
3286 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3287 // while taking even more fee to match htlc_minimum_msat.
3288 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3289 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3290 short_channel_id: 12,
3293 cltv_expiry_delta: 0,
3294 htlc_minimum_msat: 65_000,
3295 htlc_maximum_msat: 80_000,
3297 fee_proportional_millionths: 0,
3298 excess_data: Vec::new()
3300 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3301 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3302 short_channel_id: 2,
3305 cltv_expiry_delta: 0,
3306 htlc_minimum_msat: 0,
3307 htlc_maximum_msat: MAX_VALUE_MSAT,
3309 fee_proportional_millionths: 0,
3310 excess_data: Vec::new()
3312 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3313 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3314 short_channel_id: 4,
3317 cltv_expiry_delta: 0,
3318 htlc_minimum_msat: 0,
3319 htlc_maximum_msat: MAX_VALUE_MSAT,
3321 fee_proportional_millionths: 100_000,
3322 excess_data: Vec::new()
3325 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3326 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3327 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3328 assert_eq!(route.paths.len(), 1);
3329 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3330 let fees = route.paths[0].hops[0].fee_msat;
3331 assert_eq!(fees, 5_000);
3333 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3334 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3335 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3336 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3337 // the other channel.
3338 assert_eq!(route.paths.len(), 1);
3339 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3340 let fees = route.paths[0].hops[0].fee_msat;
3341 assert_eq!(fees, 5_000);
3345 fn htlc_minimum_recipient_overpay_test() {
3346 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3347 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3348 let config = UserConfig::default();
3349 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3350 let scorer = ln_test_utils::TestScorer::new();
3351 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3352 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3354 // Route to node2 over a single path which requires overpaying the recipient themselves.
3356 // First disable all paths except the us -> node1 -> node2 path
3357 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3358 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3359 short_channel_id: 13,
3362 cltv_expiry_delta: 0,
3363 htlc_minimum_msat: 0,
3364 htlc_maximum_msat: 0,
3366 fee_proportional_millionths: 0,
3367 excess_data: Vec::new()
3370 // Set channel 4 to free but with a high htlc_minimum_msat
3371 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3372 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3373 short_channel_id: 4,
3376 cltv_expiry_delta: 0,
3377 htlc_minimum_msat: 15_000,
3378 htlc_maximum_msat: MAX_VALUE_MSAT,
3380 fee_proportional_millionths: 0,
3381 excess_data: Vec::new()
3384 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3385 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3386 // what we try to find a route for, so this test only just happens to work out to exactly
3388 let mut route_params = RouteParameters::from_payment_params_and_value(
3389 payment_params.clone(), 5_000);
3390 route_params.max_total_routing_fee_msat = Some(9_999);
3391 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3392 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3393 &Default::default(), &random_seed_bytes) {
3394 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3395 } else { panic!(); }
3397 let mut route_params = RouteParameters::from_payment_params_and_value(
3398 payment_params.clone(), 5_000);
3399 route_params.max_total_routing_fee_msat = Some(10_000);
3400 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3401 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3402 assert_eq!(route.get_total_fees(), 10_000);
3406 fn disable_channels_test() {
3407 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3408 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3409 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3410 let scorer = ln_test_utils::TestScorer::new();
3411 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3412 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3414 // // Disable channels 4 and 12 by flags=2
3415 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3416 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3417 short_channel_id: 4,
3419 flags: 2, // to disable
3420 cltv_expiry_delta: 0,
3421 htlc_minimum_msat: 0,
3422 htlc_maximum_msat: MAX_VALUE_MSAT,
3424 fee_proportional_millionths: 0,
3425 excess_data: Vec::new()
3427 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3428 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3429 short_channel_id: 12,
3431 flags: 2, // to disable
3432 cltv_expiry_delta: 0,
3433 htlc_minimum_msat: 0,
3434 htlc_maximum_msat: MAX_VALUE_MSAT,
3436 fee_proportional_millionths: 0,
3437 excess_data: Vec::new()
3440 // If all the channels require some features we don't understand, route should fail
3441 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3442 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3443 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3444 &Default::default(), &random_seed_bytes) {
3445 assert_eq!(err, "Failed to find a path to the given destination");
3446 } else { panic!(); }
3448 // If we specify a channel to node7, that overrides our local channel view and that gets used
3449 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3450 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3451 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3452 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3453 &Default::default(), &random_seed_bytes).unwrap();
3454 assert_eq!(route.paths[0].hops.len(), 2);
3456 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3457 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3458 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3459 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3460 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3461 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3463 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3464 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3465 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3466 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3467 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3468 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3472 fn disable_node_test() {
3473 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3474 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3475 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3476 let scorer = ln_test_utils::TestScorer::new();
3477 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3478 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3480 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3481 let mut unknown_features = NodeFeatures::empty();
3482 unknown_features.set_unknown_feature_required();
3483 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3484 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3485 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3487 // If all nodes require some features we don't understand, route should fail
3488 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3489 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3490 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3491 &Default::default(), &random_seed_bytes) {
3492 assert_eq!(err, "Failed to find a path to the given destination");
3493 } else { panic!(); }
3495 // If we specify a channel to node7, that overrides our local channel view and that gets used
3496 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3497 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3498 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3499 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3500 &Default::default(), &random_seed_bytes).unwrap();
3501 assert_eq!(route.paths[0].hops.len(), 2);
3503 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3504 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3505 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3506 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3507 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3508 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3510 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3511 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3512 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3513 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3514 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3515 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3517 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3518 // naively) assume that the user checked the feature bits on the invoice, which override
3519 // the node_announcement.
3523 fn our_chans_test() {
3524 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3525 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3526 let scorer = ln_test_utils::TestScorer::new();
3527 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3528 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3530 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3531 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3532 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3533 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3534 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3535 assert_eq!(route.paths[0].hops.len(), 3);
3537 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3538 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3539 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3540 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3541 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3542 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3544 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3545 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3546 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3547 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3548 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3549 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3551 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3552 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3553 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3554 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3555 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3556 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3558 // If we specify a channel to node7, that overrides our local channel view and that gets used
3559 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3560 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3561 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3562 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3563 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3564 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3565 &Default::default(), &random_seed_bytes).unwrap();
3566 assert_eq!(route.paths[0].hops.len(), 2);
3568 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3569 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3570 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3571 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3572 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3573 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3575 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3576 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3577 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3578 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3579 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3580 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3583 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3584 let zero_fees = RoutingFees {
3586 proportional_millionths: 0,
3588 vec![RouteHint(vec![RouteHintHop {
3589 src_node_id: nodes[3],
3590 short_channel_id: 8,
3592 cltv_expiry_delta: (8 << 4) | 1,
3593 htlc_minimum_msat: None,
3594 htlc_maximum_msat: None,
3596 ]), RouteHint(vec![RouteHintHop {
3597 src_node_id: nodes[4],
3598 short_channel_id: 9,
3601 proportional_millionths: 0,
3603 cltv_expiry_delta: (9 << 4) | 1,
3604 htlc_minimum_msat: None,
3605 htlc_maximum_msat: None,
3606 }]), RouteHint(vec![RouteHintHop {
3607 src_node_id: nodes[5],
3608 short_channel_id: 10,
3610 cltv_expiry_delta: (10 << 4) | 1,
3611 htlc_minimum_msat: None,
3612 htlc_maximum_msat: None,
3616 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3617 let zero_fees = RoutingFees {
3619 proportional_millionths: 0,
3621 vec![RouteHint(vec![RouteHintHop {
3622 src_node_id: nodes[2],
3623 short_channel_id: 5,
3626 proportional_millionths: 0,
3628 cltv_expiry_delta: (5 << 4) | 1,
3629 htlc_minimum_msat: None,
3630 htlc_maximum_msat: None,
3632 src_node_id: nodes[3],
3633 short_channel_id: 8,
3635 cltv_expiry_delta: (8 << 4) | 1,
3636 htlc_minimum_msat: None,
3637 htlc_maximum_msat: None,
3639 ]), RouteHint(vec![RouteHintHop {
3640 src_node_id: nodes[4],
3641 short_channel_id: 9,
3644 proportional_millionths: 0,
3646 cltv_expiry_delta: (9 << 4) | 1,
3647 htlc_minimum_msat: None,
3648 htlc_maximum_msat: None,
3649 }]), RouteHint(vec![RouteHintHop {
3650 src_node_id: nodes[5],
3651 short_channel_id: 10,
3653 cltv_expiry_delta: (10 << 4) | 1,
3654 htlc_minimum_msat: None,
3655 htlc_maximum_msat: None,
3660 fn partial_route_hint_test() {
3661 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3662 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3663 let scorer = ln_test_utils::TestScorer::new();
3664 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3665 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3667 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3668 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3669 // RouteHint may be partially used by the algo to build the best path.
3671 // First check that last hop can't have its source as the payee.
3672 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3673 src_node_id: nodes[6],
3674 short_channel_id: 8,
3677 proportional_millionths: 0,
3679 cltv_expiry_delta: (8 << 4) | 1,
3680 htlc_minimum_msat: None,
3681 htlc_maximum_msat: None,
3684 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3685 invalid_last_hops.push(invalid_last_hop);
3687 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3688 .with_route_hints(invalid_last_hops).unwrap();
3689 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3690 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3691 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3692 &Default::default(), &random_seed_bytes) {
3693 assert_eq!(err, "Route hint cannot have the payee as the source.");
3694 } else { panic!(); }
3697 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3698 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3699 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3700 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3701 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3702 assert_eq!(route.paths[0].hops.len(), 5);
3704 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3705 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3706 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3707 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3708 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3709 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3711 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3712 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3713 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3714 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3715 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3716 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3718 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3719 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3720 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3721 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3722 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3723 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3725 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3726 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3727 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3728 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3729 // If we have a peer in the node map, we'll use their features here since we don't have
3730 // a way of figuring out their features from the invoice:
3731 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3732 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3734 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3735 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3736 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3737 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3738 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3739 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3742 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3743 let zero_fees = RoutingFees {
3745 proportional_millionths: 0,
3747 vec![RouteHint(vec![RouteHintHop {
3748 src_node_id: nodes[3],
3749 short_channel_id: 8,
3751 cltv_expiry_delta: (8 << 4) | 1,
3752 htlc_minimum_msat: None,
3753 htlc_maximum_msat: None,
3754 }]), RouteHint(vec![
3756 ]), RouteHint(vec![RouteHintHop {
3757 src_node_id: nodes[5],
3758 short_channel_id: 10,
3760 cltv_expiry_delta: (10 << 4) | 1,
3761 htlc_minimum_msat: None,
3762 htlc_maximum_msat: None,
3767 fn ignores_empty_last_hops_test() {
3768 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3769 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3770 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3771 let scorer = ln_test_utils::TestScorer::new();
3772 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3773 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3775 // Test handling of an empty RouteHint passed in Invoice.
3776 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3777 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3778 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3779 assert_eq!(route.paths[0].hops.len(), 5);
3781 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3782 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3783 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3784 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3785 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3786 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3788 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3789 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3790 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3791 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3792 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3793 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3795 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3796 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3797 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3798 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3799 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3800 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3802 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3803 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3804 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3805 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3806 // If we have a peer in the node map, we'll use their features here since we don't have
3807 // a way of figuring out their features from the invoice:
3808 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3809 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3811 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3812 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3813 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3814 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3815 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3816 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3819 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3821 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3822 let zero_fees = RoutingFees {
3824 proportional_millionths: 0,
3826 vec![RouteHint(vec![RouteHintHop {
3827 src_node_id: hint_hops[0],
3828 short_channel_id: 0xff00,
3831 proportional_millionths: 0,
3833 cltv_expiry_delta: (5 << 4) | 1,
3834 htlc_minimum_msat: None,
3835 htlc_maximum_msat: None,
3837 src_node_id: hint_hops[1],
3838 short_channel_id: 0xff01,
3840 cltv_expiry_delta: (8 << 4) | 1,
3841 htlc_minimum_msat: None,
3842 htlc_maximum_msat: None,
3847 fn multi_hint_last_hops_test() {
3848 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3849 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3850 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3851 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3852 let scorer = ln_test_utils::TestScorer::new();
3853 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3854 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3855 // Test through channels 2, 3, 0xff00, 0xff01.
3856 // Test shows that multiple hop hints are considered.
3858 // Disabling channels 6 & 7 by flags=2
3859 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3860 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3861 short_channel_id: 6,
3863 flags: 2, // to disable
3864 cltv_expiry_delta: 0,
3865 htlc_minimum_msat: 0,
3866 htlc_maximum_msat: MAX_VALUE_MSAT,
3868 fee_proportional_millionths: 0,
3869 excess_data: Vec::new()
3871 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3872 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3873 short_channel_id: 7,
3875 flags: 2, // to disable
3876 cltv_expiry_delta: 0,
3877 htlc_minimum_msat: 0,
3878 htlc_maximum_msat: MAX_VALUE_MSAT,
3880 fee_proportional_millionths: 0,
3881 excess_data: Vec::new()
3884 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3885 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3886 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3887 assert_eq!(route.paths[0].hops.len(), 4);
3889 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3890 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3891 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3892 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3893 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3894 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3896 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3897 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3898 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3899 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3900 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3901 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3903 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3904 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3905 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3906 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3907 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3908 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3910 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3911 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3912 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3913 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3914 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3915 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3919 fn private_multi_hint_last_hops_test() {
3920 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3921 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3923 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3924 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3926 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3927 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3928 let scorer = ln_test_utils::TestScorer::new();
3929 // Test through channels 2, 3, 0xff00, 0xff01.
3930 // Test shows that multiple hop hints are considered.
3932 // Disabling channels 6 & 7 by flags=2
3933 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3934 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3935 short_channel_id: 6,
3937 flags: 2, // to disable
3938 cltv_expiry_delta: 0,
3939 htlc_minimum_msat: 0,
3940 htlc_maximum_msat: MAX_VALUE_MSAT,
3942 fee_proportional_millionths: 0,
3943 excess_data: Vec::new()
3945 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3946 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3947 short_channel_id: 7,
3949 flags: 2, // to disable
3950 cltv_expiry_delta: 0,
3951 htlc_minimum_msat: 0,
3952 htlc_maximum_msat: MAX_VALUE_MSAT,
3954 fee_proportional_millionths: 0,
3955 excess_data: Vec::new()
3958 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3959 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3960 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
3961 assert_eq!(route.paths[0].hops.len(), 4);
3963 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3964 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3965 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3966 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3967 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3968 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3970 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3971 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3972 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3973 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3974 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3975 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3977 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3978 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3979 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3980 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3981 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3982 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3984 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3985 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3986 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3987 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3988 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3989 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3992 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3993 let zero_fees = RoutingFees {
3995 proportional_millionths: 0,
3997 vec![RouteHint(vec![RouteHintHop {
3998 src_node_id: nodes[4],
3999 short_channel_id: 11,
4001 cltv_expiry_delta: (11 << 4) | 1,
4002 htlc_minimum_msat: None,
4003 htlc_maximum_msat: None,
4005 src_node_id: nodes[3],
4006 short_channel_id: 8,
4008 cltv_expiry_delta: (8 << 4) | 1,
4009 htlc_minimum_msat: None,
4010 htlc_maximum_msat: None,
4011 }]), RouteHint(vec![RouteHintHop {
4012 src_node_id: nodes[4],
4013 short_channel_id: 9,
4016 proportional_millionths: 0,
4018 cltv_expiry_delta: (9 << 4) | 1,
4019 htlc_minimum_msat: None,
4020 htlc_maximum_msat: None,
4021 }]), RouteHint(vec![RouteHintHop {
4022 src_node_id: nodes[5],
4023 short_channel_id: 10,
4025 cltv_expiry_delta: (10 << 4) | 1,
4026 htlc_minimum_msat: None,
4027 htlc_maximum_msat: None,
4032 fn last_hops_with_public_channel_test() {
4033 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4034 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4035 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4036 let scorer = ln_test_utils::TestScorer::new();
4037 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4038 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4039 // This test shows that public routes can be present in the invoice
4040 // which would be handled in the same manner.
4042 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4043 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4044 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4045 assert_eq!(route.paths[0].hops.len(), 5);
4047 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4048 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4049 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4050 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4051 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4052 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4054 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4055 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4056 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4057 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4058 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4059 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4061 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4062 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4063 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4064 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4065 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4066 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4068 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4069 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4070 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4071 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4072 // If we have a peer in the node map, we'll use their features here since we don't have
4073 // a way of figuring out their features from the invoice:
4074 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4075 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4077 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4078 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4079 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4080 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4081 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4082 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4086 fn our_chans_last_hop_connect_test() {
4087 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4088 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4089 let scorer = ln_test_utils::TestScorer::new();
4090 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4091 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4093 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4094 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4095 let mut last_hops = last_hops(&nodes);
4096 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4097 .with_route_hints(last_hops.clone()).unwrap();
4098 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4099 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4100 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4101 &Default::default(), &random_seed_bytes).unwrap();
4102 assert_eq!(route.paths[0].hops.len(), 2);
4104 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4105 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4106 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4107 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4108 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4109 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4111 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4112 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4113 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4114 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4115 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4116 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4118 last_hops[0].0[0].fees.base_msat = 1000;
4120 // Revert to via 6 as the fee on 8 goes up
4121 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4122 .with_route_hints(last_hops).unwrap();
4123 let route_params = RouteParameters::from_payment_params_and_value(
4124 payment_params.clone(), 100);
4125 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4126 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4127 assert_eq!(route.paths[0].hops.len(), 4);
4129 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4130 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4131 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4132 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4133 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4134 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4136 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4137 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4138 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4139 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4140 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4141 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4143 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4144 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4145 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4146 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4147 // If we have a peer in the node map, we'll use their features here since we don't have
4148 // a way of figuring out their features from the invoice:
4149 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4150 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4152 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4153 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4154 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4155 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4156 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4157 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4159 // ...but still use 8 for larger payments as 6 has a variable feerate
4160 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4161 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4162 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4163 assert_eq!(route.paths[0].hops.len(), 5);
4165 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4166 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4167 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4168 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4169 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4170 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4172 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4173 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4174 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4175 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4176 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4177 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4179 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4180 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4181 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4182 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4183 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4184 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4186 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4187 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4188 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4189 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4190 // If we have a peer in the node map, we'll use their features here since we don't have
4191 // a way of figuring out their features from the invoice:
4192 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4193 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4195 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4196 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4197 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4198 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4199 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4200 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4203 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> {
4204 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4205 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4206 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4208 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4209 let last_hops = RouteHint(vec![RouteHintHop {
4210 src_node_id: middle_node_id,
4211 short_channel_id: 8,
4214 proportional_millionths: last_hop_fee_prop,
4216 cltv_expiry_delta: (8 << 4) | 1,
4217 htlc_minimum_msat: None,
4218 htlc_maximum_msat: last_hop_htlc_max,
4220 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4221 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4222 let scorer = ln_test_utils::TestScorer::new();
4223 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4224 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4225 let logger = ln_test_utils::TestLogger::new();
4226 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4227 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4228 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4229 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4230 &random_seed_bytes);
4235 fn unannounced_path_test() {
4236 // We should be able to send a payment to a destination without any help of a routing graph
4237 // if we have a channel with a common counterparty that appears in the first and last hop
4239 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4241 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4242 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4243 assert_eq!(route.paths[0].hops.len(), 2);
4245 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4246 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4247 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4248 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4249 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4250 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4252 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4253 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4254 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4255 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4256 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4257 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4261 fn overflow_unannounced_path_test_liquidity_underflow() {
4262 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4263 // the last-hop had a fee which overflowed a u64, we'd panic.
4264 // This was due to us adding the first-hop from us unconditionally, causing us to think
4265 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4266 // In this test, we previously hit a subtraction underflow due to having less available
4267 // liquidity at the last hop than 0.
4268 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());
4272 fn overflow_unannounced_path_test_feerate_overflow() {
4273 // This tests for the same case as above, except instead of hitting a subtraction
4274 // underflow, we hit a case where the fee charged at a hop overflowed.
4275 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());
4279 fn available_amount_while_routing_test() {
4280 // Tests whether we choose the correct available channel amount while routing.
4282 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4283 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4284 let scorer = ln_test_utils::TestScorer::new();
4285 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4286 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4287 let config = UserConfig::default();
4288 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4289 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4292 // We will use a simple single-path route from
4293 // our node to node2 via node0: channels {1, 3}.
4295 // First disable all other paths.
4296 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4297 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4298 short_channel_id: 2,
4301 cltv_expiry_delta: 0,
4302 htlc_minimum_msat: 0,
4303 htlc_maximum_msat: 100_000,
4305 fee_proportional_millionths: 0,
4306 excess_data: Vec::new()
4308 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4309 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4310 short_channel_id: 12,
4313 cltv_expiry_delta: 0,
4314 htlc_minimum_msat: 0,
4315 htlc_maximum_msat: 100_000,
4317 fee_proportional_millionths: 0,
4318 excess_data: Vec::new()
4321 // Make the first channel (#1) very permissive,
4322 // and we will be testing all limits on the second channel.
4323 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4324 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4325 short_channel_id: 1,
4328 cltv_expiry_delta: 0,
4329 htlc_minimum_msat: 0,
4330 htlc_maximum_msat: 1_000_000_000,
4332 fee_proportional_millionths: 0,
4333 excess_data: Vec::new()
4336 // First, let's see if routing works if we have absolutely no idea about the available amount.
4337 // In this case, it should be set to 250_000 sats.
4338 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4339 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4340 short_channel_id: 3,
4343 cltv_expiry_delta: 0,
4344 htlc_minimum_msat: 0,
4345 htlc_maximum_msat: 250_000_000,
4347 fee_proportional_millionths: 0,
4348 excess_data: Vec::new()
4352 // Attempt to route more than available results in a failure.
4353 let route_params = RouteParameters::from_payment_params_and_value(
4354 payment_params.clone(), 250_000_001);
4355 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4356 &our_id, &route_params, &network_graph.read_only(), None,
4357 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4358 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4359 } else { panic!(); }
4363 // Now, attempt to route an exact amount we have should be fine.
4364 let route_params = RouteParameters::from_payment_params_and_value(
4365 payment_params.clone(), 250_000_000);
4366 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4367 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4368 assert_eq!(route.paths.len(), 1);
4369 let path = route.paths.last().unwrap();
4370 assert_eq!(path.hops.len(), 2);
4371 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4372 assert_eq!(path.final_value_msat(), 250_000_000);
4375 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4376 // Disable channel #1 and use another first hop.
4377 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4378 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4379 short_channel_id: 1,
4382 cltv_expiry_delta: 0,
4383 htlc_minimum_msat: 0,
4384 htlc_maximum_msat: 1_000_000_000,
4386 fee_proportional_millionths: 0,
4387 excess_data: Vec::new()
4390 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4391 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4394 // Attempt to route more than available results in a failure.
4395 let route_params = RouteParameters::from_payment_params_and_value(
4396 payment_params.clone(), 200_000_001);
4397 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4398 &our_id, &route_params, &network_graph.read_only(),
4399 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4400 &Default::default(), &random_seed_bytes) {
4401 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4402 } else { panic!(); }
4406 // Now, attempt to route an exact amount we have should be fine.
4407 let route_params = RouteParameters::from_payment_params_and_value(
4408 payment_params.clone(), 200_000_000);
4409 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4410 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4411 &Default::default(), &random_seed_bytes).unwrap();
4412 assert_eq!(route.paths.len(), 1);
4413 let path = route.paths.last().unwrap();
4414 assert_eq!(path.hops.len(), 2);
4415 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4416 assert_eq!(path.final_value_msat(), 200_000_000);
4419 // Enable channel #1 back.
4420 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4421 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4422 short_channel_id: 1,
4425 cltv_expiry_delta: 0,
4426 htlc_minimum_msat: 0,
4427 htlc_maximum_msat: 1_000_000_000,
4429 fee_proportional_millionths: 0,
4430 excess_data: Vec::new()
4434 // Now let's see if routing works if we know only htlc_maximum_msat.
4435 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4436 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4437 short_channel_id: 3,
4440 cltv_expiry_delta: 0,
4441 htlc_minimum_msat: 0,
4442 htlc_maximum_msat: 15_000,
4444 fee_proportional_millionths: 0,
4445 excess_data: Vec::new()
4449 // Attempt to route more than available results in a failure.
4450 let route_params = RouteParameters::from_payment_params_and_value(
4451 payment_params.clone(), 15_001);
4452 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4453 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4454 &scorer, &Default::default(), &random_seed_bytes) {
4455 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4456 } else { panic!(); }
4460 // Now, attempt to route an exact amount we have should be fine.
4461 let route_params = RouteParameters::from_payment_params_and_value(
4462 payment_params.clone(), 15_000);
4463 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4464 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4465 assert_eq!(route.paths.len(), 1);
4466 let path = route.paths.last().unwrap();
4467 assert_eq!(path.hops.len(), 2);
4468 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4469 assert_eq!(path.final_value_msat(), 15_000);
4472 // Now let's see if routing works if we know only capacity from the UTXO.
4474 // We can't change UTXO capacity on the fly, so we'll disable
4475 // the existing channel and add another one with the capacity we need.
4476 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4477 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4478 short_channel_id: 3,
4481 cltv_expiry_delta: 0,
4482 htlc_minimum_msat: 0,
4483 htlc_maximum_msat: MAX_VALUE_MSAT,
4485 fee_proportional_millionths: 0,
4486 excess_data: Vec::new()
4489 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4490 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4491 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4492 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4493 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4495 *chain_monitor.utxo_ret.lock().unwrap() =
4496 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4497 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4499 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4500 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4501 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4502 short_channel_id: 333,
4505 cltv_expiry_delta: (3 << 4) | 1,
4506 htlc_minimum_msat: 0,
4507 htlc_maximum_msat: 15_000,
4509 fee_proportional_millionths: 0,
4510 excess_data: Vec::new()
4512 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4513 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4514 short_channel_id: 333,
4517 cltv_expiry_delta: (3 << 4) | 2,
4518 htlc_minimum_msat: 0,
4519 htlc_maximum_msat: 15_000,
4521 fee_proportional_millionths: 0,
4522 excess_data: Vec::new()
4526 // Attempt to route more than available results in a failure.
4527 let route_params = RouteParameters::from_payment_params_and_value(
4528 payment_params.clone(), 15_001);
4529 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4530 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4531 &scorer, &Default::default(), &random_seed_bytes) {
4532 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4533 } else { panic!(); }
4537 // Now, attempt to route an exact amount we have should be fine.
4538 let route_params = RouteParameters::from_payment_params_and_value(
4539 payment_params.clone(), 15_000);
4540 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4541 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4542 assert_eq!(route.paths.len(), 1);
4543 let path = route.paths.last().unwrap();
4544 assert_eq!(path.hops.len(), 2);
4545 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4546 assert_eq!(path.final_value_msat(), 15_000);
4549 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4550 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4551 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4552 short_channel_id: 333,
4555 cltv_expiry_delta: 0,
4556 htlc_minimum_msat: 0,
4557 htlc_maximum_msat: 10_000,
4559 fee_proportional_millionths: 0,
4560 excess_data: Vec::new()
4564 // Attempt to route more than available results in a failure.
4565 let route_params = RouteParameters::from_payment_params_and_value(
4566 payment_params.clone(), 10_001);
4567 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4568 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4569 &scorer, &Default::default(), &random_seed_bytes) {
4570 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4571 } else { panic!(); }
4575 // Now, attempt to route an exact amount we have should be fine.
4576 let route_params = RouteParameters::from_payment_params_and_value(
4577 payment_params.clone(), 10_000);
4578 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4579 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4580 assert_eq!(route.paths.len(), 1);
4581 let path = route.paths.last().unwrap();
4582 assert_eq!(path.hops.len(), 2);
4583 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4584 assert_eq!(path.final_value_msat(), 10_000);
4589 fn available_liquidity_last_hop_test() {
4590 // Check that available liquidity properly limits the path even when only
4591 // one of the latter hops is limited.
4592 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4593 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4594 let scorer = ln_test_utils::TestScorer::new();
4595 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4596 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4597 let config = UserConfig::default();
4598 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4599 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4602 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4603 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4604 // Total capacity: 50 sats.
4606 // Disable other potential paths.
4607 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4608 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4609 short_channel_id: 2,
4612 cltv_expiry_delta: 0,
4613 htlc_minimum_msat: 0,
4614 htlc_maximum_msat: 100_000,
4616 fee_proportional_millionths: 0,
4617 excess_data: Vec::new()
4619 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4620 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4621 short_channel_id: 7,
4624 cltv_expiry_delta: 0,
4625 htlc_minimum_msat: 0,
4626 htlc_maximum_msat: 100_000,
4628 fee_proportional_millionths: 0,
4629 excess_data: Vec::new()
4634 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4635 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4636 short_channel_id: 12,
4639 cltv_expiry_delta: 0,
4640 htlc_minimum_msat: 0,
4641 htlc_maximum_msat: 100_000,
4643 fee_proportional_millionths: 0,
4644 excess_data: Vec::new()
4646 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4647 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4648 short_channel_id: 13,
4651 cltv_expiry_delta: 0,
4652 htlc_minimum_msat: 0,
4653 htlc_maximum_msat: 100_000,
4655 fee_proportional_millionths: 0,
4656 excess_data: Vec::new()
4659 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4660 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4661 short_channel_id: 6,
4664 cltv_expiry_delta: 0,
4665 htlc_minimum_msat: 0,
4666 htlc_maximum_msat: 50_000,
4668 fee_proportional_millionths: 0,
4669 excess_data: Vec::new()
4671 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4672 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4673 short_channel_id: 11,
4676 cltv_expiry_delta: 0,
4677 htlc_minimum_msat: 0,
4678 htlc_maximum_msat: 100_000,
4680 fee_proportional_millionths: 0,
4681 excess_data: Vec::new()
4684 // Attempt to route more than available results in a failure.
4685 let route_params = RouteParameters::from_payment_params_and_value(
4686 payment_params.clone(), 60_000);
4687 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4688 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4689 &scorer, &Default::default(), &random_seed_bytes) {
4690 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4691 } else { panic!(); }
4695 // Now, attempt to route 49 sats (just a bit below the capacity).
4696 let route_params = RouteParameters::from_payment_params_and_value(
4697 payment_params.clone(), 49_000);
4698 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4699 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4700 assert_eq!(route.paths.len(), 1);
4701 let mut total_amount_paid_msat = 0;
4702 for path in &route.paths {
4703 assert_eq!(path.hops.len(), 4);
4704 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4705 total_amount_paid_msat += path.final_value_msat();
4707 assert_eq!(total_amount_paid_msat, 49_000);
4711 // Attempt to route an exact amount is also fine
4712 let route_params = RouteParameters::from_payment_params_and_value(
4713 payment_params, 50_000);
4714 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4715 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4716 assert_eq!(route.paths.len(), 1);
4717 let mut total_amount_paid_msat = 0;
4718 for path in &route.paths {
4719 assert_eq!(path.hops.len(), 4);
4720 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4721 total_amount_paid_msat += path.final_value_msat();
4723 assert_eq!(total_amount_paid_msat, 50_000);
4728 fn ignore_fee_first_hop_test() {
4729 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4730 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4731 let scorer = ln_test_utils::TestScorer::new();
4732 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4733 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4734 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4736 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4737 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4738 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4739 short_channel_id: 1,
4742 cltv_expiry_delta: 0,
4743 htlc_minimum_msat: 0,
4744 htlc_maximum_msat: 100_000,
4745 fee_base_msat: 1_000_000,
4746 fee_proportional_millionths: 0,
4747 excess_data: Vec::new()
4749 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4750 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4751 short_channel_id: 3,
4754 cltv_expiry_delta: 0,
4755 htlc_minimum_msat: 0,
4756 htlc_maximum_msat: 50_000,
4758 fee_proportional_millionths: 0,
4759 excess_data: Vec::new()
4763 let route_params = RouteParameters::from_payment_params_and_value(
4764 payment_params, 50_000);
4765 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4766 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4767 assert_eq!(route.paths.len(), 1);
4768 let mut total_amount_paid_msat = 0;
4769 for path in &route.paths {
4770 assert_eq!(path.hops.len(), 2);
4771 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4772 total_amount_paid_msat += path.final_value_msat();
4774 assert_eq!(total_amount_paid_msat, 50_000);
4779 fn simple_mpp_route_test() {
4780 let (secp_ctx, _, _, _, _) = build_graph();
4781 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4782 let config = UserConfig::default();
4783 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4784 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4786 do_simple_mpp_route_test(clear_payment_params);
4788 // MPP to a 1-hop blinded path for nodes[2]
4789 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
4790 let blinded_path = BlindedPath {
4791 introduction_node_id: nodes[2],
4792 blinding_point: ln_test_utils::pubkey(42),
4793 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4795 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4797 fee_proportional_millionths: 0,
4798 htlc_minimum_msat: 0,
4799 htlc_maximum_msat: 0,
4800 cltv_expiry_delta: 0,
4801 features: BlindedHopFeatures::empty(),
4803 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4804 .with_bolt12_features(bolt12_features.clone()).unwrap();
4805 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4807 // MPP to 3 2-hop blinded paths
4808 let mut blinded_path_node_0 = blinded_path.clone();
4809 blinded_path_node_0.introduction_node_id = nodes[0];
4810 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4811 let mut node_0_payinfo = blinded_payinfo.clone();
4812 node_0_payinfo.htlc_maximum_msat = 50_000;
4814 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4815 blinded_path_node_7.introduction_node_id = nodes[7];
4816 let mut node_7_payinfo = blinded_payinfo.clone();
4817 node_7_payinfo.htlc_maximum_msat = 60_000;
4819 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4820 blinded_path_node_1.introduction_node_id = nodes[1];
4821 let mut node_1_payinfo = blinded_payinfo.clone();
4822 node_1_payinfo.htlc_maximum_msat = 180_000;
4824 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4826 (node_0_payinfo, blinded_path_node_0),
4827 (node_7_payinfo, blinded_path_node_7),
4828 (node_1_payinfo, blinded_path_node_1)
4830 .with_bolt12_features(bolt12_features).unwrap();
4831 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4835 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4836 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4837 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4838 let scorer = ln_test_utils::TestScorer::new();
4839 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4840 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4842 // We need a route consisting of 3 paths:
4843 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4844 // To achieve this, the amount being transferred should be around
4845 // the total capacity of these 3 paths.
4847 // First, we set limits on these (previously unlimited) channels.
4848 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4850 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4851 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4852 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4853 short_channel_id: 1,
4856 cltv_expiry_delta: 0,
4857 htlc_minimum_msat: 0,
4858 htlc_maximum_msat: 100_000,
4860 fee_proportional_millionths: 0,
4861 excess_data: Vec::new()
4863 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4864 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4865 short_channel_id: 3,
4868 cltv_expiry_delta: 0,
4869 htlc_minimum_msat: 0,
4870 htlc_maximum_msat: 50_000,
4872 fee_proportional_millionths: 0,
4873 excess_data: Vec::new()
4876 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4877 // (total limit 60).
4878 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4879 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4880 short_channel_id: 12,
4883 cltv_expiry_delta: 0,
4884 htlc_minimum_msat: 0,
4885 htlc_maximum_msat: 60_000,
4887 fee_proportional_millionths: 0,
4888 excess_data: Vec::new()
4890 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4891 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4892 short_channel_id: 13,
4895 cltv_expiry_delta: 0,
4896 htlc_minimum_msat: 0,
4897 htlc_maximum_msat: 60_000,
4899 fee_proportional_millionths: 0,
4900 excess_data: Vec::new()
4903 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4904 // (total capacity 180 sats).
4905 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4906 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4907 short_channel_id: 2,
4910 cltv_expiry_delta: 0,
4911 htlc_minimum_msat: 0,
4912 htlc_maximum_msat: 200_000,
4914 fee_proportional_millionths: 0,
4915 excess_data: Vec::new()
4917 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4918 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4919 short_channel_id: 4,
4922 cltv_expiry_delta: 0,
4923 htlc_minimum_msat: 0,
4924 htlc_maximum_msat: 180_000,
4926 fee_proportional_millionths: 0,
4927 excess_data: Vec::new()
4931 // Attempt to route more than available results in a failure.
4932 let route_params = RouteParameters::from_payment_params_and_value(
4933 payment_params.clone(), 300_000);
4934 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4935 &our_id, &route_params, &network_graph.read_only(), None,
4936 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4937 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4938 } else { panic!(); }
4942 // Attempt to route while setting max_path_count to 0 results in a failure.
4943 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4944 let route_params = RouteParameters::from_payment_params_and_value(
4945 zero_payment_params, 100);
4946 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4947 &our_id, &route_params, &network_graph.read_only(), None,
4948 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4949 assert_eq!(err, "Can't find a route with no paths allowed.");
4950 } else { panic!(); }
4954 // Attempt to route while setting max_path_count to 3 results in a failure.
4955 // This is the case because the minimal_value_contribution_msat would require each path
4956 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4957 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4958 let route_params = RouteParameters::from_payment_params_and_value(
4959 fail_payment_params, 250_000);
4960 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4961 &our_id, &route_params, &network_graph.read_only(), None,
4962 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4963 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4964 } else { panic!(); }
4968 // Now, attempt to route 250 sats (just a bit below the capacity).
4969 // Our algorithm should provide us with these 3 paths.
4970 let route_params = RouteParameters::from_payment_params_and_value(
4971 payment_params.clone(), 250_000);
4972 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4973 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4974 assert_eq!(route.paths.len(), 3);
4975 let mut total_amount_paid_msat = 0;
4976 for path in &route.paths {
4977 if let Some(bt) = &path.blinded_tail {
4978 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4980 assert_eq!(path.hops.len(), 2);
4981 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4983 total_amount_paid_msat += path.final_value_msat();
4985 assert_eq!(total_amount_paid_msat, 250_000);
4989 // Attempt to route an exact amount is also fine
4990 let route_params = RouteParameters::from_payment_params_and_value(
4991 payment_params.clone(), 290_000);
4992 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4993 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4994 assert_eq!(route.paths.len(), 3);
4995 let mut total_amount_paid_msat = 0;
4996 for path in &route.paths {
4997 if payment_params.payee.blinded_route_hints().len() != 0 {
4998 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4999 if let Some(bt) = &path.blinded_tail {
5000 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5001 if bt.hops.len() > 1 {
5002 assert_eq!(path.hops.last().unwrap().pubkey,
5003 payment_params.payee.blinded_route_hints().iter()
5004 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5005 .map(|(_, p)| p.introduction_node_id).unwrap());
5007 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5010 assert_eq!(path.hops.len(), 2);
5011 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5013 total_amount_paid_msat += path.final_value_msat();
5015 assert_eq!(total_amount_paid_msat, 290_000);
5020 fn long_mpp_route_test() {
5021 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5022 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5023 let scorer = ln_test_utils::TestScorer::new();
5024 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5025 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5026 let config = UserConfig::default();
5027 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5028 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5031 // We need a route consisting of 3 paths:
5032 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5033 // Note that these paths overlap (channels 5, 12, 13).
5034 // We will route 300 sats.
5035 // Each path will have 100 sats capacity, those channels which
5036 // are used twice will have 200 sats capacity.
5038 // Disable other potential paths.
5039 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5040 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5041 short_channel_id: 2,
5044 cltv_expiry_delta: 0,
5045 htlc_minimum_msat: 0,
5046 htlc_maximum_msat: 100_000,
5048 fee_proportional_millionths: 0,
5049 excess_data: Vec::new()
5051 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5052 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5053 short_channel_id: 7,
5056 cltv_expiry_delta: 0,
5057 htlc_minimum_msat: 0,
5058 htlc_maximum_msat: 100_000,
5060 fee_proportional_millionths: 0,
5061 excess_data: Vec::new()
5064 // Path via {node0, node2} is channels {1, 3, 5}.
5065 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5066 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5067 short_channel_id: 1,
5070 cltv_expiry_delta: 0,
5071 htlc_minimum_msat: 0,
5072 htlc_maximum_msat: 100_000,
5074 fee_proportional_millionths: 0,
5075 excess_data: Vec::new()
5077 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5078 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5079 short_channel_id: 3,
5082 cltv_expiry_delta: 0,
5083 htlc_minimum_msat: 0,
5084 htlc_maximum_msat: 100_000,
5086 fee_proportional_millionths: 0,
5087 excess_data: Vec::new()
5090 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5091 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5092 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5093 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5094 short_channel_id: 5,
5097 cltv_expiry_delta: 0,
5098 htlc_minimum_msat: 0,
5099 htlc_maximum_msat: 200_000,
5101 fee_proportional_millionths: 0,
5102 excess_data: Vec::new()
5105 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5106 // Add 100 sats to the capacities of {12, 13}, because these channels
5107 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5108 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5109 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5110 short_channel_id: 12,
5113 cltv_expiry_delta: 0,
5114 htlc_minimum_msat: 0,
5115 htlc_maximum_msat: 200_000,
5117 fee_proportional_millionths: 0,
5118 excess_data: Vec::new()
5120 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5121 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5122 short_channel_id: 13,
5125 cltv_expiry_delta: 0,
5126 htlc_minimum_msat: 0,
5127 htlc_maximum_msat: 200_000,
5129 fee_proportional_millionths: 0,
5130 excess_data: Vec::new()
5133 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5134 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5135 short_channel_id: 6,
5138 cltv_expiry_delta: 0,
5139 htlc_minimum_msat: 0,
5140 htlc_maximum_msat: 100_000,
5142 fee_proportional_millionths: 0,
5143 excess_data: Vec::new()
5145 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5146 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5147 short_channel_id: 11,
5150 cltv_expiry_delta: 0,
5151 htlc_minimum_msat: 0,
5152 htlc_maximum_msat: 100_000,
5154 fee_proportional_millionths: 0,
5155 excess_data: Vec::new()
5158 // Path via {node7, node2} is channels {12, 13, 5}.
5159 // We already limited them to 200 sats (they are used twice for 100 sats).
5160 // Nothing to do here.
5163 // Attempt to route more than available results in a failure.
5164 let route_params = RouteParameters::from_payment_params_and_value(
5165 payment_params.clone(), 350_000);
5166 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5167 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5168 &scorer, &Default::default(), &random_seed_bytes) {
5169 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5170 } else { panic!(); }
5174 // Now, attempt to route 300 sats (exact amount we can route).
5175 // Our algorithm should provide us with these 3 paths, 100 sats each.
5176 let route_params = RouteParameters::from_payment_params_and_value(
5177 payment_params, 300_000);
5178 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5179 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5180 assert_eq!(route.paths.len(), 3);
5182 let mut total_amount_paid_msat = 0;
5183 for path in &route.paths {
5184 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5185 total_amount_paid_msat += path.final_value_msat();
5187 assert_eq!(total_amount_paid_msat, 300_000);
5193 fn mpp_cheaper_route_test() {
5194 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5195 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5196 let scorer = ln_test_utils::TestScorer::new();
5197 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5198 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5199 let config = UserConfig::default();
5200 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5201 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5204 // This test checks that if we have two cheaper paths and one more expensive path,
5205 // so that liquidity-wise any 2 of 3 combination is sufficient,
5206 // two cheaper paths will be taken.
5207 // These paths have equal available liquidity.
5209 // We need a combination of 3 paths:
5210 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5211 // Note that these paths overlap (channels 5, 12, 13).
5212 // Each path will have 100 sats capacity, those channels which
5213 // are used twice will have 200 sats capacity.
5215 // Disable other potential paths.
5216 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5217 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5218 short_channel_id: 2,
5221 cltv_expiry_delta: 0,
5222 htlc_minimum_msat: 0,
5223 htlc_maximum_msat: 100_000,
5225 fee_proportional_millionths: 0,
5226 excess_data: Vec::new()
5228 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5229 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5230 short_channel_id: 7,
5233 cltv_expiry_delta: 0,
5234 htlc_minimum_msat: 0,
5235 htlc_maximum_msat: 100_000,
5237 fee_proportional_millionths: 0,
5238 excess_data: Vec::new()
5241 // Path via {node0, node2} is channels {1, 3, 5}.
5242 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5243 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5244 short_channel_id: 1,
5247 cltv_expiry_delta: 0,
5248 htlc_minimum_msat: 0,
5249 htlc_maximum_msat: 100_000,
5251 fee_proportional_millionths: 0,
5252 excess_data: Vec::new()
5254 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5255 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5256 short_channel_id: 3,
5259 cltv_expiry_delta: 0,
5260 htlc_minimum_msat: 0,
5261 htlc_maximum_msat: 100_000,
5263 fee_proportional_millionths: 0,
5264 excess_data: Vec::new()
5267 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5268 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5269 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5270 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5271 short_channel_id: 5,
5274 cltv_expiry_delta: 0,
5275 htlc_minimum_msat: 0,
5276 htlc_maximum_msat: 200_000,
5278 fee_proportional_millionths: 0,
5279 excess_data: Vec::new()
5282 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5283 // Add 100 sats to the capacities of {12, 13}, because these channels
5284 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5285 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5286 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5287 short_channel_id: 12,
5290 cltv_expiry_delta: 0,
5291 htlc_minimum_msat: 0,
5292 htlc_maximum_msat: 200_000,
5294 fee_proportional_millionths: 0,
5295 excess_data: Vec::new()
5297 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5298 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5299 short_channel_id: 13,
5302 cltv_expiry_delta: 0,
5303 htlc_minimum_msat: 0,
5304 htlc_maximum_msat: 200_000,
5306 fee_proportional_millionths: 0,
5307 excess_data: Vec::new()
5310 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5311 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5312 short_channel_id: 6,
5315 cltv_expiry_delta: 0,
5316 htlc_minimum_msat: 0,
5317 htlc_maximum_msat: 100_000,
5318 fee_base_msat: 1_000,
5319 fee_proportional_millionths: 0,
5320 excess_data: Vec::new()
5322 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5323 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5324 short_channel_id: 11,
5327 cltv_expiry_delta: 0,
5328 htlc_minimum_msat: 0,
5329 htlc_maximum_msat: 100_000,
5331 fee_proportional_millionths: 0,
5332 excess_data: Vec::new()
5335 // Path via {node7, node2} is channels {12, 13, 5}.
5336 // We already limited them to 200 sats (they are used twice for 100 sats).
5337 // Nothing to do here.
5340 // Now, attempt to route 180 sats.
5341 // Our algorithm should provide us with these 2 paths.
5342 let route_params = RouteParameters::from_payment_params_and_value(
5343 payment_params, 180_000);
5344 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5345 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5346 assert_eq!(route.paths.len(), 2);
5348 let mut total_value_transferred_msat = 0;
5349 let mut total_paid_msat = 0;
5350 for path in &route.paths {
5351 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5352 total_value_transferred_msat += path.final_value_msat();
5353 for hop in &path.hops {
5354 total_paid_msat += hop.fee_msat;
5357 // If we paid fee, this would be higher.
5358 assert_eq!(total_value_transferred_msat, 180_000);
5359 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5360 assert_eq!(total_fees_paid, 0);
5365 fn fees_on_mpp_route_test() {
5366 // This test makes sure that MPP algorithm properly takes into account
5367 // fees charged on the channels, by making the fees impactful:
5368 // if the fee is not properly accounted for, the behavior is different.
5369 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5370 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5371 let scorer = ln_test_utils::TestScorer::new();
5372 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5373 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5374 let config = UserConfig::default();
5375 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5376 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5379 // We need a route consisting of 2 paths:
5380 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5381 // We will route 200 sats, Each path will have 100 sats capacity.
5383 // This test is not particularly stable: e.g.,
5384 // there's a way to route via {node0, node2, node4}.
5385 // It works while pathfinding is deterministic, but can be broken otherwise.
5386 // It's fine to ignore this concern for now.
5388 // Disable other potential paths.
5389 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5390 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5391 short_channel_id: 2,
5394 cltv_expiry_delta: 0,
5395 htlc_minimum_msat: 0,
5396 htlc_maximum_msat: 100_000,
5398 fee_proportional_millionths: 0,
5399 excess_data: Vec::new()
5402 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5403 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5404 short_channel_id: 7,
5407 cltv_expiry_delta: 0,
5408 htlc_minimum_msat: 0,
5409 htlc_maximum_msat: 100_000,
5411 fee_proportional_millionths: 0,
5412 excess_data: Vec::new()
5415 // Path via {node0, node2} is channels {1, 3, 5}.
5416 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5417 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5418 short_channel_id: 1,
5421 cltv_expiry_delta: 0,
5422 htlc_minimum_msat: 0,
5423 htlc_maximum_msat: 100_000,
5425 fee_proportional_millionths: 0,
5426 excess_data: Vec::new()
5428 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5429 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5430 short_channel_id: 3,
5433 cltv_expiry_delta: 0,
5434 htlc_minimum_msat: 0,
5435 htlc_maximum_msat: 100_000,
5437 fee_proportional_millionths: 0,
5438 excess_data: Vec::new()
5441 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5442 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5443 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5444 short_channel_id: 5,
5447 cltv_expiry_delta: 0,
5448 htlc_minimum_msat: 0,
5449 htlc_maximum_msat: 100_000,
5451 fee_proportional_millionths: 0,
5452 excess_data: Vec::new()
5455 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5456 // All channels should be 100 sats capacity. But for the fee experiment,
5457 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5458 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5459 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5460 // so no matter how large are other channels,
5461 // the whole path will be limited by 100 sats with just these 2 conditions:
5462 // - channel 12 capacity is 250 sats
5463 // - fee for channel 6 is 150 sats
5464 // Let's test this by enforcing these 2 conditions and removing other limits.
5465 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5466 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5467 short_channel_id: 12,
5470 cltv_expiry_delta: 0,
5471 htlc_minimum_msat: 0,
5472 htlc_maximum_msat: 250_000,
5474 fee_proportional_millionths: 0,
5475 excess_data: Vec::new()
5477 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5478 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5479 short_channel_id: 13,
5482 cltv_expiry_delta: 0,
5483 htlc_minimum_msat: 0,
5484 htlc_maximum_msat: MAX_VALUE_MSAT,
5486 fee_proportional_millionths: 0,
5487 excess_data: Vec::new()
5490 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5491 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5492 short_channel_id: 6,
5495 cltv_expiry_delta: 0,
5496 htlc_minimum_msat: 0,
5497 htlc_maximum_msat: MAX_VALUE_MSAT,
5498 fee_base_msat: 150_000,
5499 fee_proportional_millionths: 0,
5500 excess_data: Vec::new()
5502 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5503 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5504 short_channel_id: 11,
5507 cltv_expiry_delta: 0,
5508 htlc_minimum_msat: 0,
5509 htlc_maximum_msat: MAX_VALUE_MSAT,
5511 fee_proportional_millionths: 0,
5512 excess_data: Vec::new()
5516 // Attempt to route more than available results in a failure.
5517 let route_params = RouteParameters::from_payment_params_and_value(
5518 payment_params.clone(), 210_000);
5519 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5520 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5521 &scorer, &Default::default(), &random_seed_bytes) {
5522 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5523 } else { panic!(); }
5527 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5528 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5529 max_total_routing_fee_msat: Some(149_999) };
5530 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5531 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5532 &scorer, &Default::default(), &random_seed_bytes) {
5533 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5534 } else { panic!(); }
5538 // Now, attempt to route 200 sats (exact amount we can route).
5539 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5540 max_total_routing_fee_msat: Some(150_000) };
5541 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5542 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5543 assert_eq!(route.paths.len(), 2);
5545 let mut total_amount_paid_msat = 0;
5546 for path in &route.paths {
5547 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5548 total_amount_paid_msat += path.final_value_msat();
5550 assert_eq!(total_amount_paid_msat, 200_000);
5551 assert_eq!(route.get_total_fees(), 150_000);
5556 fn mpp_with_last_hops() {
5557 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5558 // via a single last-hop route hint, we'd fail to route if we first collected routes
5559 // totaling close but not quite enough to fund the full payment.
5561 // This was because we considered last-hop hints to have exactly the sought payment amount
5562 // instead of the amount we were trying to collect, needlessly limiting our path searching
5563 // at the very first hop.
5565 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5566 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5567 // to only have the remaining to-collect amount in available liquidity.
5569 // This bug appeared in production in some specific channel configurations.
5570 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5571 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5572 let scorer = ln_test_utils::TestScorer::new();
5573 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5574 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5575 let config = UserConfig::default();
5576 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5577 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5578 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5579 src_node_id: nodes[2],
5580 short_channel_id: 42,
5581 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5582 cltv_expiry_delta: 42,
5583 htlc_minimum_msat: None,
5584 htlc_maximum_msat: None,
5585 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5587 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5588 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5589 // would first use the no-fee route and then fail to find a path along the second route as
5590 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5591 // under 5% of our payment amount.
5592 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5593 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5594 short_channel_id: 1,
5597 cltv_expiry_delta: (5 << 4) | 5,
5598 htlc_minimum_msat: 0,
5599 htlc_maximum_msat: 99_000,
5600 fee_base_msat: u32::max_value(),
5601 fee_proportional_millionths: u32::max_value(),
5602 excess_data: Vec::new()
5604 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5605 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5606 short_channel_id: 2,
5609 cltv_expiry_delta: (5 << 4) | 3,
5610 htlc_minimum_msat: 0,
5611 htlc_maximum_msat: 99_000,
5612 fee_base_msat: u32::max_value(),
5613 fee_proportional_millionths: u32::max_value(),
5614 excess_data: Vec::new()
5616 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5617 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5618 short_channel_id: 4,
5621 cltv_expiry_delta: (4 << 4) | 1,
5622 htlc_minimum_msat: 0,
5623 htlc_maximum_msat: MAX_VALUE_MSAT,
5625 fee_proportional_millionths: 0,
5626 excess_data: Vec::new()
5628 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5629 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5630 short_channel_id: 13,
5632 flags: 0|2, // Channel disabled
5633 cltv_expiry_delta: (13 << 4) | 1,
5634 htlc_minimum_msat: 0,
5635 htlc_maximum_msat: MAX_VALUE_MSAT,
5637 fee_proportional_millionths: 2000000,
5638 excess_data: Vec::new()
5641 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5643 let route_params = RouteParameters::from_payment_params_and_value(
5644 payment_params, 100_000);
5645 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5646 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5647 assert_eq!(route.paths.len(), 2);
5648 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5649 // Paths are manually ordered ordered by SCID, so:
5650 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5651 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5652 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5653 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5654 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5655 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5656 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5657 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5658 assert_eq!(route.get_total_fees(), 1);
5659 assert_eq!(route.get_total_amount(), 100_000);
5663 fn drop_lowest_channel_mpp_route_test() {
5664 // This test checks that low-capacity channel is dropped when after
5665 // path finding we realize that we found more capacity than we need.
5666 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5667 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5668 let scorer = ln_test_utils::TestScorer::new();
5669 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5670 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5671 let config = UserConfig::default();
5672 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5673 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5675 .with_max_channel_saturation_power_of_half(0);
5677 // We need a route consisting of 3 paths:
5678 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5680 // The first and the second paths should be sufficient, but the third should be
5681 // cheaper, so that we select it but drop later.
5683 // First, we set limits on these (previously unlimited) channels.
5684 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5686 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5687 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5688 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5689 short_channel_id: 1,
5692 cltv_expiry_delta: 0,
5693 htlc_minimum_msat: 0,
5694 htlc_maximum_msat: 100_000,
5696 fee_proportional_millionths: 0,
5697 excess_data: Vec::new()
5699 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5700 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5701 short_channel_id: 3,
5704 cltv_expiry_delta: 0,
5705 htlc_minimum_msat: 0,
5706 htlc_maximum_msat: 50_000,
5708 fee_proportional_millionths: 0,
5709 excess_data: Vec::new()
5712 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5713 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5714 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5715 short_channel_id: 12,
5718 cltv_expiry_delta: 0,
5719 htlc_minimum_msat: 0,
5720 htlc_maximum_msat: 60_000,
5722 fee_proportional_millionths: 0,
5723 excess_data: Vec::new()
5725 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5726 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5727 short_channel_id: 13,
5730 cltv_expiry_delta: 0,
5731 htlc_minimum_msat: 0,
5732 htlc_maximum_msat: 60_000,
5734 fee_proportional_millionths: 0,
5735 excess_data: Vec::new()
5738 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5739 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5740 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5741 short_channel_id: 2,
5744 cltv_expiry_delta: 0,
5745 htlc_minimum_msat: 0,
5746 htlc_maximum_msat: 20_000,
5748 fee_proportional_millionths: 0,
5749 excess_data: Vec::new()
5751 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5752 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5753 short_channel_id: 4,
5756 cltv_expiry_delta: 0,
5757 htlc_minimum_msat: 0,
5758 htlc_maximum_msat: 20_000,
5760 fee_proportional_millionths: 0,
5761 excess_data: Vec::new()
5765 // Attempt to route more than available results in a failure.
5766 let route_params = RouteParameters::from_payment_params_and_value(
5767 payment_params.clone(), 150_000);
5768 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5769 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5770 &scorer, &Default::default(), &random_seed_bytes) {
5771 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5772 } else { panic!(); }
5776 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5777 // Our algorithm should provide us with these 3 paths.
5778 let route_params = RouteParameters::from_payment_params_and_value(
5779 payment_params.clone(), 125_000);
5780 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5781 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5782 assert_eq!(route.paths.len(), 3);
5783 let mut total_amount_paid_msat = 0;
5784 for path in &route.paths {
5785 assert_eq!(path.hops.len(), 2);
5786 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5787 total_amount_paid_msat += path.final_value_msat();
5789 assert_eq!(total_amount_paid_msat, 125_000);
5793 // Attempt to route without the last small cheap channel
5794 let route_params = RouteParameters::from_payment_params_and_value(
5795 payment_params, 90_000);
5796 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5797 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5798 assert_eq!(route.paths.len(), 2);
5799 let mut total_amount_paid_msat = 0;
5800 for path in &route.paths {
5801 assert_eq!(path.hops.len(), 2);
5802 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5803 total_amount_paid_msat += path.final_value_msat();
5805 assert_eq!(total_amount_paid_msat, 90_000);
5810 fn min_criteria_consistency() {
5811 // Test that we don't use an inconsistent metric between updating and walking nodes during
5812 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5813 // was updated with a different criterion from the heap sorting, resulting in loops in
5814 // calculated paths. We test for that specific case here.
5816 // We construct a network that looks like this:
5818 // node2 -1(3)2- node3
5822 // node1 -1(5)2- node4 -1(1)2- node6
5828 // We create a loop on the side of our real path - our destination is node 6, with a
5829 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5830 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5831 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5832 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5833 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5834 // "previous hop" being set to node 3, creating a loop in the path.
5835 let secp_ctx = Secp256k1::new();
5836 let logger = Arc::new(ln_test_utils::TestLogger::new());
5837 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5838 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5839 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5840 let scorer = ln_test_utils::TestScorer::new();
5841 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5842 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5843 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5845 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5846 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5847 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5848 short_channel_id: 6,
5851 cltv_expiry_delta: (6 << 4) | 0,
5852 htlc_minimum_msat: 0,
5853 htlc_maximum_msat: MAX_VALUE_MSAT,
5855 fee_proportional_millionths: 0,
5856 excess_data: Vec::new()
5858 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5860 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5861 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5862 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5863 short_channel_id: 5,
5866 cltv_expiry_delta: (5 << 4) | 0,
5867 htlc_minimum_msat: 0,
5868 htlc_maximum_msat: MAX_VALUE_MSAT,
5870 fee_proportional_millionths: 0,
5871 excess_data: Vec::new()
5873 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5875 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5876 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5877 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5878 short_channel_id: 4,
5881 cltv_expiry_delta: (4 << 4) | 0,
5882 htlc_minimum_msat: 0,
5883 htlc_maximum_msat: MAX_VALUE_MSAT,
5885 fee_proportional_millionths: 0,
5886 excess_data: Vec::new()
5888 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5890 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5891 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5892 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5893 short_channel_id: 3,
5896 cltv_expiry_delta: (3 << 4) | 0,
5897 htlc_minimum_msat: 0,
5898 htlc_maximum_msat: MAX_VALUE_MSAT,
5900 fee_proportional_millionths: 0,
5901 excess_data: Vec::new()
5903 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5905 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5906 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5907 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5908 short_channel_id: 2,
5911 cltv_expiry_delta: (2 << 4) | 0,
5912 htlc_minimum_msat: 0,
5913 htlc_maximum_msat: MAX_VALUE_MSAT,
5915 fee_proportional_millionths: 0,
5916 excess_data: Vec::new()
5919 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5920 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5921 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5922 short_channel_id: 1,
5925 cltv_expiry_delta: (1 << 4) | 0,
5926 htlc_minimum_msat: 100,
5927 htlc_maximum_msat: MAX_VALUE_MSAT,
5929 fee_proportional_millionths: 0,
5930 excess_data: Vec::new()
5932 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5935 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5936 let route_params = RouteParameters::from_payment_params_and_value(
5937 payment_params, 10_000);
5938 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5939 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5940 assert_eq!(route.paths.len(), 1);
5941 assert_eq!(route.paths[0].hops.len(), 3);
5943 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5944 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5945 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5946 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5947 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5948 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5950 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5951 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5952 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5953 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5954 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5955 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5957 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5958 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5959 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5960 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5961 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5962 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5968 fn exact_fee_liquidity_limit() {
5969 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5970 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5971 // we calculated fees on a higher value, resulting in us ignoring such paths.
5972 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5973 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5974 let scorer = ln_test_utils::TestScorer::new();
5975 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5976 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5977 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5979 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5981 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5982 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5983 short_channel_id: 2,
5986 cltv_expiry_delta: 0,
5987 htlc_minimum_msat: 0,
5988 htlc_maximum_msat: 85_000,
5990 fee_proportional_millionths: 0,
5991 excess_data: Vec::new()
5994 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5995 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5996 short_channel_id: 12,
5999 cltv_expiry_delta: (4 << 4) | 1,
6000 htlc_minimum_msat: 0,
6001 htlc_maximum_msat: 270_000,
6003 fee_proportional_millionths: 1000000,
6004 excess_data: Vec::new()
6008 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6009 // 200% fee charged channel 13 in the 1-to-2 direction.
6010 let mut route_params = RouteParameters::from_payment_params_and_value(
6011 payment_params, 90_000);
6012 route_params.max_total_routing_fee_msat = Some(90_000*2);
6013 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6014 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6015 assert_eq!(route.paths.len(), 1);
6016 assert_eq!(route.paths[0].hops.len(), 2);
6018 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6019 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6020 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6021 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6022 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6023 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6025 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6026 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6027 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6028 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6029 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6030 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6035 fn htlc_max_reduction_below_min() {
6036 // Test that if, while walking the graph, we reduce the value being sent to meet an
6037 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6038 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6039 // resulting in us thinking there is no possible path, even if other paths exist.
6040 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6041 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6042 let scorer = ln_test_utils::TestScorer::new();
6043 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6044 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6045 let config = UserConfig::default();
6046 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6047 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6050 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6051 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6052 // then try to send 90_000.
6053 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6054 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6055 short_channel_id: 2,
6058 cltv_expiry_delta: 0,
6059 htlc_minimum_msat: 0,
6060 htlc_maximum_msat: 80_000,
6062 fee_proportional_millionths: 0,
6063 excess_data: Vec::new()
6065 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6066 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6067 short_channel_id: 4,
6070 cltv_expiry_delta: (4 << 4) | 1,
6071 htlc_minimum_msat: 90_000,
6072 htlc_maximum_msat: MAX_VALUE_MSAT,
6074 fee_proportional_millionths: 0,
6075 excess_data: Vec::new()
6079 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6080 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6081 // expensive) channels 12-13 path.
6082 let mut route_params = RouteParameters::from_payment_params_and_value(
6083 payment_params, 90_000);
6084 route_params.max_total_routing_fee_msat = Some(90_000*2);
6085 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6086 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6087 assert_eq!(route.paths.len(), 1);
6088 assert_eq!(route.paths[0].hops.len(), 2);
6090 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6091 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6092 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6093 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6094 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6095 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6097 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6098 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6099 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6100 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6101 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6102 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6107 fn multiple_direct_first_hops() {
6108 // Previously we'd only ever considered one first hop path per counterparty.
6109 // However, as we don't restrict users to one channel per peer, we really need to support
6110 // looking at all first hop paths.
6111 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6112 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6113 // route over multiple channels with the same first hop.
6114 let secp_ctx = Secp256k1::new();
6115 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6116 let logger = Arc::new(ln_test_utils::TestLogger::new());
6117 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6118 let scorer = ln_test_utils::TestScorer::new();
6119 let config = UserConfig::default();
6120 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6121 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6123 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6124 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6127 let route_params = RouteParameters::from_payment_params_and_value(
6128 payment_params.clone(), 100_000);
6129 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6130 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6131 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6132 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6133 assert_eq!(route.paths.len(), 1);
6134 assert_eq!(route.paths[0].hops.len(), 1);
6136 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6137 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6138 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6141 let route_params = RouteParameters::from_payment_params_and_value(
6142 payment_params.clone(), 100_000);
6143 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6144 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6145 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6146 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6147 assert_eq!(route.paths.len(), 2);
6148 assert_eq!(route.paths[0].hops.len(), 1);
6149 assert_eq!(route.paths[1].hops.len(), 1);
6151 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6152 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6154 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6155 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6157 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6158 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6162 // If we have a bunch of outbound channels to the same node, where most are not
6163 // sufficient to pay the full payment, but one is, we should default to just using the
6164 // one single channel that has sufficient balance, avoiding MPP.
6166 // If we have several options above the 3xpayment value threshold, we should pick the
6167 // smallest of them, avoiding further fragmenting our available outbound balance to
6169 let route_params = RouteParameters::from_payment_params_and_value(
6170 payment_params, 100_000);
6171 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6172 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6173 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6174 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6175 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6176 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6177 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6178 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6179 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6180 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6181 assert_eq!(route.paths.len(), 1);
6182 assert_eq!(route.paths[0].hops.len(), 1);
6184 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6185 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6186 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6191 fn prefers_shorter_route_with_higher_fees() {
6192 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6193 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6194 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6196 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6197 let scorer = ln_test_utils::TestScorer::new();
6198 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6199 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6200 let route_params = RouteParameters::from_payment_params_and_value(
6201 payment_params.clone(), 100);
6202 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6203 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6204 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6206 assert_eq!(route.get_total_fees(), 100);
6207 assert_eq!(route.get_total_amount(), 100);
6208 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6210 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6211 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6212 let scorer = FixedPenaltyScorer::with_penalty(100);
6213 let route_params = RouteParameters::from_payment_params_and_value(
6214 payment_params, 100);
6215 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6216 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6217 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6219 assert_eq!(route.get_total_fees(), 300);
6220 assert_eq!(route.get_total_amount(), 100);
6221 assert_eq!(path, vec![2, 4, 7, 10]);
6224 struct BadChannelScorer {
6225 short_channel_id: u64,
6229 impl Writeable for BadChannelScorer {
6230 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6232 impl ScoreLookUp for BadChannelScorer {
6233 type ScoreParams = ();
6234 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6235 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
6239 struct BadNodeScorer {
6244 impl Writeable for BadNodeScorer {
6245 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6248 impl ScoreLookUp for BadNodeScorer {
6249 type ScoreParams = ();
6250 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6251 if *target == self.node_id { u64::max_value() } else { 0 }
6256 fn avoids_routing_through_bad_channels_and_nodes() {
6257 let (secp_ctx, network, _, _, logger) = build_graph();
6258 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6259 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6260 let network_graph = network.read_only();
6262 // A path to nodes[6] exists when no penalties are applied to any channel.
6263 let scorer = ln_test_utils::TestScorer::new();
6264 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6265 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6266 let route_params = RouteParameters::from_payment_params_and_value(
6267 payment_params, 100);
6268 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6269 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6270 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6272 assert_eq!(route.get_total_fees(), 100);
6273 assert_eq!(route.get_total_amount(), 100);
6274 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6276 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6277 let scorer = BadChannelScorer { short_channel_id: 6 };
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(), 300);
6283 assert_eq!(route.get_total_amount(), 100);
6284 assert_eq!(path, vec![2, 4, 7, 10]);
6286 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6287 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6288 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6289 &scorer, &Default::default(), &random_seed_bytes) {
6290 Err(LightningError { err, .. } ) => {
6291 assert_eq!(err, "Failed to find a path to the given destination");
6293 Ok(_) => panic!("Expected error"),
6298 fn total_fees_single_path() {
6300 paths: vec![Path { hops: vec![
6302 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6303 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6304 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6307 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6308 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6309 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6312 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6313 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6314 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6316 ], blinded_tail: None }],
6320 assert_eq!(route.get_total_fees(), 250);
6321 assert_eq!(route.get_total_amount(), 225);
6325 fn total_fees_multi_path() {
6327 paths: vec![Path { hops: vec![
6329 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6330 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6331 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6334 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6335 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6336 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6338 ], blinded_tail: None }, Path { hops: vec![
6340 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6341 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6342 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6345 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6346 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6347 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6349 ], blinded_tail: None }],
6353 assert_eq!(route.get_total_fees(), 200);
6354 assert_eq!(route.get_total_amount(), 300);
6358 fn total_empty_route_no_panic() {
6359 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6360 // would both panic if the route was completely empty. We test to ensure they return 0
6361 // here, even though its somewhat nonsensical as a route.
6362 let route = Route { paths: Vec::new(), route_params: None };
6364 assert_eq!(route.get_total_fees(), 0);
6365 assert_eq!(route.get_total_amount(), 0);
6369 fn limits_total_cltv_delta() {
6370 let (secp_ctx, network, _, _, logger) = build_graph();
6371 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6372 let network_graph = network.read_only();
6374 let scorer = ln_test_utils::TestScorer::new();
6376 // Make sure that generally there is at least one route available
6377 let feasible_max_total_cltv_delta = 1008;
6378 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6379 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6380 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6381 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6382 let route_params = RouteParameters::from_payment_params_and_value(
6383 feasible_payment_params, 100);
6384 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6385 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6386 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6387 assert_ne!(path.len(), 0);
6389 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6390 let fail_max_total_cltv_delta = 23;
6391 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6392 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6393 let route_params = RouteParameters::from_payment_params_and_value(
6394 fail_payment_params, 100);
6395 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6396 &Default::default(), &random_seed_bytes)
6398 Err(LightningError { err, .. } ) => {
6399 assert_eq!(err, "Failed to find a path to the given destination");
6401 Ok(_) => panic!("Expected error"),
6406 fn avoids_recently_failed_paths() {
6407 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6408 // randomly inserting channels into it until we can't find a route anymore.
6409 let (secp_ctx, network, _, _, logger) = build_graph();
6410 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6411 let network_graph = network.read_only();
6413 let scorer = ln_test_utils::TestScorer::new();
6414 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6415 .with_max_path_count(1);
6416 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6417 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6419 // We should be able to find a route initially, and then after we fail a few random
6420 // channels eventually we won't be able to any longer.
6421 let route_params = RouteParameters::from_payment_params_and_value(
6422 payment_params.clone(), 100);
6423 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6424 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6426 let route_params = RouteParameters::from_payment_params_and_value(
6427 payment_params.clone(), 100);
6428 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6429 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6431 for chan in route.paths[0].hops.iter() {
6432 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6434 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6435 % route.paths[0].hops.len();
6436 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6442 fn limits_path_length() {
6443 let (secp_ctx, network, _, _, logger) = build_line_graph();
6444 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6445 let network_graph = network.read_only();
6447 let scorer = ln_test_utils::TestScorer::new();
6448 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6449 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6451 // First check we can actually create a long route on this graph.
6452 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6453 let route_params = RouteParameters::from_payment_params_and_value(
6454 feasible_payment_params, 100);
6455 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6456 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6457 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6458 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6460 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6461 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6462 let route_params = RouteParameters::from_payment_params_and_value(
6463 fail_payment_params, 100);
6464 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6465 &Default::default(), &random_seed_bytes)
6467 Err(LightningError { err, .. } ) => {
6468 assert_eq!(err, "Failed to find a path to the given destination");
6470 Ok(_) => panic!("Expected error"),
6475 fn adds_and_limits_cltv_offset() {
6476 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6477 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6479 let scorer = ln_test_utils::TestScorer::new();
6481 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6482 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6483 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6484 let route_params = RouteParameters::from_payment_params_and_value(
6485 payment_params.clone(), 100);
6486 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6487 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6488 assert_eq!(route.paths.len(), 1);
6490 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6492 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6493 let mut route_default = route.clone();
6494 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6495 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6496 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6497 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6498 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6500 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6501 let mut route_limited = route.clone();
6502 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6503 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6504 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6505 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6506 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6510 fn adds_plausible_cltv_offset() {
6511 let (secp_ctx, network, _, _, logger) = build_graph();
6512 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6513 let network_graph = network.read_only();
6514 let network_nodes = network_graph.nodes();
6515 let network_channels = network_graph.channels();
6516 let scorer = ln_test_utils::TestScorer::new();
6517 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6518 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6519 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6521 let route_params = RouteParameters::from_payment_params_and_value(
6522 payment_params.clone(), 100);
6523 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6524 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6525 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6527 let mut path_plausibility = vec![];
6529 for p in route.paths {
6530 // 1. Select random observation point
6531 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6532 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6534 prng.process_in_place(&mut random_bytes);
6535 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6536 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6538 // 2. Calculate what CLTV expiry delta we would observe there
6539 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6541 // 3. Starting from the observation point, find candidate paths
6542 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6543 candidates.push_back((observation_point, vec![]));
6545 let mut found_plausible_candidate = false;
6547 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6548 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6549 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6550 found_plausible_candidate = true;
6551 break 'candidate_loop;
6555 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6556 for channel_id in &cur_node.channels {
6557 if let Some(channel_info) = network_channels.get(&channel_id) {
6558 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6559 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6560 if cur_path_cltv_deltas.iter().sum::<u32>()
6561 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6562 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6563 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6564 candidates.push_back((*next_id, new_path_cltv_deltas));
6572 path_plausibility.push(found_plausible_candidate);
6574 assert!(path_plausibility.iter().all(|x| *x));
6578 fn builds_correct_path_from_hops() {
6579 let (secp_ctx, network, _, _, logger) = build_graph();
6580 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6581 let network_graph = network.read_only();
6583 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6584 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6586 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6587 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6588 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6589 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6590 Arc::clone(&logger), &random_seed_bytes).unwrap();
6591 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6592 assert_eq!(hops.len(), route.paths[0].hops.len());
6593 for (idx, hop_pubkey) in hops.iter().enumerate() {
6594 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6599 fn avoids_saturating_channels() {
6600 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6601 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6602 let decay_params = ProbabilisticScoringDecayParameters::default();
6603 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6605 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6606 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6607 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6608 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6609 short_channel_id: 4,
6612 cltv_expiry_delta: (4 << 4) | 1,
6613 htlc_minimum_msat: 0,
6614 htlc_maximum_msat: 250_000_000,
6616 fee_proportional_millionths: 0,
6617 excess_data: Vec::new()
6619 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6620 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6621 short_channel_id: 13,
6624 cltv_expiry_delta: (13 << 4) | 1,
6625 htlc_minimum_msat: 0,
6626 htlc_maximum_msat: 250_000_000,
6628 fee_proportional_millionths: 0,
6629 excess_data: Vec::new()
6632 let config = UserConfig::default();
6633 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6634 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6636 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6637 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6638 // 100,000 sats is less than the available liquidity on each channel, set above.
6639 let route_params = RouteParameters::from_payment_params_and_value(
6640 payment_params, 100_000_000);
6641 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6642 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6643 assert_eq!(route.paths.len(), 2);
6644 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6645 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6648 #[cfg(not(feature = "no-std"))]
6649 pub(super) fn random_init_seed() -> u64 {
6650 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6651 use core::hash::{BuildHasher, Hasher};
6652 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6653 println!("Using seed of {}", seed);
6658 #[cfg(not(feature = "no-std"))]
6659 fn generate_routes() {
6660 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6662 let logger = ln_test_utils::TestLogger::new();
6663 let graph = match super::bench_utils::read_network_graph(&logger) {
6671 let params = ProbabilisticScoringFeeParameters::default();
6672 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6673 let features = super::Bolt11InvoiceFeatures::empty();
6675 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6679 #[cfg(not(feature = "no-std"))]
6680 fn generate_routes_mpp() {
6681 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6683 let logger = ln_test_utils::TestLogger::new();
6684 let graph = match super::bench_utils::read_network_graph(&logger) {
6692 let params = ProbabilisticScoringFeeParameters::default();
6693 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6694 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6696 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6700 #[cfg(not(feature = "no-std"))]
6701 fn generate_large_mpp_routes() {
6702 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6704 let logger = ln_test_utils::TestLogger::new();
6705 let graph = match super::bench_utils::read_network_graph(&logger) {
6713 let params = ProbabilisticScoringFeeParameters::default();
6714 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6715 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6717 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6721 fn honors_manual_penalties() {
6722 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6723 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6725 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6726 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6728 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6729 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6731 // First check set manual penalties are returned by the scorer.
6732 let usage = ChannelUsage {
6734 inflight_htlc_msat: 0,
6735 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6737 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6738 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6739 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6741 // Then check we can get a normal route
6742 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6743 let route_params = RouteParameters::from_payment_params_and_value(
6744 payment_params, 100);
6745 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6746 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6747 assert!(route.is_ok());
6749 // Then check that we can't get a route if we ban an intermediate node.
6750 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6751 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6752 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6753 assert!(route.is_err());
6755 // Finally make sure we can route again, when we remove the ban.
6756 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6757 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6758 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6759 assert!(route.is_ok());
6763 fn abide_by_route_hint_max_htlc() {
6764 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6765 // params in the final route.
6766 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6767 let netgraph = network_graph.read_only();
6768 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6769 let scorer = ln_test_utils::TestScorer::new();
6770 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6771 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6772 let config = UserConfig::default();
6774 let max_htlc_msat = 50_000;
6775 let route_hint_1 = RouteHint(vec![RouteHintHop {
6776 src_node_id: nodes[2],
6777 short_channel_id: 42,
6780 proportional_millionths: 0,
6782 cltv_expiry_delta: 10,
6783 htlc_minimum_msat: None,
6784 htlc_maximum_msat: Some(max_htlc_msat),
6786 let dest_node_id = ln_test_utils::pubkey(42);
6787 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6788 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6789 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6792 // Make sure we'll error if our route hints don't have enough liquidity according to their
6793 // htlc_maximum_msat.
6794 let mut route_params = RouteParameters::from_payment_params_and_value(
6795 payment_params, max_htlc_msat + 1);
6796 route_params.max_total_routing_fee_msat = None;
6797 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6798 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6801 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6802 } else { panic!(); }
6804 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6805 let mut route_hint_2 = route_hint_1.clone();
6806 route_hint_2.0[0].short_channel_id = 43;
6807 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6808 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6809 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6811 let mut route_params = RouteParameters::from_payment_params_and_value(
6812 payment_params, max_htlc_msat + 1);
6813 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
6814 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6815 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6816 assert_eq!(route.paths.len(), 2);
6817 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6818 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6822 fn direct_channel_to_hints_with_max_htlc() {
6823 // Check that if we have a first hop channel peer that's connected to multiple provided route
6824 // hints, that we properly split the payment between the route hints if needed.
6825 let logger = Arc::new(ln_test_utils::TestLogger::new());
6826 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6827 let scorer = ln_test_utils::TestScorer::new();
6828 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6829 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6830 let config = UserConfig::default();
6832 let our_node_id = ln_test_utils::pubkey(42);
6833 let intermed_node_id = ln_test_utils::pubkey(43);
6834 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6836 let amt_msat = 900_000;
6837 let max_htlc_msat = 500_000;
6838 let route_hint_1 = RouteHint(vec![RouteHintHop {
6839 src_node_id: intermed_node_id,
6840 short_channel_id: 44,
6843 proportional_millionths: 0,
6845 cltv_expiry_delta: 10,
6846 htlc_minimum_msat: None,
6847 htlc_maximum_msat: Some(max_htlc_msat),
6849 src_node_id: intermed_node_id,
6850 short_channel_id: 45,
6853 proportional_millionths: 0,
6855 cltv_expiry_delta: 10,
6856 htlc_minimum_msat: None,
6857 // Check that later route hint max htlcs don't override earlier ones
6858 htlc_maximum_msat: Some(max_htlc_msat - 50),
6860 let mut route_hint_2 = route_hint_1.clone();
6861 route_hint_2.0[0].short_channel_id = 46;
6862 route_hint_2.0[1].short_channel_id = 47;
6863 let dest_node_id = ln_test_utils::pubkey(44);
6864 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6865 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6866 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6869 let route_params = RouteParameters::from_payment_params_and_value(
6870 payment_params, amt_msat);
6871 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6872 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6873 &Default::default(), &random_seed_bytes).unwrap();
6874 assert_eq!(route.paths.len(), 2);
6875 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6876 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6877 assert_eq!(route.get_total_amount(), amt_msat);
6879 // Re-run but with two first hop channels connected to the same route hint peers that must be
6881 let first_hops = vec![
6882 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6883 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6885 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6886 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6887 &Default::default(), &random_seed_bytes).unwrap();
6888 assert_eq!(route.paths.len(), 2);
6889 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6890 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6891 assert_eq!(route.get_total_amount(), amt_msat);
6893 // Make sure this works for blinded route hints.
6894 let blinded_path = BlindedPath {
6895 introduction_node_id: intermed_node_id,
6896 blinding_point: ln_test_utils::pubkey(42),
6898 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6899 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6902 let blinded_payinfo = BlindedPayInfo {
6904 fee_proportional_millionths: 0,
6905 htlc_minimum_msat: 1,
6906 htlc_maximum_msat: max_htlc_msat,
6907 cltv_expiry_delta: 10,
6908 features: BlindedHopFeatures::empty(),
6910 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
6911 let payment_params = PaymentParameters::blinded(vec![
6912 (blinded_payinfo.clone(), blinded_path.clone()),
6913 (blinded_payinfo.clone(), blinded_path.clone())])
6914 .with_bolt12_features(bolt12_features).unwrap();
6915 let route_params = RouteParameters::from_payment_params_and_value(
6916 payment_params, amt_msat);
6917 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6918 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6919 &Default::default(), &random_seed_bytes).unwrap();
6920 assert_eq!(route.paths.len(), 2);
6921 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6922 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6923 assert_eq!(route.get_total_amount(), amt_msat);
6927 fn blinded_route_ser() {
6928 let blinded_path_1 = BlindedPath {
6929 introduction_node_id: ln_test_utils::pubkey(42),
6930 blinding_point: ln_test_utils::pubkey(43),
6932 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6933 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6936 let blinded_path_2 = BlindedPath {
6937 introduction_node_id: ln_test_utils::pubkey(46),
6938 blinding_point: ln_test_utils::pubkey(47),
6940 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6941 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6944 // (De)serialize a Route with 1 blinded path out of two total paths.
6945 let mut route = Route { paths: vec![Path {
6946 hops: vec![RouteHop {
6947 pubkey: ln_test_utils::pubkey(50),
6948 node_features: NodeFeatures::empty(),
6949 short_channel_id: 42,
6950 channel_features: ChannelFeatures::empty(),
6952 cltv_expiry_delta: 0,
6953 maybe_announced_channel: true,
6955 blinded_tail: Some(BlindedTail {
6956 hops: blinded_path_1.blinded_hops,
6957 blinding_point: blinded_path_1.blinding_point,
6958 excess_final_cltv_expiry_delta: 40,
6959 final_value_msat: 100,
6961 hops: vec![RouteHop {
6962 pubkey: ln_test_utils::pubkey(51),
6963 node_features: NodeFeatures::empty(),
6964 short_channel_id: 43,
6965 channel_features: ChannelFeatures::empty(),
6967 cltv_expiry_delta: 0,
6968 maybe_announced_channel: true,
6969 }], blinded_tail: None }],
6972 let encoded_route = route.encode();
6973 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6974 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6975 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6977 // (De)serialize a Route with two paths, each containing a blinded tail.
6978 route.paths[1].blinded_tail = Some(BlindedTail {
6979 hops: blinded_path_2.blinded_hops,
6980 blinding_point: blinded_path_2.blinding_point,
6981 excess_final_cltv_expiry_delta: 41,
6982 final_value_msat: 101,
6984 let encoded_route = route.encode();
6985 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6986 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6987 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6991 fn blinded_path_inflight_processing() {
6992 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6993 // account for the blinded tail's final amount_msat.
6994 let mut inflight_htlcs = InFlightHtlcs::new();
6995 let blinded_path = BlindedPath {
6996 introduction_node_id: ln_test_utils::pubkey(43),
6997 blinding_point: ln_test_utils::pubkey(48),
6998 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7001 hops: vec![RouteHop {
7002 pubkey: ln_test_utils::pubkey(42),
7003 node_features: NodeFeatures::empty(),
7004 short_channel_id: 42,
7005 channel_features: ChannelFeatures::empty(),
7007 cltv_expiry_delta: 0,
7008 maybe_announced_channel: false,
7011 pubkey: blinded_path.introduction_node_id,
7012 node_features: NodeFeatures::empty(),
7013 short_channel_id: 43,
7014 channel_features: ChannelFeatures::empty(),
7016 cltv_expiry_delta: 0,
7017 maybe_announced_channel: false,
7019 blinded_tail: Some(BlindedTail {
7020 hops: blinded_path.blinded_hops,
7021 blinding_point: blinded_path.blinding_point,
7022 excess_final_cltv_expiry_delta: 0,
7023 final_value_msat: 200,
7026 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7027 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7028 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7032 fn blinded_path_cltv_shadow_offset() {
7033 // Make sure we add a shadow offset when sending to blinded paths.
7034 let blinded_path = BlindedPath {
7035 introduction_node_id: ln_test_utils::pubkey(43),
7036 blinding_point: ln_test_utils::pubkey(44),
7038 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7039 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7042 let mut route = Route { paths: vec![Path {
7043 hops: vec![RouteHop {
7044 pubkey: ln_test_utils::pubkey(42),
7045 node_features: NodeFeatures::empty(),
7046 short_channel_id: 42,
7047 channel_features: ChannelFeatures::empty(),
7049 cltv_expiry_delta: 0,
7050 maybe_announced_channel: false,
7053 pubkey: blinded_path.introduction_node_id,
7054 node_features: NodeFeatures::empty(),
7055 short_channel_id: 43,
7056 channel_features: ChannelFeatures::empty(),
7058 cltv_expiry_delta: 0,
7059 maybe_announced_channel: false,
7062 blinded_tail: Some(BlindedTail {
7063 hops: blinded_path.blinded_hops,
7064 blinding_point: blinded_path.blinding_point,
7065 excess_final_cltv_expiry_delta: 0,
7066 final_value_msat: 200,
7068 }], route_params: None};
7070 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7071 let (_, network_graph, _, _, _) = build_line_graph();
7072 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7073 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7074 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7078 fn simple_blinded_route_hints() {
7079 do_simple_blinded_route_hints(1);
7080 do_simple_blinded_route_hints(2);
7081 do_simple_blinded_route_hints(3);
7084 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7085 // Check that we can generate a route to a blinded path with the expected hops.
7086 let (secp_ctx, network, _, _, logger) = build_graph();
7087 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7088 let network_graph = network.read_only();
7090 let scorer = ln_test_utils::TestScorer::new();
7091 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7092 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7094 let mut blinded_path = BlindedPath {
7095 introduction_node_id: nodes[2],
7096 blinding_point: ln_test_utils::pubkey(42),
7097 blinded_hops: Vec::with_capacity(num_blinded_hops),
7099 for i in 0..num_blinded_hops {
7100 blinded_path.blinded_hops.push(
7101 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7104 let blinded_payinfo = BlindedPayInfo {
7106 fee_proportional_millionths: 500,
7107 htlc_minimum_msat: 1000,
7108 htlc_maximum_msat: 100_000_000,
7109 cltv_expiry_delta: 15,
7110 features: BlindedHopFeatures::empty(),
7113 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7114 let route_params = RouteParameters::from_payment_params_and_value(
7115 payment_params, 1001);
7116 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7117 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7118 assert_eq!(route.paths.len(), 1);
7119 assert_eq!(route.paths[0].hops.len(), 2);
7121 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7122 assert_eq!(tail.hops, blinded_path.blinded_hops);
7123 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7124 assert_eq!(tail.final_value_msat, 1001);
7126 let final_hop = route.paths[0].hops.last().unwrap();
7127 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7128 if tail.hops.len() > 1 {
7129 assert_eq!(final_hop.fee_msat,
7130 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7131 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7133 assert_eq!(final_hop.fee_msat, 0);
7134 assert_eq!(final_hop.cltv_expiry_delta, 0);
7139 fn blinded_path_routing_errors() {
7140 // Check that we can generate a route to a blinded path with the expected hops.
7141 let (secp_ctx, network, _, _, logger) = build_graph();
7142 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7143 let network_graph = network.read_only();
7145 let scorer = ln_test_utils::TestScorer::new();
7146 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7147 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7149 let mut invalid_blinded_path = BlindedPath {
7150 introduction_node_id: nodes[2],
7151 blinding_point: ln_test_utils::pubkey(42),
7153 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7156 let blinded_payinfo = BlindedPayInfo {
7158 fee_proportional_millionths: 500,
7159 htlc_minimum_msat: 1000,
7160 htlc_maximum_msat: 100_000_000,
7161 cltv_expiry_delta: 15,
7162 features: BlindedHopFeatures::empty(),
7165 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7166 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7167 let payment_params = PaymentParameters::blinded(vec![
7168 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7169 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7170 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7171 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7172 &scorer, &Default::default(), &random_seed_bytes)
7174 Err(LightningError { err, .. }) => {
7175 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7177 _ => panic!("Expected error")
7180 invalid_blinded_path.introduction_node_id = our_id;
7181 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7182 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7183 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7184 &Default::default(), &random_seed_bytes)
7186 Err(LightningError { err, .. }) => {
7187 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7189 _ => panic!("Expected error")
7192 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7193 invalid_blinded_path.blinded_hops.clear();
7194 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7195 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7196 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7197 &Default::default(), &random_seed_bytes)
7199 Err(LightningError { err, .. }) => {
7200 assert_eq!(err, "0-hop blinded path provided");
7202 _ => panic!("Expected error")
7207 fn matching_intro_node_paths_provided() {
7208 // Check that if multiple blinded paths with the same intro node are provided in payment
7209 // parameters, we'll return the correct paths in the resulting MPP route.
7210 let (secp_ctx, network, _, _, logger) = build_graph();
7211 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7212 let network_graph = network.read_only();
7214 let scorer = ln_test_utils::TestScorer::new();
7215 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7216 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7217 let config = UserConfig::default();
7219 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7220 let blinded_path_1 = BlindedPath {
7221 introduction_node_id: nodes[2],
7222 blinding_point: ln_test_utils::pubkey(42),
7224 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7225 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7228 let blinded_payinfo_1 = BlindedPayInfo {
7230 fee_proportional_millionths: 0,
7231 htlc_minimum_msat: 0,
7232 htlc_maximum_msat: 30_000,
7233 cltv_expiry_delta: 0,
7234 features: BlindedHopFeatures::empty(),
7237 let mut blinded_path_2 = blinded_path_1.clone();
7238 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7239 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7240 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7242 let blinded_hints = vec![
7243 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7244 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7246 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7247 .with_bolt12_features(bolt12_features).unwrap();
7249 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7250 route_params.max_total_routing_fee_msat = Some(100_000);
7251 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7252 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7253 assert_eq!(route.paths.len(), 2);
7254 let mut total_amount_paid_msat = 0;
7255 for path in route.paths.into_iter() {
7256 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7257 if let Some(bt) = &path.blinded_tail {
7258 assert_eq!(bt.blinding_point,
7259 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7260 .map(|(_, bp)| bp.blinding_point).unwrap());
7261 } else { panic!(); }
7262 total_amount_paid_msat += path.final_value_msat();
7264 assert_eq!(total_amount_paid_msat, 100_000);
7268 fn direct_to_intro_node() {
7269 // This previously caused a debug panic in the router when asserting
7270 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7271 // direct channels we failed to account for the fee charged for use of the blinded path.
7274 // node0 -1(1)2 - node1
7275 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7276 // doesn't account for the blinded path fee.
7278 let secp_ctx = Secp256k1::new();
7279 let logger = Arc::new(ln_test_utils::TestLogger::new());
7280 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7281 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7282 let scorer = ln_test_utils::TestScorer::new();
7283 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7284 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7286 let amt_msat = 10_000_000;
7287 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7288 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7289 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7290 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7291 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7292 short_channel_id: 1,
7295 cltv_expiry_delta: 42,
7296 htlc_minimum_msat: 1_000,
7297 htlc_maximum_msat: 10_000_000,
7299 fee_proportional_millionths: 0,
7300 excess_data: Vec::new()
7302 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7303 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7304 short_channel_id: 1,
7307 cltv_expiry_delta: 42,
7308 htlc_minimum_msat: 1_000,
7309 htlc_maximum_msat: 10_000_000,
7311 fee_proportional_millionths: 0,
7312 excess_data: Vec::new()
7314 let first_hops = vec![
7315 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7317 let blinded_path = BlindedPath {
7318 introduction_node_id: nodes[1],
7319 blinding_point: ln_test_utils::pubkey(42),
7321 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7322 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7325 let blinded_payinfo = BlindedPayInfo {
7326 fee_base_msat: 1000,
7327 fee_proportional_millionths: 0,
7328 htlc_minimum_msat: 1000,
7329 htlc_maximum_msat: MAX_VALUE_MSAT,
7330 cltv_expiry_delta: 0,
7331 features: BlindedHopFeatures::empty(),
7333 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7335 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7337 let netgraph = network_graph.read_only();
7338 let route_params = RouteParameters::from_payment_params_and_value(
7339 payment_params.clone(), amt_msat);
7340 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7341 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7342 &Default::default(), &random_seed_bytes) {
7343 assert_eq!(err, "Failed to find a path to the given destination");
7344 } else { panic!("Expected error") }
7346 // Sending an exact amount accounting for the blinded path fee works.
7347 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7348 let route_params = RouteParameters::from_payment_params_and_value(
7349 payment_params, amt_minus_blinded_path_fee);
7350 let route = get_route(&nodes[0], &route_params, &netgraph,
7351 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7352 &Default::default(), &random_seed_bytes).unwrap();
7353 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7354 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7358 fn direct_to_matching_intro_nodes() {
7359 // This previously caused us to enter `unreachable` code in the following situation:
7360 // 1. We add a route candidate for intro_node contributing a high amount
7361 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7362 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7363 // amount, and update our route candidate for intro_node for the lower amount
7364 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7365 // lower contribution amount, but fail (this was previously caused by failure to account for
7366 // blinded path fees when adding first_hop<>intro_node candidates)
7367 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7368 // candidate still thinks its path is contributing the original higher amount. This caused us
7369 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7371 let secp_ctx = Secp256k1::new();
7372 let logger = Arc::new(ln_test_utils::TestLogger::new());
7373 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7374 let scorer = ln_test_utils::TestScorer::new();
7375 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7376 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7377 let config = UserConfig::default();
7379 // Values are taken from the fuzz input that uncovered this panic.
7380 let amt_msat = 21_7020_5185_1403_2640;
7381 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7382 let first_hops = vec![
7383 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7384 18446744073709551615)];
7386 let blinded_path = BlindedPath {
7387 introduction_node_id: nodes[1],
7388 blinding_point: ln_test_utils::pubkey(42),
7390 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7391 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7394 let blinded_payinfo = BlindedPayInfo {
7395 fee_base_msat: 5046_2720,
7396 fee_proportional_millionths: 0,
7397 htlc_minimum_msat: 4503_5996_2737_0496,
7398 htlc_maximum_msat: 45_0359_9627_3704_9600,
7399 cltv_expiry_delta: 0,
7400 features: BlindedHopFeatures::empty(),
7402 let mut blinded_hints = vec![
7403 (blinded_payinfo.clone(), blinded_path.clone()),
7404 (blinded_payinfo.clone(), blinded_path.clone()),
7406 blinded_hints[1].0.fee_base_msat = 419_4304;
7407 blinded_hints[1].0.fee_proportional_millionths = 257;
7408 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7409 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7410 blinded_hints[1].0.cltv_expiry_delta = 0;
7412 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7413 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7414 .with_bolt12_features(bolt12_features).unwrap();
7416 let netgraph = network_graph.read_only();
7417 let route_params = RouteParameters::from_payment_params_and_value(
7418 payment_params, amt_msat);
7419 let route = get_route(&nodes[0], &route_params, &netgraph,
7420 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7421 &Default::default(), &random_seed_bytes).unwrap();
7422 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7423 assert_eq!(route.get_total_amount(), amt_msat);
7427 fn we_are_intro_node_candidate_hops() {
7428 // This previously led to a panic in the router because we'd generate a Path with only a
7429 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7430 // where the origin node is the intro node. We now fully disallow considering candidate hops
7431 // where the origin node is the intro node.
7432 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7433 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7434 let scorer = ln_test_utils::TestScorer::new();
7435 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7436 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7437 let config = UserConfig::default();
7439 // Values are taken from the fuzz input that uncovered this panic.
7440 let amt_msat = 21_7020_5185_1423_0019;
7442 let blinded_path = BlindedPath {
7443 introduction_node_id: our_id,
7444 blinding_point: ln_test_utils::pubkey(42),
7446 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7447 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7450 let blinded_payinfo = BlindedPayInfo {
7451 fee_base_msat: 5052_9027,
7452 fee_proportional_millionths: 0,
7453 htlc_minimum_msat: 21_7020_5185_1423_0019,
7454 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7455 cltv_expiry_delta: 0,
7456 features: BlindedHopFeatures::empty(),
7458 let mut blinded_hints = vec![
7459 (blinded_payinfo.clone(), blinded_path.clone()),
7460 (blinded_payinfo.clone(), blinded_path.clone()),
7462 blinded_hints[1].1.introduction_node_id = nodes[6];
7464 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7465 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7466 .with_bolt12_features(bolt12_features.clone()).unwrap();
7468 let netgraph = network_graph.read_only();
7469 let route_params = RouteParameters::from_payment_params_and_value(
7470 payment_params, amt_msat);
7471 if let Err(LightningError { err, .. }) = get_route(
7472 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7474 assert_eq!(err, "Failed to find a path to the given destination");
7479 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7480 // This previously led to a debug panic in the router because we'd find an invalid Path with
7481 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7482 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7483 // the payment, when it was intended to only include the final value of the payment.
7484 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7485 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7486 let scorer = ln_test_utils::TestScorer::new();
7487 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7488 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7489 let config = UserConfig::default();
7491 // Values are taken from the fuzz input that uncovered this panic.
7492 let amt_msat = 21_7020_5185_1423_0019;
7494 let blinded_path = BlindedPath {
7495 introduction_node_id: our_id,
7496 blinding_point: ln_test_utils::pubkey(42),
7498 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7499 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7502 let blinded_payinfo = BlindedPayInfo {
7503 fee_base_msat: 10_4425_1395,
7504 fee_proportional_millionths: 0,
7505 htlc_minimum_msat: 21_7301_9934_9094_0931,
7506 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7507 cltv_expiry_delta: 0,
7508 features: BlindedHopFeatures::empty(),
7510 let mut blinded_hints = vec![
7511 (blinded_payinfo.clone(), blinded_path.clone()),
7512 (blinded_payinfo.clone(), blinded_path.clone()),
7513 (blinded_payinfo.clone(), blinded_path.clone()),
7515 blinded_hints[1].0.fee_base_msat = 5052_9027;
7516 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7517 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7519 blinded_hints[2].1.introduction_node_id = nodes[6];
7521 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7522 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7523 .with_bolt12_features(bolt12_features.clone()).unwrap();
7525 let netgraph = network_graph.read_only();
7526 let route_params = RouteParameters::from_payment_params_and_value(
7527 payment_params, amt_msat);
7528 if let Err(LightningError { err, .. }) = get_route(
7529 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7531 assert_eq!(err, "Failed to find a path to the given destination");
7536 fn min_htlc_overpay_violates_max_htlc() {
7537 do_min_htlc_overpay_violates_max_htlc(true);
7538 do_min_htlc_overpay_violates_max_htlc(false);
7540 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7541 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7542 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7543 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7544 // that the used liquidity for a hop was less than its available liquidity limit.
7545 let secp_ctx = Secp256k1::new();
7546 let logger = Arc::new(ln_test_utils::TestLogger::new());
7547 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7548 let scorer = ln_test_utils::TestScorer::new();
7549 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7550 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7551 let config = UserConfig::default();
7553 // Values are taken from the fuzz input that uncovered this panic.
7554 let amt_msat = 7_4009_8048;
7555 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7556 let first_hop_outbound_capacity = 2_7345_2000;
7557 let first_hops = vec![get_channel_details(
7558 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7559 first_hop_outbound_capacity
7562 let base_fee = 1_6778_3453;
7563 let htlc_min = 2_5165_8240;
7564 let payment_params = if blinded_payee {
7565 let blinded_path = BlindedPath {
7566 introduction_node_id: nodes[0],
7567 blinding_point: ln_test_utils::pubkey(42),
7569 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7570 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7573 let blinded_payinfo = BlindedPayInfo {
7574 fee_base_msat: base_fee,
7575 fee_proportional_millionths: 0,
7576 htlc_minimum_msat: htlc_min,
7577 htlc_maximum_msat: htlc_min * 1000,
7578 cltv_expiry_delta: 0,
7579 features: BlindedHopFeatures::empty(),
7581 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7582 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7583 .with_bolt12_features(bolt12_features.clone()).unwrap()
7585 let route_hint = RouteHint(vec![RouteHintHop {
7586 src_node_id: nodes[0],
7587 short_channel_id: 42,
7589 base_msat: base_fee,
7590 proportional_millionths: 0,
7592 cltv_expiry_delta: 10,
7593 htlc_minimum_msat: Some(htlc_min),
7594 htlc_maximum_msat: None,
7597 PaymentParameters::from_node_id(nodes[1], 42)
7598 .with_route_hints(vec![route_hint]).unwrap()
7599 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7602 let netgraph = network_graph.read_only();
7603 let route_params = RouteParameters::from_payment_params_and_value(
7604 payment_params, amt_msat);
7605 if let Err(LightningError { err, .. }) = get_route(
7606 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7607 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7609 assert_eq!(err, "Failed to find a path to the given destination");
7614 fn previously_used_liquidity_violates_max_htlc() {
7615 do_previously_used_liquidity_violates_max_htlc(true);
7616 do_previously_used_liquidity_violates_max_htlc(false);
7619 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7620 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7621 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7622 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7623 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7624 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7625 let secp_ctx = Secp256k1::new();
7626 let logger = Arc::new(ln_test_utils::TestLogger::new());
7627 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7628 let scorer = ln_test_utils::TestScorer::new();
7629 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7630 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7631 let config = UserConfig::default();
7633 // Values are taken from the fuzz input that uncovered this panic.
7634 let amt_msat = 52_4288;
7635 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7636 let first_hops = vec![get_channel_details(
7637 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7638 ), get_channel_details(
7639 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7642 let base_fees = [0, 425_9840, 0, 0];
7643 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7644 let payment_params = if blinded_payee {
7645 let blinded_path = BlindedPath {
7646 introduction_node_id: nodes[0],
7647 blinding_point: ln_test_utils::pubkey(42),
7649 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7650 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7653 let mut blinded_hints = Vec::new();
7654 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7655 blinded_hints.push((BlindedPayInfo {
7656 fee_base_msat: *base_fee,
7657 fee_proportional_millionths: 0,
7658 htlc_minimum_msat: *htlc_min,
7659 htlc_maximum_msat: htlc_min * 100,
7660 cltv_expiry_delta: 10,
7661 features: BlindedHopFeatures::empty(),
7662 }, blinded_path.clone()));
7664 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7665 PaymentParameters::blinded(blinded_hints.clone())
7666 .with_bolt12_features(bolt12_features.clone()).unwrap()
7668 let mut route_hints = Vec::new();
7669 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7670 route_hints.push(RouteHint(vec![RouteHintHop {
7671 src_node_id: nodes[0],
7672 short_channel_id: 42 + idx as u64,
7674 base_msat: *base_fee,
7675 proportional_millionths: 0,
7677 cltv_expiry_delta: 10,
7678 htlc_minimum_msat: Some(*htlc_min),
7679 htlc_maximum_msat: Some(htlc_min * 100),
7682 PaymentParameters::from_node_id(nodes[1], 42)
7683 .with_route_hints(route_hints).unwrap()
7684 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7687 let netgraph = network_graph.read_only();
7688 let route_params = RouteParameters::from_payment_params_and_value(
7689 payment_params, amt_msat);
7691 let route = get_route(
7692 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7693 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7695 assert_eq!(route.paths.len(), 1);
7696 assert_eq!(route.get_total_amount(), amt_msat);
7700 fn candidate_path_min() {
7701 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7702 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7703 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7704 // would add a connecting first_hop node that did not have enough contribution amount, leading
7705 // to a debug panic upon invalid path construction.
7706 let secp_ctx = Secp256k1::new();
7707 let logger = Arc::new(ln_test_utils::TestLogger::new());
7708 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7709 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7710 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7711 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7712 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7713 let config = UserConfig::default();
7715 // Values are taken from the fuzz input that uncovered this panic.
7716 let amt_msat = 7_4009_8048;
7717 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7718 let first_hops = vec![get_channel_details(
7719 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7722 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7723 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7724 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7725 short_channel_id: 6,
7728 cltv_expiry_delta: (6 << 4) | 0,
7729 htlc_minimum_msat: 0,
7730 htlc_maximum_msat: MAX_VALUE_MSAT,
7732 fee_proportional_millionths: 0,
7733 excess_data: Vec::new()
7735 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
7737 let htlc_min = 2_5165_8240;
7738 let blinded_hints = vec![
7740 fee_base_msat: 1_6778_3453,
7741 fee_proportional_millionths: 0,
7742 htlc_minimum_msat: htlc_min,
7743 htlc_maximum_msat: htlc_min * 100,
7744 cltv_expiry_delta: 10,
7745 features: BlindedHopFeatures::empty(),
7747 introduction_node_id: nodes[0],
7748 blinding_point: ln_test_utils::pubkey(42),
7750 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7751 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7755 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7756 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7757 .with_bolt12_features(bolt12_features.clone()).unwrap();
7758 let route_params = RouteParameters::from_payment_params_and_value(
7759 payment_params, amt_msat);
7760 let netgraph = network_graph.read_only();
7762 if let Err(LightningError { err, .. }) = get_route(
7763 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7764 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7767 assert_eq!(err, "Failed to find a path to the given destination");
7772 fn path_contribution_includes_min_htlc_overpay() {
7773 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
7774 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
7775 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
7776 // selection, both tested here.
7777 let secp_ctx = Secp256k1::new();
7778 let logger = Arc::new(ln_test_utils::TestLogger::new());
7779 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7780 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7781 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7782 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7783 let config = UserConfig::default();
7785 // Values are taken from the fuzz input that uncovered this panic.
7786 let amt_msat = 562_0000;
7787 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7788 let first_hops = vec![
7789 get_channel_details(
7790 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
7794 let htlc_mins = [49_0000, 1125_0000];
7795 let payment_params = {
7796 let blinded_path = BlindedPath {
7797 introduction_node_id: nodes[0],
7798 blinding_point: ln_test_utils::pubkey(42),
7800 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7801 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7804 let mut blinded_hints = Vec::new();
7805 for htlc_min in htlc_mins.iter() {
7806 blinded_hints.push((BlindedPayInfo {
7808 fee_proportional_millionths: 0,
7809 htlc_minimum_msat: *htlc_min,
7810 htlc_maximum_msat: *htlc_min * 100,
7811 cltv_expiry_delta: 10,
7812 features: BlindedHopFeatures::empty(),
7813 }, blinded_path.clone()));
7815 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7816 PaymentParameters::blinded(blinded_hints.clone())
7817 .with_bolt12_features(bolt12_features.clone()).unwrap()
7820 let netgraph = network_graph.read_only();
7821 let route_params = RouteParameters::from_payment_params_and_value(
7822 payment_params, amt_msat);
7823 let route = get_route(
7824 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7825 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7828 assert_eq!(route.paths.len(), 1);
7829 assert_eq!(route.get_total_amount(), amt_msat);
7833 fn first_hop_preferred_over_hint() {
7834 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
7835 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
7836 let secp_ctx = Secp256k1::new();
7837 let logger = Arc::new(ln_test_utils::TestLogger::new());
7838 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7839 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7840 let scorer = ln_test_utils::TestScorer::new();
7841 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7842 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7843 let config = UserConfig::default();
7845 let amt_msat = 1_000_000;
7846 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
7848 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
7849 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7850 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
7851 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7852 short_channel_id: 1,
7855 cltv_expiry_delta: 42,
7856 htlc_minimum_msat: 1_000,
7857 htlc_maximum_msat: 10_000_000,
7859 fee_proportional_millionths: 0,
7860 excess_data: Vec::new()
7862 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7863 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7864 short_channel_id: 1,
7867 cltv_expiry_delta: 42,
7868 htlc_minimum_msat: 1_000,
7869 htlc_maximum_msat: 10_000_000,
7871 fee_proportional_millionths: 0,
7872 excess_data: Vec::new()
7875 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7876 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
7877 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7878 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7879 short_channel_id: 2,
7882 cltv_expiry_delta: 42,
7883 htlc_minimum_msat: 1_000,
7884 htlc_maximum_msat: 10_000_000,
7886 fee_proportional_millionths: 0,
7887 excess_data: Vec::new()
7889 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7890 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7891 short_channel_id: 2,
7894 cltv_expiry_delta: 42,
7895 htlc_minimum_msat: 1_000,
7896 htlc_maximum_msat: 10_000_000,
7898 fee_proportional_millionths: 0,
7899 excess_data: Vec::new()
7902 let dest_node_id = nodes[2];
7904 let route_hint = RouteHint(vec![RouteHintHop {
7905 src_node_id: our_node_id,
7906 short_channel_id: 44,
7909 proportional_millionths: 0,
7911 cltv_expiry_delta: 10,
7912 htlc_minimum_msat: None,
7913 htlc_maximum_msat: Some(5_000_000),
7916 src_node_id: nodes[0],
7917 short_channel_id: 45,
7920 proportional_millionths: 0,
7922 cltv_expiry_delta: 10,
7923 htlc_minimum_msat: None,
7924 htlc_maximum_msat: None,
7927 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7928 .with_route_hints(vec![route_hint]).unwrap()
7929 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
7930 let route_params = RouteParameters::from_payment_params_and_value(
7931 payment_params, amt_msat);
7933 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
7935 let first_hop = get_channel_details(Some(1), nodes[0],
7936 channelmanager::provided_init_features(&config), 999_999);
7937 let first_hops = vec![first_hop];
7939 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
7940 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7941 &Default::default(), &random_seed_bytes).unwrap();
7942 assert_eq!(route.paths.len(), 1);
7943 assert_eq!(route.get_total_amount(), amt_msat);
7944 assert_eq!(route.paths[0].hops.len(), 2);
7945 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
7946 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
7947 assert_eq!(route.get_total_fees(), 123);
7949 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
7950 // for a first hop channel.
7951 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
7952 first_hop.outbound_scid_alias = Some(44);
7953 let first_hops = vec![first_hop];
7955 let route_res = 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);
7958 assert!(route_res.is_err());
7960 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
7961 // use the cheaper second hop of the route hint.
7962 let mut first_hop = get_channel_details(Some(1), nodes[0],
7963 channelmanager::provided_init_features(&config), 10_000_000);
7964 first_hop.outbound_scid_alias = Some(44);
7965 let first_hops = vec![first_hop];
7967 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
7968 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7969 &Default::default(), &random_seed_bytes).unwrap();
7970 assert_eq!(route.paths.len(), 1);
7971 assert_eq!(route.get_total_amount(), amt_msat);
7972 assert_eq!(route.paths[0].hops.len(), 2);
7973 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
7974 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
7975 assert_eq!(route.get_total_fees(), 123);
7979 fn allow_us_being_first_hint() {
7980 // Check that we consider a route hint even if we are the src of the first hop.
7981 let secp_ctx = Secp256k1::new();
7982 let logger = Arc::new(ln_test_utils::TestLogger::new());
7983 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7984 let scorer = ln_test_utils::TestScorer::new();
7985 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7986 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7987 let config = UserConfig::default();
7989 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
7991 let amt_msat = 1_000_000;
7992 let dest_node_id = nodes[1];
7994 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
7995 let first_hops = vec![first_hop];
7997 let route_hint = RouteHint(vec![RouteHintHop {
7998 src_node_id: our_node_id,
7999 short_channel_id: 44,
8002 proportional_millionths: 0,
8004 cltv_expiry_delta: 10,
8005 htlc_minimum_msat: None,
8006 htlc_maximum_msat: None,
8009 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8010 .with_route_hints(vec![route_hint]).unwrap()
8011 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8013 let route_params = RouteParameters::from_payment_params_and_value(
8014 payment_params, amt_msat);
8017 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8018 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8019 &Default::default(), &random_seed_bytes).unwrap();
8021 assert_eq!(route.paths.len(), 1);
8022 assert_eq!(route.get_total_amount(), amt_msat);
8023 assert_eq!(route.get_total_fees(), 0);
8024 assert_eq!(route.paths[0].hops.len(), 1);
8026 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8030 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8031 pub(crate) mod bench_utils {
8035 use bitcoin::hashes::Hash;
8036 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8038 use crate::chain::transaction::OutPoint;
8039 use crate::routing::scoring::ScoreUpdate;
8040 use crate::sign::{EntropySource, KeysManager};
8041 use crate::ln::ChannelId;
8042 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8043 use crate::ln::features::Bolt11InvoiceFeatures;
8044 use crate::routing::gossip::NetworkGraph;
8045 use crate::util::config::UserConfig;
8046 use crate::util::ser::ReadableArgs;
8047 use crate::util::test_utils::TestLogger;
8049 /// Tries to open a network graph file, or panics with a URL to fetch it.
8050 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8051 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8052 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8053 .or_else(|_| { // Fall back to guessing based on the binary location
8054 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8055 let mut path = std::env::current_exe().unwrap();
8056 path.pop(); // lightning-...
8058 path.pop(); // debug
8059 path.pop(); // target
8060 path.push("lightning");
8061 path.push("net_graph-2023-01-18.bin");
8064 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8065 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8066 let mut path = std::env::current_exe().unwrap();
8067 path.pop(); // bench...
8069 path.pop(); // debug
8070 path.pop(); // target
8071 path.pop(); // bench
8072 path.push("lightning");
8073 path.push("net_graph-2023-01-18.bin");
8076 .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");
8077 #[cfg(require_route_graph_test)]
8078 return Ok(res.unwrap());
8079 #[cfg(not(require_route_graph_test))]
8083 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8084 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8087 pub(crate) fn payer_pubkey() -> PublicKey {
8088 let secp_ctx = Secp256k1::new();
8089 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8093 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8095 channel_id: ChannelId::new_zero(),
8096 counterparty: ChannelCounterparty {
8097 features: channelmanager::provided_init_features(&UserConfig::default()),
8099 unspendable_punishment_reserve: 0,
8100 forwarding_info: None,
8101 outbound_htlc_minimum_msat: None,
8102 outbound_htlc_maximum_msat: None,
8104 funding_txo: Some(OutPoint {
8105 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8108 short_channel_id: Some(1),
8109 inbound_scid_alias: None,
8110 outbound_scid_alias: None,
8111 channel_value_satoshis: 10_000_000_000,
8113 balance_msat: 10_000_000_000,
8114 outbound_capacity_msat: 10_000_000_000,
8115 next_outbound_htlc_minimum_msat: 0,
8116 next_outbound_htlc_limit_msat: 10_000_000_000,
8117 inbound_capacity_msat: 0,
8118 unspendable_punishment_reserve: None,
8119 confirmations_required: None,
8120 confirmations: None,
8121 force_close_spend_delay: None,
8123 is_channel_ready: true,
8126 inbound_htlc_minimum_msat: None,
8127 inbound_htlc_maximum_msat: None,
8129 feerate_sat_per_1000_weight: None,
8130 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8134 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8135 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8136 starting_amount: u64, route_count: usize,
8137 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8138 let payer = payer_pubkey();
8139 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8140 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8142 let nodes = graph.read_only().nodes().clone();
8143 let mut route_endpoints = Vec::new();
8144 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8145 // with some routes we picked being un-routable.
8146 for _ in 0..route_count * 3 / 2 {
8148 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8149 let src = PublicKey::from_slice(nodes.unordered_keys()
8150 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8151 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8152 let dst = PublicKey::from_slice(nodes.unordered_keys()
8153 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8154 let params = PaymentParameters::from_node_id(dst, 42)
8155 .with_bolt11_features(features.clone()).unwrap();
8156 let first_hop = first_hop(src);
8157 let amt_msat = starting_amount + seed % 1_000_000;
8158 let route_params = RouteParameters::from_payment_params_and_value(
8159 params.clone(), amt_msat);
8161 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8162 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8164 // ...and seed the scorer with success and failure data...
8165 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8166 let mut score_amt = seed % 1_000_000_000;
8168 // Generate fail/success paths for a wider range of potential amounts with
8169 // MPP enabled to give us a chance to apply penalties for more potential
8171 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8172 let params = PaymentParameters::from_node_id(dst, 42)
8173 .with_bolt11_features(mpp_features).unwrap();
8174 let route_params = RouteParameters::from_payment_params_and_value(
8175 params.clone(), score_amt);
8176 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8177 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8178 &random_seed_bytes);
8179 if let Ok(route) = route_res {
8180 for path in route.paths {
8181 if seed & 0x80 == 0 {
8182 scorer.payment_path_successful(&path);
8184 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8185 scorer.payment_path_failed(&path, short_channel_id);
8187 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8191 // If we couldn't find a path with a higer amount, reduce and try again.
8195 route_endpoints.push((first_hop, params, amt_msat));
8201 // Because we've changed channel scores, it's possible we'll take different routes to the
8202 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8203 // requires a too-high CLTV delta.
8204 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8205 let route_params = RouteParameters::from_payment_params_and_value(
8206 params.clone(), *amt_msat);
8207 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8208 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8210 route_endpoints.truncate(route_count);
8211 assert_eq!(route_endpoints.len(), route_count);
8219 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8220 use crate::sign::{EntropySource, KeysManager};
8221 use crate::ln::channelmanager;
8222 use crate::ln::features::Bolt11InvoiceFeatures;
8223 use crate::routing::gossip::NetworkGraph;
8224 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8225 use crate::util::config::UserConfig;
8226 use crate::util::logger::{Logger, Record};
8227 use crate::util::test_utils::TestLogger;
8229 use criterion::Criterion;
8231 struct DummyLogger {}
8232 impl Logger for DummyLogger {
8233 fn log(&self, _record: Record) {}
8236 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8237 let logger = TestLogger::new();
8238 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8239 let scorer = FixedPenaltyScorer::with_penalty(0);
8240 generate_routes(bench, &network_graph, scorer, &Default::default(),
8241 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8244 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8245 let logger = TestLogger::new();
8246 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8247 let scorer = FixedPenaltyScorer::with_penalty(0);
8248 generate_routes(bench, &network_graph, scorer, &Default::default(),
8249 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8250 "generate_mpp_routes_with_zero_penalty_scorer");
8253 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8254 let logger = TestLogger::new();
8255 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8256 let params = ProbabilisticScoringFeeParameters::default();
8257 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8258 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8259 "generate_routes_with_probabilistic_scorer");
8262 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8263 let logger = TestLogger::new();
8264 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8265 let params = ProbabilisticScoringFeeParameters::default();
8266 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8267 generate_routes(bench, &network_graph, scorer, ¶ms,
8268 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8269 "generate_mpp_routes_with_probabilistic_scorer");
8272 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8273 let logger = TestLogger::new();
8274 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8275 let params = ProbabilisticScoringFeeParameters::default();
8276 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8277 generate_routes(bench, &network_graph, scorer, ¶ms,
8278 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8279 "generate_large_mpp_routes_with_probabilistic_scorer");
8282 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8283 let logger = TestLogger::new();
8284 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8285 let mut params = ProbabilisticScoringFeeParameters::default();
8286 params.linear_success_probability = false;
8287 let scorer = ProbabilisticScorer::new(
8288 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8289 generate_routes(bench, &network_graph, scorer, ¶ms,
8290 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8291 "generate_routes_with_nonlinear_probabilistic_scorer");
8294 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8295 let logger = TestLogger::new();
8296 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8297 let mut params = ProbabilisticScoringFeeParameters::default();
8298 params.linear_success_probability = false;
8299 let scorer = ProbabilisticScorer::new(
8300 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8301 generate_routes(bench, &network_graph, scorer, ¶ms,
8302 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8303 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8306 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8307 let logger = TestLogger::new();
8308 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8309 let mut params = ProbabilisticScoringFeeParameters::default();
8310 params.linear_success_probability = false;
8311 let scorer = ProbabilisticScorer::new(
8312 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8313 generate_routes(bench, &network_graph, scorer, ¶ms,
8314 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8315 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8318 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8319 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8320 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8321 bench_name: &'static str,
8323 let payer = bench_utils::payer_pubkey();
8324 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8325 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8327 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8328 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8330 // ...then benchmark finding paths between the nodes we learned.
8332 bench.bench_function(bench_name, |b| b.iter(|| {
8333 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8334 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8335 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8336 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());