1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
29 use crate::prelude::*;
30 use crate::sync::Mutex;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
51 /// Creates a new router.
52 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
53 let random_seed_bytes = Mutex::new(random_seed_bytes);
54 Self { network_graph, logger, random_seed_bytes, scorer, score_params }
58 impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
65 params: &RouteParameters,
66 first_hops: Option<&[&ChannelDetails]>,
67 inflight_htlcs: InFlightHtlcs
68 ) -> Result<Route, LightningError> {
69 let random_seed_bytes = {
70 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
71 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).to_byte_array();
72 *locked_random_seed_bytes
75 payer, params, &self.network_graph, first_hops, &*self.logger,
76 &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
83 /// A trait defining behavior for routing a payment.
85 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
87 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
88 /// and [`RouteParameters::final_value_msat`], respectively.
90 &self, payer: &PublicKey, route_params: &RouteParameters,
91 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
92 ) -> Result<Route, LightningError>;
94 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
96 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
97 /// and [`RouteParameters::final_value_msat`], respectively.
99 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
101 fn find_route_with_id(
102 &self, payer: &PublicKey, route_params: &RouteParameters,
103 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
104 _payment_hash: PaymentHash, _payment_id: PaymentId
105 ) -> Result<Route, LightningError> {
106 self.find_route(payer, route_params, first_hops, inflight_htlcs)
110 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
112 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
115 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
116 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
118 // Maps a channel's short channel id and its direction to the liquidity used up.
119 inflight_htlcs: &'a InFlightHtlcs,
121 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
122 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
123 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
124 ScorerAccountingForInFlightHtlcs {
131 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
132 type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
133 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
134 let target = match candidate.target() {
135 Some(target) => target,
136 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
138 let short_channel_id = match candidate.short_channel_id() {
139 Some(short_channel_id) => short_channel_id,
140 None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
142 let source = candidate.source();
143 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
144 &source, &target, short_channel_id
146 let usage = ChannelUsage {
147 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
151 self.scorer.channel_penalty_msat(candidate, usage, score_params)
153 self.scorer.channel_penalty_msat(candidate, usage, score_params)
158 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
159 /// in-use channel liquidity.
161 pub struct InFlightHtlcs(
162 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
163 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
164 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
166 HashMap<(u64, bool), u64>
170 /// Constructs an empty `InFlightHtlcs`.
171 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
173 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
174 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
175 if path.hops.is_empty() { return };
177 let mut cumulative_msat = 0;
178 if let Some(tail) = &path.blinded_tail {
179 cumulative_msat += tail.final_value_msat;
182 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
183 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
184 // the router excludes the payer node. In the following lines, the payer's information is
185 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
186 // in our sliding window of two.
187 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
188 .map(|hop| hop.pubkey)
189 .chain(core::iter::once(payer_node_id));
191 // Taking the reversed vector from above, we zip it with just the reversed hops list to
192 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
193 // the total amount sent.
194 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
195 cumulative_msat += next_hop.fee_msat;
197 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
198 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
199 .or_insert(cumulative_msat);
203 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
205 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
207 .entry((channel_scid, source < target))
208 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
209 .or_insert(used_msat);
212 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
214 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
215 self.0.get(&(channel_scid, source < target)).map(|v| *v)
219 impl Writeable for InFlightHtlcs {
220 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
223 impl Readable for InFlightHtlcs {
224 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
225 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
226 Ok(Self(infight_map))
230 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
231 /// that leads to it.
232 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
233 pub struct RouteHop {
234 /// The node_id of the node at this hop.
235 pub pubkey: PublicKey,
236 /// The node_announcement features of the node at this hop. For the last hop, these may be
237 /// amended to match the features present in the invoice this node generated.
238 pub node_features: NodeFeatures,
239 /// The channel that should be used from the previous hop to reach this node.
240 pub short_channel_id: u64,
241 /// The channel_announcement features of the channel that should be used from the previous hop
242 /// to reach this node.
243 pub channel_features: ChannelFeatures,
244 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
245 /// If this is the last hop in [`Path::hops`]:
246 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
247 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
249 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
251 /// The CLTV delta added for this hop.
252 /// If this is the last hop in [`Path::hops`]:
253 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
254 /// * otherwise, this is the CLTV delta expected at the destination
256 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
257 pub cltv_expiry_delta: u32,
258 /// Indicates whether this hop is possibly announced in the public network graph.
260 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
261 /// either know for sure it's announced in the public graph, or if any public channels exist
262 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
263 /// the channel to be unannounced.
265 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
266 pub maybe_announced_channel: bool,
269 impl_writeable_tlv_based!(RouteHop, {
270 (0, pubkey, required),
271 (1, maybe_announced_channel, (default_value, true)),
272 (2, node_features, required),
273 (4, short_channel_id, required),
274 (6, channel_features, required),
275 (8, fee_msat, required),
276 (10, cltv_expiry_delta, required),
279 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
280 /// their [`Bolt12Invoice`].
282 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
283 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
284 pub struct BlindedTail {
285 /// The hops of the [`BlindedPath`] provided by the recipient.
287 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
288 pub hops: Vec<BlindedHop>,
289 /// The blinding point of the [`BlindedPath`] provided by the recipient.
291 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
292 pub blinding_point: PublicKey,
293 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
294 /// inferring the destination. May be 0.
295 pub excess_final_cltv_expiry_delta: u32,
296 /// The total amount paid on this [`Path`], excluding the fees.
297 pub final_value_msat: u64,
300 impl_writeable_tlv_based!(BlindedTail, {
301 (0, hops, required_vec),
302 (2, blinding_point, required),
303 (4, excess_final_cltv_expiry_delta, required),
304 (6, final_value_msat, required),
307 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
308 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
309 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
311 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
312 pub hops: Vec<RouteHop>,
313 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
314 pub blinded_tail: Option<BlindedTail>,
318 /// Gets the fees for a given path, excluding any excess paid to the recipient.
319 pub fn fee_msat(&self) -> u64 {
320 match &self.blinded_tail {
321 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
323 // Do not count last hop of each path since that's the full value of the payment
324 self.hops.split_last().map_or(0,
325 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
330 /// Gets the total amount paid on this [`Path`], excluding the fees.
331 pub fn final_value_msat(&self) -> u64 {
332 match &self.blinded_tail {
333 Some(blinded_tail) => blinded_tail.final_value_msat,
334 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
338 /// Gets the final hop's CLTV expiry delta.
339 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
340 match &self.blinded_tail {
342 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
347 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
348 /// it can take multiple paths. Each path is composed of one or more hops through the network.
349 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
351 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
352 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
354 pub paths: Vec<Path>,
355 /// The `route_params` parameter passed to [`find_route`].
357 /// This is used by `ChannelManager` to track information which may be required for retries.
359 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
360 pub route_params: Option<RouteParameters>,
364 /// Returns the total amount of fees paid on this [`Route`].
366 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
367 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
368 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
370 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
371 pub fn get_total_fees(&self) -> u64 {
372 let overpaid_value_msat = self.route_params.as_ref()
373 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
374 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
377 /// Returns the total amount paid on this [`Route`], excluding the fees.
379 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
380 /// we had to reach the [`htlc_minimum_msat`] limits.
382 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
383 pub fn get_total_amount(&self) -> u64 {
384 self.paths.iter().map(|path| path.final_value_msat()).sum()
388 impl fmt::Display for Route {
389 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
390 log_route!(self).fmt(f)
394 const SERIALIZATION_VERSION: u8 = 1;
395 const MIN_SERIALIZATION_VERSION: u8 = 1;
397 impl Writeable for Route {
398 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
399 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
400 (self.paths.len() as u64).write(writer)?;
401 let mut blinded_tails = Vec::new();
402 for path in self.paths.iter() {
403 (path.hops.len() as u8).write(writer)?;
404 for (idx, hop) in path.hops.iter().enumerate() {
406 if let Some(blinded_tail) = &path.blinded_tail {
407 if blinded_tails.is_empty() {
408 blinded_tails = Vec::with_capacity(path.hops.len());
410 blinded_tails.push(None);
413 blinded_tails.push(Some(blinded_tail));
414 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
417 write_tlv_fields!(writer, {
418 // For compatibility with LDK versions prior to 0.0.117, we take the individual
419 // RouteParameters' fields and reconstruct them on read.
420 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
421 (2, blinded_tails, optional_vec),
422 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
423 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
429 impl Readable for Route {
430 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
431 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
432 let path_count: u64 = Readable::read(reader)?;
433 if path_count == 0 { return Err(DecodeError::InvalidValue); }
434 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
435 let mut min_final_cltv_expiry_delta = u32::max_value();
436 for _ in 0..path_count {
437 let hop_count: u8 = Readable::read(reader)?;
438 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
439 for _ in 0..hop_count {
440 hops.push(Readable::read(reader)?);
442 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
443 min_final_cltv_expiry_delta =
444 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
445 paths.push(Path { hops, blinded_tail: None });
447 _init_and_read_len_prefixed_tlv_fields!(reader, {
448 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
449 (2, blinded_tails, optional_vec),
450 (3, final_value_msat, option),
451 (5, max_total_routing_fee_msat, option)
453 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
454 if blinded_tails.len() != 0 {
455 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
456 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
457 path.blinded_tail = blinded_tail_opt;
461 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
462 let route_params = match (payment_params, final_value_msat) {
463 (Some(payment_params), Some(final_value_msat)) => {
464 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
469 Ok(Route { paths, route_params })
473 /// Parameters needed to find a [`Route`].
475 /// Passed to [`find_route`] and [`build_route_from_hops`].
476 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
477 pub struct RouteParameters {
478 /// The parameters of the failed payment path.
479 pub payment_params: PaymentParameters,
481 /// The amount in msats sent on the failed payment path.
482 pub final_value_msat: u64,
484 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
486 /// This limit also applies to the total fees that may arise while retrying failed payment
489 /// Note that values below a few sats may result in some paths being spuriously ignored.
490 pub max_total_routing_fee_msat: Option<u64>,
493 impl RouteParameters {
494 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
496 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
497 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
498 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
502 impl Writeable for RouteParameters {
503 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
504 write_tlv_fields!(writer, {
505 (0, self.payment_params, required),
506 (1, self.max_total_routing_fee_msat, option),
507 (2, self.final_value_msat, required),
508 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
509 // `RouteParameters` directly. For compatibility, we write it here.
510 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
516 impl Readable for RouteParameters {
517 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
518 _init_and_read_len_prefixed_tlv_fields!(reader, {
519 (0, payment_params, (required: ReadableArgs, 0)),
520 (1, max_total_routing_fee_msat, option),
521 (2, final_value_msat, required),
522 (4, final_cltv_delta, option),
524 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
525 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
526 if final_cltv_expiry_delta == &0 {
527 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
532 final_value_msat: final_value_msat.0.unwrap(),
533 max_total_routing_fee_msat,
538 /// Maximum total CTLV difference we allow for a full payment path.
539 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
541 /// Maximum number of paths we allow an (MPP) payment to have.
542 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
543 // limits, but for now more than 10 paths likely carries too much one-path failure.
544 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
546 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
548 // The median hop CLTV expiry delta currently seen in the network.
549 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
551 // During routing, we only consider paths shorter than our maximum length estimate.
552 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
553 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
554 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
556 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
557 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
558 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
559 // (payment_secret and total_msat) = 93 bytes for the final hop.
560 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
561 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
562 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
564 /// Information used to route a payment.
565 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
566 pub struct PaymentParameters {
567 /// Information about the payee, such as their features and route hints for their channels.
570 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
571 pub expiry_time: Option<u64>,
573 /// The maximum total CLTV delta we accept for the route.
574 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
575 pub max_total_cltv_expiry_delta: u32,
577 /// The maximum number of paths that may be used by (MPP) payments.
578 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
579 pub max_path_count: u8,
581 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
582 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
583 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
584 /// increasing failure probability for those paths.
586 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
587 /// restriction have been found. While paths which meet this criteria will be searched for, it
588 /// is ultimately up to the scorer to select them over other paths.
590 /// A value of 0 will allow payments up to and including a channel's total announced usable
591 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
594 pub max_channel_saturation_power_of_half: u8,
596 /// A list of SCIDs which this payment was previously attempted over and which caused the
597 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
599 pub previously_failed_channels: Vec<u64>,
602 impl Writeable for PaymentParameters {
603 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
604 let mut clear_hints = &vec![];
605 let mut blinded_hints = &vec![];
607 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
608 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
610 write_tlv_fields!(writer, {
611 (0, self.payee.node_id(), option),
612 (1, self.max_total_cltv_expiry_delta, required),
613 (2, self.payee.features(), option),
614 (3, self.max_path_count, required),
615 (4, *clear_hints, required_vec),
616 (5, self.max_channel_saturation_power_of_half, required),
617 (6, self.expiry_time, option),
618 (7, self.previously_failed_channels, required_vec),
619 (8, *blinded_hints, optional_vec),
620 (9, self.payee.final_cltv_expiry_delta(), option),
626 impl ReadableArgs<u32> for PaymentParameters {
627 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
628 _init_and_read_len_prefixed_tlv_fields!(reader, {
629 (0, payee_pubkey, option),
630 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
631 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
632 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
633 (4, clear_route_hints, required_vec),
634 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
635 (6, expiry_time, option),
636 (7, previously_failed_channels, optional_vec),
637 (8, blinded_route_hints, optional_vec),
638 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
640 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
641 let payee = if blinded_route_hints.len() != 0 {
642 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
644 route_hints: blinded_route_hints,
645 features: features.and_then(|f: Features| f.bolt12()),
649 route_hints: clear_route_hints,
650 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
651 features: features.and_then(|f| f.bolt11()),
652 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
656 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
657 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
659 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
661 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
667 impl PaymentParameters {
668 /// Creates a payee with the node id of the given `pubkey`.
670 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
672 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
674 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
676 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
677 max_path_count: DEFAULT_MAX_PATH_COUNT,
678 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
679 previously_failed_channels: Vec::new(),
683 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
685 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
688 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
689 /// whether your router will be allowed to find a multi-part route for this payment. If you
690 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
691 /// [`RecipientOnionFields::secret_only`].
693 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
694 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
695 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
696 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
697 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
700 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
701 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
702 /// [`PaymentParameters::expiry_time`].
703 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
704 Self::blinded(invoice.payment_paths().to_vec())
705 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
706 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
709 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
710 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
712 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
714 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
715 max_path_count: DEFAULT_MAX_PATH_COUNT,
716 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
717 previously_failed_channels: Vec::new(),
721 /// Includes the payee's features. Errors if the parameters were not initialized with
722 /// [`PaymentParameters::from_bolt12_invoice`].
724 /// This is not exported to bindings users since bindings don't support move semantics
725 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
727 Payee::Clear { .. } => Err(()),
728 Payee::Blinded { route_hints, .. } =>
729 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
733 /// Includes the payee's features. Errors if the parameters were initialized with
734 /// [`PaymentParameters::from_bolt12_invoice`].
736 /// This is not exported to bindings users since bindings don't support move semantics
737 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
739 Payee::Blinded { .. } => Err(()),
740 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
742 payee: Payee::Clear {
743 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
749 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
750 /// [`PaymentParameters::from_bolt12_invoice`].
752 /// This is not exported to bindings users since bindings don't support move semantics
753 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
755 Payee::Blinded { .. } => Err(()),
756 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
758 payee: Payee::Clear {
759 route_hints, node_id, features, final_cltv_expiry_delta,
765 /// Includes a payment expiration in seconds relative to the UNIX epoch.
767 /// This is not exported to bindings users since bindings don't support move semantics
768 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
769 Self { expiry_time: Some(expiry_time), ..self }
772 /// Includes a limit for the total CLTV expiry delta which is considered during routing
774 /// This is not exported to bindings users since bindings don't support move semantics
775 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
776 Self { max_total_cltv_expiry_delta, ..self }
779 /// Includes a limit for the maximum number of payment paths that may be used.
781 /// This is not exported to bindings users since bindings don't support move semantics
782 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
783 Self { max_path_count, ..self }
786 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
787 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
789 /// This is not exported to bindings users since bindings don't support move semantics
790 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
791 Self { max_channel_saturation_power_of_half, ..self }
795 /// The recipient of a payment, differing based on whether they've hidden their identity with route
797 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
799 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
800 /// will be included in the final [`Route`].
802 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
804 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
805 /// Features supported by the payee.
807 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
809 features: Option<Bolt12InvoiceFeatures>,
811 /// The recipient included these route hints in their BOLT11 invoice.
813 /// The node id of the payee.
815 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
816 route_hints: Vec<RouteHint>,
817 /// Features supported by the payee.
819 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
820 /// does not contain any features.
822 /// [`for_keysend`]: PaymentParameters::for_keysend
823 features: Option<Bolt11InvoiceFeatures>,
824 /// The minimum CLTV delta at the end of the route. This value must not be zero.
825 final_cltv_expiry_delta: u32,
830 fn node_id(&self) -> Option<PublicKey> {
832 Self::Clear { node_id, .. } => Some(*node_id),
836 fn node_features(&self) -> Option<NodeFeatures> {
838 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
839 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
842 fn supports_basic_mpp(&self) -> bool {
844 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
845 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
848 fn features(&self) -> Option<FeaturesRef> {
850 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
851 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
854 fn final_cltv_expiry_delta(&self) -> Option<u32> {
856 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
860 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
862 Self::Blinded { route_hints, .. } => &route_hints[..],
863 Self::Clear { .. } => &[]
867 fn unblinded_route_hints(&self) -> &[RouteHint] {
869 Self::Blinded { .. } => &[],
870 Self::Clear { route_hints, .. } => &route_hints[..]
875 enum FeaturesRef<'a> {
876 Bolt11(&'a Bolt11InvoiceFeatures),
877 Bolt12(&'a Bolt12InvoiceFeatures),
880 Bolt11(Bolt11InvoiceFeatures),
881 Bolt12(Bolt12InvoiceFeatures),
885 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
887 Self::Bolt12(f) => Some(f),
891 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
893 Self::Bolt11(f) => Some(f),
899 impl<'a> Writeable for FeaturesRef<'a> {
900 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
902 Self::Bolt11(f) => Ok(f.write(w)?),
903 Self::Bolt12(f) => Ok(f.write(w)?),
908 impl ReadableArgs<bool> for Features {
909 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
910 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
911 Ok(Self::Bolt12(Readable::read(reader)?))
915 /// A list of hops along a payment path terminating with a channel to the recipient.
916 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
917 pub struct RouteHint(pub Vec<RouteHintHop>);
919 impl Writeable for RouteHint {
920 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
921 (self.0.len() as u64).write(writer)?;
922 for hop in self.0.iter() {
929 impl Readable for RouteHint {
930 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
931 let hop_count: u64 = Readable::read(reader)?;
932 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
933 for _ in 0..hop_count {
934 hops.push(Readable::read(reader)?);
940 /// A channel descriptor for a hop along a payment path.
942 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
943 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
944 /// fields not supported in BOLT 11 will be stripped.
945 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
946 pub struct RouteHintHop {
947 /// The node_id of the non-target end of the route
948 pub src_node_id: PublicKey,
949 /// The short_channel_id of this channel
950 pub short_channel_id: u64,
951 /// The fees which must be paid to use this channel
952 pub fees: RoutingFees,
953 /// The difference in CLTV values between this node and the next node.
954 pub cltv_expiry_delta: u16,
955 /// The minimum value, in msat, which must be relayed to the next hop.
956 pub htlc_minimum_msat: Option<u64>,
957 /// The maximum value in msat available for routing with a single HTLC.
958 pub htlc_maximum_msat: Option<u64>,
961 impl_writeable_tlv_based!(RouteHintHop, {
962 (0, src_node_id, required),
963 (1, htlc_minimum_msat, option),
964 (2, short_channel_id, required),
965 (3, htlc_maximum_msat, option),
967 (6, cltv_expiry_delta, required),
970 #[derive(Eq, PartialEq)]
971 #[repr(align(64))] // Force the size to 64 bytes
972 struct RouteGraphNode {
975 // The maximum value a yet-to-be-constructed payment path might flow through this node.
976 // This value is upper-bounded by us by:
977 // - how much is needed for a path being constructed
978 // - how much value can channels following this node (up to the destination) can contribute,
979 // considering their capacity and fees
980 value_contribution_msat: u64,
981 total_cltv_delta: u32,
982 /// The number of hops walked up to this node.
983 path_length_to_node: u8,
986 impl cmp::Ord for RouteGraphNode {
987 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
988 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
992 impl cmp::PartialOrd for RouteGraphNode {
993 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
994 Some(self.cmp(other))
998 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
999 // substantially when it is laid out at exactly 64 bytes.
1000 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1001 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1003 /// A wrapper around the various hop representations.
1005 /// Can be used to examine the properties of a hop,
1006 /// potentially to decide whether to include it in a route.
1007 #[derive(Clone, Debug)]
1008 pub enum CandidateRouteHop<'a> {
1009 /// A hop from the payer, where the outbound liquidity is known.
1011 /// Channel details of the first hop
1013 /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1014 /// has been funded and is able to pay), and accessor methods may panic otherwise.
1016 /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1017 details: &'a ChannelDetails,
1018 /// The node id of the payer, which is also the source side of this candidate route hop.
1019 payer_node_id: &'a NodeId,
1021 payer_node_counter: u32,
1023 target_node_counter: u32,
1025 /// A hop found in the [`ReadOnlyNetworkGraph`].
1027 /// Information about the channel, including potentially its capacity and
1028 /// direction-specific information.
1029 info: DirectedChannelInfo<'a>,
1030 /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1032 short_channel_id: u64,
1034 /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1036 /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1037 /// terminate at the payee.
1039 /// Information about the private hop communicated via BOLT 11.
1040 hint: &'a RouteHintHop,
1041 /// Node id of the next hop in BOLT 11 route hint.
1042 target_node_id: &'a NodeId,
1044 source_node_counter: u32,
1046 target_node_counter: u32,
1048 /// A blinded path which starts with an introduction point and ultimately terminates with the
1051 /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1052 /// `None` in this state.
1054 /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1055 /// path, the full path is treated as a single [`CandidateRouteHop`].
1057 /// Information about the blinded path including the fee, HTLC amount limits, and
1058 /// cryptographic material required to build an HTLC through the given path.
1059 hint: &'a (BlindedPayInfo, BlindedPath),
1060 /// Index of the hint in the original list of blinded hints.
1062 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1063 /// a short channel ID for this hop.
1066 source_node_counter: u32,
1068 /// Similar to [`Self::Blinded`], but the path here only has one hop.
1070 /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1071 /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1072 /// payee's identity - it's the introduction point!
1074 /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1075 /// to the hops *between* the introduction node and the destination.
1077 /// This primarily exists to track that we need to included a blinded path at the end of our
1078 /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1080 /// Information about the blinded path including the fee, HTLC amount limits, and
1081 /// cryptographic material required to build an HTLC terminating with the given path.
1083 /// Note that the [`BlindedPayInfo`] is ignored here.
1084 hint: &'a (BlindedPayInfo, BlindedPath),
1085 /// Index of the hint in the original list of blinded hints.
1087 /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1088 /// a short channel ID for this hop.
1091 source_node_counter: u32,
1095 impl<'a> CandidateRouteHop<'a> {
1096 /// Returns the short channel ID for this hop, if one is known.
1098 /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1099 /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1101 /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1102 /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1103 /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1104 /// (which is always true for channels which are funded and ready for use).
1106 /// In other words, this should always return `Some` as long as the candidate hop is not a
1107 /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1109 /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1110 /// define a global namespace.
1112 fn short_channel_id(&self) -> Option<u64> {
1114 CandidateRouteHop::FirstHop { details, .. } => details.get_outbound_payment_scid(),
1115 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1116 CandidateRouteHop::PrivateHop { hint, .. } => Some(hint.short_channel_id),
1117 CandidateRouteHop::Blinded { .. } => None,
1118 CandidateRouteHop::OneHopBlinded { .. } => None,
1122 /// Returns the globally unique short channel ID for this hop, if one is known.
1124 /// This only returns `Some` if the channel is public (either our own, or one we've learned
1125 /// from the public network graph), and thus the short channel ID we have for this channel is
1126 /// globally unique and identifies this channel in a global namespace.
1128 pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1130 CandidateRouteHop::FirstHop { details, .. } => if details.is_public { details.short_channel_id } else { None },
1131 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1132 CandidateRouteHop::PrivateHop { .. } => None,
1133 CandidateRouteHop::Blinded { .. } => None,
1134 CandidateRouteHop::OneHopBlinded { .. } => None,
1138 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1139 fn features(&self) -> ChannelFeatures {
1141 CandidateRouteHop::FirstHop { details, .. } => details.counterparty.features.to_context(),
1142 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1143 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1144 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1145 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1149 /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1150 /// next-hop for an HTLC taking this hop.
1152 /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1153 /// next-hop goes on chain with a payment preimage.
1155 pub fn cltv_expiry_delta(&self) -> u32 {
1157 CandidateRouteHop::FirstHop { .. } => 0,
1158 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1159 CandidateRouteHop::PrivateHop { hint, .. } => hint.cltv_expiry_delta as u32,
1160 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1161 CandidateRouteHop::OneHopBlinded { .. } => 0,
1165 /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1167 pub fn htlc_minimum_msat(&self) -> u64 {
1169 CandidateRouteHop::FirstHop { details, .. } => details.next_outbound_htlc_minimum_msat,
1170 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1171 CandidateRouteHop::PrivateHop { hint, .. } => hint.htlc_minimum_msat.unwrap_or(0),
1172 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1173 CandidateRouteHop::OneHopBlinded { .. } => 0,
1178 fn src_node_counter(&self) -> u32 {
1180 CandidateRouteHop::FirstHop { payer_node_counter, .. } => *payer_node_counter,
1181 CandidateRouteHop::PublicHop { info, .. } => info.source_counter(),
1182 CandidateRouteHop::PrivateHop { source_node_counter, .. } => *source_node_counter,
1183 CandidateRouteHop::Blinded { source_node_counter, .. } => *source_node_counter,
1184 CandidateRouteHop::OneHopBlinded { source_node_counter, .. } => *source_node_counter,
1189 fn target_node_counter(&self) -> Option<u32> {
1191 CandidateRouteHop::FirstHop { target_node_counter, .. } => Some(*target_node_counter),
1192 CandidateRouteHop::PublicHop { info, .. } => Some(info.target_counter()),
1193 CandidateRouteHop::PrivateHop { target_node_counter, .. } => Some(*target_node_counter),
1194 CandidateRouteHop::Blinded { .. } => None,
1195 CandidateRouteHop::OneHopBlinded { .. } => None,
1199 /// Returns the fees that must be paid to route an HTLC over this channel.
1201 pub fn fees(&self) -> RoutingFees {
1203 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1204 base_msat: 0, proportional_millionths: 0,
1206 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1207 CandidateRouteHop::PrivateHop { hint, .. } => hint.fees,
1208 CandidateRouteHop::Blinded { hint, .. } => {
1210 base_msat: hint.0.fee_base_msat,
1211 proportional_millionths: hint.0.fee_proportional_millionths
1214 CandidateRouteHop::OneHopBlinded { .. } =>
1215 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1219 /// Fetch the effective capacity of this hop.
1221 /// Note that this may be somewhat expensive, so calls to this should be limited and results
1223 fn effective_capacity(&self) -> EffectiveCapacity {
1225 CandidateRouteHop::FirstHop { details, .. } => EffectiveCapacity::ExactLiquidity {
1226 liquidity_msat: details.next_outbound_htlc_limit_msat,
1228 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1229 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. } =>
1230 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1231 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. } =>
1232 EffectiveCapacity::Infinite,
1233 CandidateRouteHop::Blinded { hint, .. } =>
1234 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1235 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1239 /// Returns an ID describing the given hop.
1241 /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1243 fn id(&self) -> CandidateHopId {
1245 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1246 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1247 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1250 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1252 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1258 /// Returns the source node id of current hop.
1260 /// Source node id refers to the node forwarding the HTLC through this hop.
1262 /// For [`Self::FirstHop`] we return payer's node id.
1264 pub fn source(&self) -> NodeId {
1266 CandidateRouteHop::FirstHop { payer_node_id, .. } => **payer_node_id,
1267 CandidateRouteHop::PublicHop { info, .. } => *info.source(),
1268 CandidateRouteHop::PrivateHop { hint, .. } => hint.src_node_id.into(),
1269 CandidateRouteHop::Blinded { hint, .. } => hint.1.introduction_node_id.into(),
1270 CandidateRouteHop::OneHopBlinded { hint, .. } => hint.1.introduction_node_id.into(),
1273 /// Returns the target node id of this hop, if known.
1275 /// Target node id refers to the node receiving the HTLC after this hop.
1277 /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1278 /// path is unknown.
1280 /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1281 /// and such a return value would be somewhat nonsensical.
1283 pub fn target(&self) -> Option<NodeId> {
1285 CandidateRouteHop::FirstHop { details, .. } => Some(details.counterparty.node_id.into()),
1286 CandidateRouteHop::PublicHop { info, .. } => Some(*info.target()),
1287 CandidateRouteHop::PrivateHop { target_node_id, .. } => Some(**target_node_id),
1288 CandidateRouteHop::Blinded { .. } => None,
1289 CandidateRouteHop::OneHopBlinded { .. } => None,
1294 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1296 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1298 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1299 /// isn't guaranteed to be unique at all.
1301 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1302 /// difficult-to-use API.
1303 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1304 enum CandidateHopId {
1305 /// Contains (scid, src_node_id < target_node_id)
1307 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1312 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1313 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1315 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1316 EffectiveCapacity::Infinite => u64::max_value(),
1317 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1318 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1319 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1320 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1321 // expected to have been generated from up-to-date capacity information.
1322 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1323 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1324 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1328 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1329 -> bool where I1::Item: PartialEq<I2::Item> {
1331 let a = iter_a.next();
1332 let b = iter_b.next();
1333 if a.is_none() && b.is_none() { return true; }
1334 if a.is_none() || b.is_none() { return false; }
1335 if a.unwrap().ne(&b.unwrap()) { return false; }
1339 /// It's useful to keep track of the hops associated with the fees required to use them,
1340 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1341 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1342 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1345 struct PathBuildingHop<'a> {
1346 candidate: CandidateRouteHop<'a>,
1347 target_node_counter: Option<u32>,
1348 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1349 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1350 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1351 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1352 /// avoid processing them again.
1353 was_processed: bool,
1355 is_first_hop_target: bool,
1356 /// Used to compare channels when choosing the for routing.
1357 /// Includes paying for the use of a hop and the following hops, as well as
1358 /// an estimated cost of reaching this hop.
1359 /// Might get stale when fees are recomputed. Primarily for internal use.
1360 total_fee_msat: u64,
1361 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1362 /// walk and may be invalid thereafter.
1363 path_htlc_minimum_msat: u64,
1364 /// All penalties incurred from this channel on the way to the destination, as calculated using
1365 /// channel scoring.
1366 path_penalty_msat: u64,
1370 /// All the fees paid *after* this channel on the way to the destination
1371 next_hops_fee_msat: u64,
1372 /// Fee paid for the use of the current channel (see candidate.fees()).
1373 /// The value will be actually deducted from the counterparty balance on the previous link.
1374 hop_use_fee_msat: u64,
1376 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1377 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1378 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1379 // value_contribution_msat, which requires tracking it here. See comments below where it is
1380 // used for more info.
1381 value_contribution_msat: u64,
1384 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<Option<PathBuildingHop>>();
1385 const _NODE_MAP_SIZE_EXACTLY_TWO_CACHE_LINES: usize = core::mem::size_of::<Option<PathBuildingHop>>() - 128;
1387 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1388 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1389 let mut debug_struct = f.debug_struct("PathBuildingHop");
1391 .field("source_node_id", &self.candidate.source())
1392 .field("target_node_id", &self.candidate.target())
1393 .field("short_channel_id", &self.candidate.short_channel_id())
1394 .field("total_fee_msat", &self.total_fee_msat)
1395 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1396 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1397 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat.saturating_sub(self.next_hops_fee_msat).saturating_sub(self.hop_use_fee_msat)))
1398 .field("path_penalty_msat", &self.path_penalty_msat)
1399 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1400 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1401 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1402 let debug_struct = debug_struct
1403 .field("value_contribution_msat", &self.value_contribution_msat);
1404 debug_struct.finish()
1408 // Instantiated with a list of hops with correct data in them collected during path finding,
1409 // an instance of this struct should be further modified only via given methods.
1411 struct PaymentPath<'a> {
1412 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1415 impl<'a> PaymentPath<'a> {
1416 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1417 fn get_value_msat(&self) -> u64 {
1418 self.hops.last().unwrap().0.fee_msat
1421 fn get_path_penalty_msat(&self) -> u64 {
1422 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1425 fn get_total_fee_paid_msat(&self) -> u64 {
1426 if self.hops.len() < 1 {
1430 // Can't use next_hops_fee_msat because it gets outdated.
1431 for (i, (hop, _)) in self.hops.iter().enumerate() {
1432 if i != self.hops.len() - 1 {
1433 result += hop.fee_msat;
1439 fn get_cost_msat(&self) -> u64 {
1440 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1443 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1444 // to change fees may result in an inconsistency.
1446 // Sometimes we call this function right after constructing a path which is inconsistent in
1447 // that it the value being transferred has decreased while we were doing path finding, leading
1448 // to the fees being paid not lining up with the actual limits.
1450 // Note that this function is not aware of the available_liquidity limit, and thus does not
1451 // support increasing the value being transferred beyond what was selected during the initial
1454 // Returns the amount that this path contributes to the total payment value, which may be greater
1455 // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1456 fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1457 let mut extra_contribution_msat = 0;
1458 let mut total_fee_paid_msat = 0 as u64;
1459 for i in (0..self.hops.len()).rev() {
1460 let last_hop = i == self.hops.len() - 1;
1462 // For non-last-hop, this value will represent the fees paid on the current hop. It
1463 // will consist of the fees for the use of the next hop, and extra fees to match
1464 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1465 let mut cur_hop_fees_msat = 0;
1467 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1470 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1471 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1472 cur_hop.path_penalty_msat += extra_contribution_msat;
1473 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1474 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1475 // set it too high just to maliciously take more fees by exploiting this
1476 // match htlc_minimum_msat logic.
1477 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1478 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1479 // Note that there is a risk that *previous hops* (those closer to us, as we go
1480 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1482 // This might make us end up with a broken route, although this should be super-rare
1483 // in practice, both because of how healthy channels look like, and how we pick
1484 // channels in add_entry.
1485 // Also, this can't be exploited more heavily than *announce a free path and fail
1487 cur_hop_transferred_amount_msat += extra_fees_msat;
1489 // We remember and return the extra fees on the final hop to allow accounting for
1490 // them in the path's value contribution.
1492 extra_contribution_msat = extra_fees_msat;
1494 total_fee_paid_msat += extra_fees_msat;
1495 cur_hop_fees_msat += extra_fees_msat;
1500 // Final hop is a special case: it usually has just value_msat (by design), but also
1501 // it still could overpay for the htlc_minimum_msat.
1502 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1504 // Propagate updated fees for the use of the channels to one hop back, where they
1505 // will be actually paid (fee_msat). The last hop is handled above separately.
1506 cur_hop.fee_msat = cur_hop_fees_msat;
1509 // Fee for the use of the current hop which will be deducted on the previous hop.
1510 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1511 // this channel is free for us.
1513 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1514 cur_hop.hop_use_fee_msat = new_fee;
1515 total_fee_paid_msat += new_fee;
1517 // It should not be possible because this function is called only to reduce the
1518 // value. In that case, compute_fee was already called with the same fees for
1519 // larger amount and there was no overflow.
1524 value_msat + extra_contribution_msat
1529 /// Calculate the fees required to route the given amount over a channel with the given fees.
1530 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1531 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1532 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1536 /// Calculate the fees required to route the given amount over a channel with the given fees,
1537 /// saturating to [`u64::max_value`].
1538 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1539 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1540 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1541 .saturating_add(channel_fees.base_msat as u64)
1544 /// The default `features` we assume for a node in a route, when no `features` are known about that
1547 /// Default features are:
1548 /// * variable_length_onion_optional
1549 fn default_node_features() -> NodeFeatures {
1550 let mut features = NodeFeatures::empty();
1551 features.set_variable_length_onion_optional();
1555 struct LoggedPayeePubkey(Option<PublicKey>);
1556 impl fmt::Display for LoggedPayeePubkey {
1557 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1560 "payee node id ".fmt(f)?;
1564 "blinded payee".fmt(f)
1570 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1571 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1572 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1574 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1575 "blinded route hint with introduction node id ".fmt(f)?;
1576 hint.1.introduction_node_id.fmt(f)?;
1577 " and blinding point ".fmt(f)?;
1578 hint.1.blinding_point.fmt(f)
1580 CandidateRouteHop::FirstHop { .. } => {
1581 "first hop with SCID ".fmt(f)?;
1582 self.0.short_channel_id().unwrap().fmt(f)
1584 CandidateRouteHop::PrivateHop { .. } => {
1585 "route hint with SCID ".fmt(f)?;
1586 self.0.short_channel_id().unwrap().fmt(f)
1590 self.0.short_channel_id().unwrap().fmt(f)
1597 fn sort_first_hop_channels(
1598 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1599 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1601 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1602 // most like to use.
1604 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1605 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1608 // Second, because simply always sorting in descending order would always use our largest
1609 // available outbound capacity, needlessly fragmenting our available channel capacities,
1610 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1611 // which have enough, but not too much, capacity for the payment.
1613 // Available outbound balances factor in liquidity already reserved for previously found paths.
1614 channels.sort_unstable_by(|chan_a, chan_b| {
1615 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1616 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1617 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1618 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1619 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1620 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1621 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1622 // Sort in descending order
1623 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1625 // Sort in ascending order
1626 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1631 /// Finds a route from us (payer) to the given target node (payee).
1633 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1634 /// in the given [`RouteParameters::payment_params`].
1635 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1637 /// Private routing paths between a public node and the target may be included in the `payee` field
1638 /// of [`RouteParameters::payment_params`].
1640 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1641 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1642 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1644 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1645 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1646 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1650 /// Panics if first_hops contains channels without `short_channel_id`s;
1651 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1653 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1654 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1655 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1656 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1657 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1658 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1659 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1660 ) -> Result<Route, LightningError>
1661 where L::Target: Logger, GL::Target: Logger {
1662 let graph_lock = network_graph.read_only();
1663 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1664 scorer, score_params, random_seed_bytes)?;
1665 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1669 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1670 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1671 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1672 _random_seed_bytes: &[u8; 32]
1673 ) -> Result<Route, LightningError>
1674 where L::Target: Logger {
1676 let payment_params = &route_params.payment_params;
1677 let final_value_msat = route_params.final_value_msat;
1678 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1679 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1680 // so use a dummy id for this in the blinded case.
1681 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1682 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1683 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1684 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1685 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1687 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1688 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1690 if our_node_id == maybe_dummy_payee_node_id {
1691 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1694 if final_value_msat > MAX_VALUE_MSAT {
1695 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1698 if final_value_msat == 0 {
1699 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1702 match &payment_params.payee {
1703 Payee::Clear { route_hints, node_id, .. } => {
1704 for route in route_hints.iter() {
1705 for hop in &route.0 {
1706 if hop.src_node_id == *node_id {
1707 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1712 Payee::Blinded { route_hints, .. } => {
1713 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1714 return Err(LightningError{err: "Cannot generate a route to blinded paths if we are the introduction node to all of them".to_owned(), action: ErrorAction::IgnoreError});
1716 for (_, blinded_path) in route_hints.iter() {
1717 if blinded_path.blinded_hops.len() == 0 {
1718 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1719 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1720 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1721 } else if blinded_path.blinded_hops.len() == 1 &&
1722 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1723 && p.introduction_node_id != blinded_path.introduction_node_id)
1725 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1730 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1731 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1732 return Err(LightningError{err: "Can't find a route where the maximum total CLTV expiry delta is below the final CLTV expiry.".to_owned(), action: ErrorAction::IgnoreError});
1735 // The general routing idea is the following:
1736 // 1. Fill first/last hops communicated by the caller.
1737 // 2. Attempt to construct a path from payer to payee for transferring
1738 // any ~sufficient (described later) value.
1739 // If succeed, remember which channels were used and how much liquidity they have available,
1740 // so that future paths don't rely on the same liquidity.
1741 // 3. Proceed to the next step if:
1742 // - we hit the recommended target value;
1743 // - OR if we could not construct a new path. Any next attempt will fail too.
1744 // Otherwise, repeat step 2.
1745 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1746 // (not recommended value).
1747 // 5. If yes, proceed. If not, fail routing.
1748 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1749 // transferred up to the transfer target value.
1750 // 7. Reduce the value of the last path until we are sending only the target value.
1751 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1752 // them so that we're not sending two HTLCs along the same path.
1754 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1755 // distance from the payee
1757 // We are not a faithful Dijkstra's implementation because we can change values which impact
1758 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1759 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1760 // the value we are currently attempting to send over a path, we simply reduce the value being
1761 // sent along the path for any hops after that channel. This may imply that later fees (which
1762 // we've already tabulated) are lower because a smaller value is passing through the channels
1763 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1764 // channels which were selected earlier (and which may still be used for other paths without a
1765 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1768 // One potentially problematic case for this algorithm would be if there are many
1769 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1770 // graph walking), we may never find a path which is not liquidity-limited and has lower
1771 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1772 // Because we only consider paths with at least 5% of the total value being sent, the damage
1773 // from such a case should be limited, however this could be further reduced in the future by
1774 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1775 // limits for the purposes of fee calculation.
1777 // Alternatively, we could store more detailed path information in the heap (targets, below)
1778 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1779 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1780 // and practically (as we would need to store dynamically-allocated path information in heap
1781 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1782 // results of such an algorithm would likely be biased towards lower-value paths.
1784 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1785 // outside of our current search value, running a path search more times to gather candidate
1786 // paths at different values. While this may be acceptable, further path searches may increase
1787 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1788 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1789 // the same time, remaining generic across different payment values.
1791 let network_channels = network_graph.channels();
1792 let network_nodes = network_graph.nodes();
1794 if payment_params.max_path_count == 0 {
1795 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1798 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1799 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1801 let allow_mpp = if payment_params.max_path_count == 1 {
1803 } else if payment_params.payee.supports_basic_mpp() {
1805 } else if let Some(payee) = payee_node_id_opt {
1806 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1807 |info| info.features.supports_basic_mpp()))
1810 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1812 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1813 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1814 if allow_mpp { "with" } else { "without" },
1815 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1816 max_total_routing_fee_msat);
1818 let private_hop_targets_node_counter_offset = network_graph.max_node_counter() + 2;
1819 let mut private_node_id_to_node_counter = HashMap::new();
1821 let mut private_hop_key_cache = HashMap::with_capacity(
1822 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
1825 // Because we store references to private hop node_ids in `dist`, below, we need them to exist
1826 // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
1827 // we'll need here and simply fetch them when routing.
1828 let payee_node_counter = payee_node_id_opt
1829 .and_then(|payee| network_nodes.get(&payee))
1830 .map(|node| node.node_counter)
1831 .unwrap_or(private_hop_targets_node_counter_offset);
1832 private_node_id_to_node_counter.insert(maybe_dummy_payee_node_id, payee_node_counter);
1833 private_hop_key_cache.insert(maybe_dummy_payee_pk, (NodeId::from_pubkey(&maybe_dummy_payee_pk), payee_node_counter));
1835 for route in payment_params.payee.unblinded_route_hints().iter() {
1836 for hop in route.0.iter() {
1837 let hop_node_id = NodeId::from_pubkey(&hop.src_node_id);
1838 let node_counter = if let Some(node) = network_nodes.get(&hop_node_id) {
1841 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
1842 *private_node_id_to_node_counter.entry(hop_node_id)
1843 .or_insert(next_node_counter)
1845 private_hop_key_cache.insert(hop.src_node_id, (hop_node_id, node_counter));
1850 // Prepare the data we'll use for payee-to-payer search by
1851 // inserting first hops suggested by the caller as targets.
1852 // Our search will then attempt to reach them while traversing from the payee node.
1853 let mut first_hop_targets: HashMap<_, (Vec<&ChannelDetails>, u32)> =
1854 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1855 if let Some(hops) = first_hops {
1857 if chan.get_outbound_payment_scid().is_none() {
1858 panic!("first_hops should be filled in with usable channels, not pending ones");
1860 if chan.counterparty.node_id == *our_node_pubkey {
1861 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1863 let counterparty_node_id = NodeId::from_pubkey(&chan.counterparty.node_id);
1865 .entry(counterparty_node_id)
1866 .or_insert_with(|| {
1867 let node_counter = if let Some(node) = network_nodes.get(&counterparty_node_id) {
1870 let next_node_counter = private_hop_targets_node_counter_offset + private_node_id_to_node_counter.len() as u32;
1871 *private_node_id_to_node_counter.entry(counterparty_node_id)
1872 .or_insert(next_node_counter)
1874 (Vec::new(), node_counter)
1878 if first_hop_targets.is_empty() {
1879 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1883 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1884 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1885 // adding duplicate entries when we find a better path to a given node.
1886 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1888 // Map from node_id to information about the best current path to that node, including feerate
1890 let dist_len = private_hop_targets_node_counter_offset + private_hop_key_cache.len() as u32 + 1;
1891 let mut dist: Vec<Option<PathBuildingHop>> = vec![None; dist_len as usize];
1892 let payer_node_counter = network_nodes
1894 .map(|node| node.node_counter)
1896 private_node_id_to_node_counter.get(&our_node_id).map(|counter| *counter)
1898 .unwrap_or(network_graph.max_node_counter() + 1);
1900 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1901 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1902 // htlc_minimum with extra fees while still finding a cheaper path.
1903 let mut hit_minimum_limit;
1905 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1906 // We start with a path_value of the exact amount we want, and if that generates a route we may
1907 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1908 // amount we want in total across paths, selecting the best subset at the end.
1909 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1910 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1911 let mut path_value_msat = final_value_msat;
1913 // Routing Fragmentation Mitigation heuristic:
1915 // Routing fragmentation across many payment paths increases the overall routing
1916 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1917 // Taking too many smaller paths also increases the chance of payment failure.
1918 // Thus to avoid this effect, we require from our collected links to provide
1919 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1920 // This requirement is currently set to be 1/max_path_count of the payment
1921 // value to ensure we only ever return routes that do not violate this limit.
1922 let minimal_value_contribution_msat: u64 = if allow_mpp {
1923 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1928 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1929 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1930 // drop the requirement by setting this to 0.
1931 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1933 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1934 // determine if the channel can be used by additional MPP paths or to inform path finding
1935 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1936 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1938 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1939 HashMap::with_capacity(network_nodes.len());
1941 // Keeping track of how much value we already collected across other paths. Helps to decide
1942 // when we want to stop looking for new paths.
1943 let mut already_collected_value_msat = 0;
1945 for (_, (channels, _)) in first_hop_targets.iter_mut() {
1946 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1950 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1951 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1953 // Remember how many candidates we ignored to allow for some logging afterwards.
1954 let mut num_ignored_value_contribution: u32 = 0;
1955 let mut num_ignored_path_length_limit: u32 = 0;
1956 let mut num_ignored_cltv_delta_limit: u32 = 0;
1957 let mut num_ignored_previously_failed: u32 = 0;
1958 let mut num_ignored_total_fee_limit: u32 = 0;
1959 let mut num_ignored_avoid_overpayment: u32 = 0;
1960 let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
1962 macro_rules! add_entry {
1963 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
1964 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1965 // since that value has to be transferred over this channel.
1966 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
1967 ( $candidate: expr, $next_hops_fee_msat: expr,
1968 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1969 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1970 // We "return" whether we updated the path at the end, and how much we can route via
1971 // this channel, via this:
1972 let mut hop_contribution_amt_msat = None;
1973 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1974 // practice these cases should be caught earlier:
1975 // - for regular channels at channel announcement (TODO)
1976 // - for first and last hops early in get_route
1977 let src_node_id = $candidate.source();
1978 if Some(src_node_id) != $candidate.target() {
1979 let scid_opt = $candidate.short_channel_id();
1980 let effective_capacity = $candidate.effective_capacity();
1981 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1983 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1984 // It may be misleading because we might later choose to reduce the value transferred
1985 // over these channels, and the channel which was insufficient might become sufficient.
1986 // Worst case: we drop a good channel here because it can't cover the high following
1987 // fees caused by one expensive channel, but then this channel could have been used
1988 // if the amount being transferred over this path is lower.
1989 // We do this for now, but this is a subject for removal.
1990 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1991 let used_liquidity_msat = used_liquidities
1992 .get(&$candidate.id())
1993 .map_or(0, |used_liquidity_msat| {
1994 available_value_contribution_msat = available_value_contribution_msat
1995 .saturating_sub(*used_liquidity_msat);
1996 *used_liquidity_msat
1999 // Verify the liquidity offered by this channel complies to the minimal contribution.
2000 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2001 // Do not consider candidate hops that would exceed the maximum path length.
2002 let path_length_to_node = $next_hops_path_length + 1;
2003 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
2005 // Do not consider candidates that exceed the maximum total cltv expiry limit.
2006 // In order to already account for some of the privacy enhancing random CLTV
2007 // expiry delta offset we add on top later, we subtract a rough estimate
2008 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2009 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2010 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2011 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2012 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2013 .saturating_add($candidate.cltv_expiry_delta());
2014 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2016 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2017 // Includes paying fees for the use of the following channels.
2018 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2019 Some(result) => result,
2020 // Can't overflow due to how the values were computed right above.
2021 None => unreachable!(),
2023 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2024 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2025 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2027 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2028 let may_overpay_to_meet_path_minimum_msat =
2029 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2030 recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2031 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2032 recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2034 let payment_failed_on_this_channel = scid_opt.map_or(false,
2035 |scid| payment_params.previously_failed_channels.contains(&scid));
2037 let (should_log_candidate, first_hop_details) = match $candidate {
2038 CandidateRouteHop::FirstHop { details, .. } => (true, Some(details)),
2039 CandidateRouteHop::PrivateHop { .. } => (true, None),
2040 CandidateRouteHop::Blinded { .. } => (true, None),
2041 CandidateRouteHop::OneHopBlinded { .. } => (true, None),
2045 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2046 // bother considering this channel. If retrying with recommended_value_msat may
2047 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2048 // around again with a higher amount.
2049 if !contributes_sufficient_value {
2050 if should_log_candidate {
2051 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
2053 if let Some(details) = first_hop_details {
2055 "First hop candidate next_outbound_htlc_limit_msat: {}",
2056 details.next_outbound_htlc_limit_msat,
2060 num_ignored_value_contribution += 1;
2061 } else if exceeds_max_path_length {
2062 if should_log_candidate {
2063 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2065 num_ignored_path_length_limit += 1;
2066 } else if exceeds_cltv_delta_limit {
2067 if should_log_candidate {
2068 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2070 if let Some(_) = first_hop_details {
2072 "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2073 hop_total_cltv_delta,
2074 max_total_cltv_expiry_delta,
2078 num_ignored_cltv_delta_limit += 1;
2079 } else if payment_failed_on_this_channel {
2080 if should_log_candidate {
2081 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2083 num_ignored_previously_failed += 1;
2084 } else if may_overpay_to_meet_path_minimum_msat {
2085 if should_log_candidate {
2087 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
2088 LoggedCandidateHop(&$candidate));
2090 if let Some(details) = first_hop_details {
2092 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2093 details.next_outbound_htlc_minimum_msat,
2097 num_ignored_avoid_overpayment += 1;
2098 hit_minimum_limit = true;
2099 } else if over_path_minimum_msat {
2100 // Note that low contribution here (limited by available_liquidity_msat)
2101 // might violate htlc_minimum_msat on the hops which are next along the
2102 // payment path (upstream to the payee). To avoid that, we recompute
2103 // path fees knowing the final path contribution after constructing it.
2104 let curr_min = cmp::max(
2105 $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2107 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2108 .saturating_add(curr_min);
2110 let dist_entry = &mut dist[$candidate.src_node_counter() as usize];
2111 let old_entry = if let Some(hop) = dist_entry {
2114 // If there was previously no known way to access the source node
2115 // (recall it goes payee-to-payer) of short_channel_id, first add a
2116 // semi-dummy record just to compute the fees to reach the source node.
2117 // This will affect our decision on selecting short_channel_id
2118 // as a way to reach the $candidate.target() node.
2119 *dist_entry = Some(PathBuildingHop {
2120 candidate: $candidate.clone(),
2121 target_node_counter: None,
2123 next_hops_fee_msat: u64::max_value(),
2124 hop_use_fee_msat: u64::max_value(),
2125 total_fee_msat: u64::max_value(),
2126 path_htlc_minimum_msat,
2127 path_penalty_msat: u64::max_value(),
2128 was_processed: false,
2129 is_first_hop_target: false,
2130 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2131 value_contribution_msat,
2133 dist_entry.as_mut().unwrap()
2136 #[allow(unused_mut)] // We only use the mut in cfg(test)
2137 let mut should_process = !old_entry.was_processed;
2138 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2140 // In test/fuzzing builds, we do extra checks to make sure the skipping
2141 // of already-seen nodes only happens in cases we expect (see below).
2142 if !should_process { should_process = true; }
2146 let mut hop_use_fee_msat = 0;
2147 let mut total_fee_msat: u64 = $next_hops_fee_msat;
2149 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2150 // will have the same effective-fee
2151 if src_node_id != our_node_id {
2152 // Note that `u64::max_value` means we'll always fail the
2153 // `old_entry.total_fee_msat > total_fee_msat` check below
2154 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2155 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2158 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2159 if total_fee_msat > max_total_routing_fee_msat {
2160 if should_log_candidate {
2161 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2163 if let Some(_) = first_hop_details {
2165 "First hop candidate routing fee: {}. Limit: {}",
2167 max_total_routing_fee_msat,
2171 num_ignored_total_fee_limit += 1;
2173 let channel_usage = ChannelUsage {
2174 amount_msat: amount_to_transfer_over_msat,
2175 inflight_htlc_msat: used_liquidity_msat,
2178 let channel_penalty_msat =
2179 scorer.channel_penalty_msat($candidate,
2182 let path_penalty_msat = $next_hops_path_penalty_msat
2183 .saturating_add(channel_penalty_msat);
2185 // Update the way of reaching $candidate.source()
2186 // with the given short_channel_id (from $candidate.target()),
2187 // if this way is cheaper than the already known
2188 // (considering the cost to "reach" this channel from the route destination,
2189 // the cost of using this channel,
2190 // and the cost of routing to the source node of this channel).
2191 // Also, consider that htlc_minimum_msat_difference, because we might end up
2192 // paying it. Consider the following exploit:
2193 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2194 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2195 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2196 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2198 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2199 // but it may require additional tracking - we don't want to double-count
2200 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2201 // can't use something that may decrease on future hops.
2202 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2203 .saturating_add(old_entry.path_penalty_msat);
2204 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2205 .saturating_add(path_penalty_msat);
2207 if !old_entry.was_processed && new_cost < old_cost {
2208 let new_graph_node = RouteGraphNode {
2209 node_id: src_node_id,
2210 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2211 total_cltv_delta: hop_total_cltv_delta,
2212 value_contribution_msat,
2213 path_length_to_node,
2215 targets.push(new_graph_node);
2216 old_entry.target_node_counter = $candidate.target_node_counter();
2217 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2218 old_entry.hop_use_fee_msat = hop_use_fee_msat;
2219 old_entry.total_fee_msat = total_fee_msat;
2220 old_entry.candidate = $candidate.clone();
2221 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2222 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2223 old_entry.path_penalty_msat = path_penalty_msat;
2224 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2226 old_entry.value_contribution_msat = value_contribution_msat;
2228 hop_contribution_amt_msat = Some(value_contribution_msat);
2229 } else if old_entry.was_processed && new_cost < old_cost {
2230 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2232 // If we're skipping processing a node which was previously
2233 // processed even though we found another path to it with a
2234 // cheaper fee, check that it was because the second path we
2235 // found (which we are processing now) has a lower value
2236 // contribution due to an HTLC minimum limit.
2238 // e.g. take a graph with two paths from node 1 to node 2, one
2239 // through channel A, and one through channel B. Channel A and
2240 // B are both in the to-process heap, with their scores set by
2241 // a higher htlc_minimum than fee.
2242 // Channel A is processed first, and the channels onwards from
2243 // node 1 are added to the to-process heap. Thereafter, we pop
2244 // Channel B off of the heap, note that it has a much more
2245 // restrictive htlc_maximum_msat, and recalculate the fees for
2246 // all of node 1's channels using the new, reduced, amount.
2248 // This would be bogus - we'd be selecting a higher-fee path
2249 // with a lower htlc_maximum_msat instead of the one we'd
2250 // already decided to use.
2251 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2253 value_contribution_msat + path_penalty_msat <
2254 old_entry.value_contribution_msat + old_entry.path_penalty_msat
2261 if should_log_candidate {
2263 "Ignoring {} due to its htlc_minimum_msat limit.",
2264 LoggedCandidateHop(&$candidate));
2266 if let Some(details) = first_hop_details {
2268 "First hop candidate next_outbound_htlc_minimum_msat: {}",
2269 details.next_outbound_htlc_minimum_msat,
2273 num_ignored_htlc_minimum_msat_limit += 1;
2277 hop_contribution_amt_msat
2281 let default_node_features = default_node_features();
2283 // Find ways (channels with destination) to reach a given node and store them
2284 // in the corresponding data structures (routing graph etc).
2285 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2286 // meaning how much will be paid in fees after this node (to the best of our knowledge).
2287 // This data can later be helpful to optimize routing (pay lower fees).
2288 macro_rules! add_entries_to_cheapest_to_target_node {
2289 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2290 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2291 let fee_to_target_msat;
2292 let next_hops_path_htlc_minimum_msat;
2293 let next_hops_path_penalty_msat;
2294 let is_first_hop_target;
2295 let skip_node = if let Some(elem) = &mut dist[$node.node_counter as usize] {
2296 let was_processed = elem.was_processed;
2297 elem.was_processed = true;
2298 fee_to_target_msat = elem.total_fee_msat;
2299 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2300 next_hops_path_penalty_msat = elem.path_penalty_msat;
2301 is_first_hop_target = elem.is_first_hop_target;
2304 // Entries are added to dist in add_entry!() when there is a channel from a node.
2305 // Because there are no channels from payee, it will not have a dist entry at this point.
2306 // If we're processing any other node, it is always be the result of a channel from it.
2307 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2309 fee_to_target_msat = 0;
2310 next_hops_path_htlc_minimum_msat = 0;
2311 next_hops_path_penalty_msat = 0;
2312 is_first_hop_target = false;
2317 if is_first_hop_target {
2318 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get(&$node_id) {
2319 for details in first_channels {
2320 debug_assert_eq!(*peer_node_counter, $node.node_counter);
2321 let candidate = CandidateRouteHop::FirstHop {
2322 details, payer_node_id: &our_node_id, payer_node_counter,
2323 target_node_counter: $node.node_counter,
2325 add_entry!(&candidate, fee_to_target_msat,
2326 $next_hops_value_contribution,
2327 next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2328 $next_hops_cltv_delta, $next_hops_path_length);
2333 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2336 &default_node_features
2339 if !features.requires_unknown_bits() {
2340 for chan_id in $node.channels.iter() {
2341 let chan = network_channels.get(chan_id).unwrap();
2342 if !chan.features.requires_unknown_bits() {
2343 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2344 if first_hops.is_none() || *source != our_node_id {
2345 if directed_channel.direction().enabled {
2346 let candidate = CandidateRouteHop::PublicHop {
2347 info: directed_channel,
2348 short_channel_id: *chan_id,
2350 add_entry!(&candidate,
2352 $next_hops_value_contribution,
2353 next_hops_path_htlc_minimum_msat,
2354 next_hops_path_penalty_msat,
2355 $next_hops_cltv_delta, $next_hops_path_length);
2366 let mut payment_paths = Vec::<PaymentPath>::new();
2368 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2369 'paths_collection: loop {
2370 // For every new path, start from scratch, except for used_liquidities, which
2371 // helps to avoid reusing previously selected paths in future iterations.
2373 for e in dist.iter_mut() {
2376 for (node_id, (chans, peer_node_counter)) in first_hop_targets.iter() {
2377 // In order to avoid looking up whether each node is a first-hop target, we store a
2378 // dummy entry in dist for each first-hop target, allowing us to do this lookup for
2379 // free since we're already looking at the `was_processed` flag.
2381 // Note that all the fields (except `is_first_hop_target`) will be overwritten whenever
2382 // we find a path to the target, so are left as dummies here.
2383 dist[*peer_node_counter as usize] = Some(PathBuildingHop {
2384 candidate: CandidateRouteHop::FirstHop {
2386 payer_node_id: &our_node_id,
2387 target_node_counter: u32::max_value(),
2388 payer_node_counter: u32::max_value(),
2390 target_node_counter: None,
2392 next_hops_fee_msat: u64::max_value(),
2393 hop_use_fee_msat: u64::max_value(),
2394 total_fee_msat: u64::max_value(),
2395 path_htlc_minimum_msat: u64::max_value(),
2396 path_penalty_msat: u64::max_value(),
2397 was_processed: false,
2398 is_first_hop_target: true,
2399 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2400 value_contribution_msat: 0,
2403 hit_minimum_limit = false;
2405 // If first hop is a private channel and the only way to reach the payee, this is the only
2406 // place where it could be added.
2407 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|(first_channels, peer_node_counter)| {
2408 debug_assert_eq!(*peer_node_counter, payee_node_counter);
2409 for details in first_channels {
2410 let candidate = CandidateRouteHop::FirstHop {
2411 details, payer_node_id: &our_node_id, payer_node_counter,
2412 target_node_counter: payee_node_counter,
2414 let added = add_entry!(&candidate, 0, path_value_msat,
2415 0, 0u64, 0, 0).is_some();
2416 log_trace!(logger, "{} direct route to payee via {}",
2417 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2421 // Add the payee as a target, so that the payee-to-payer
2422 // search algorithm knows what to start with.
2423 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2424 // The payee is not in our network graph, so nothing to add here.
2425 // There is still a chance of reaching them via last_hops though,
2426 // so don't yet fail the payment here.
2427 // If not, targets.pop() will not even let us enter the loop in step 2.
2430 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2435 // If a caller provided us with last hops, add them to routing targets. Since this happens
2436 // earlier than general path finding, they will be somewhat prioritized, although currently
2437 // it matters only if the fees are exactly the same.
2438 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2439 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2440 let intro_node_counter_opt =
2441 // Only add the hops in this route to our candidate set if either
2442 // we have a direct channel to the first hop or the first hop is
2443 // in the regular network graph.
2444 network_nodes.get(&intro_node_id).map(|node| node.node_counter)
2446 first_hop_targets.get(&intro_node_id).map(|(_, node_counter)| *node_counter)
2448 if intro_node_counter_opt.is_none() || our_node_id == intro_node_id { continue }
2449 let candidate = if hint.1.blinded_hops.len() == 1 {
2450 CandidateRouteHop::OneHopBlinded {
2453 source_node_counter: intro_node_counter_opt.unwrap(),
2456 CandidateRouteHop::Blinded {
2459 source_node_counter: intro_node_counter_opt.unwrap(),
2462 let mut path_contribution_msat = path_value_msat;
2463 if let Some(hop_used_msat) = add_entry!(&candidate,
2464 0, path_contribution_msat, 0, 0_u64, 0, 0)
2466 path_contribution_msat = hop_used_msat;
2468 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2469 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2471 for details in first_channels {
2472 let first_hop_candidate = CandidateRouteHop::FirstHop {
2473 details, payer_node_id: &our_node_id, payer_node_counter,
2474 target_node_counter: *peer_node_counter,
2476 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2480 let path_min = candidate.htlc_minimum_msat().saturating_add(
2481 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2482 add_entry!(&first_hop_candidate, blinded_path_fee,
2483 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2484 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2488 for route in payment_params.payee.unblinded_route_hints().iter()
2489 .filter(|route| !route.0.is_empty())
2491 let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2492 let first_hop_src_is_reachable =
2493 // Only add the hops in this route to our candidate set if either we are part of
2494 // the first hop, we have a direct channel to the first hop, or the first hop is in
2495 // the regular network graph.
2496 our_node_id == first_hop_src_id ||
2497 first_hop_targets.get(&first_hop_src_id).is_some() ||
2498 network_nodes.get(&first_hop_src_id).is_some();
2499 if first_hop_src_is_reachable {
2500 // We start building the path from reverse, i.e., from payee
2501 // to the first RouteHintHop in the path.
2502 let hop_iter = route.0.iter().rev();
2503 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2504 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2505 let mut hop_used = true;
2506 let mut aggregate_next_hops_fee_msat: u64 = 0;
2507 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2508 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2509 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2510 let mut aggregate_next_hops_path_length: u8 = 0;
2511 let mut aggregate_path_contribution_msat = path_value_msat;
2513 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2514 let (target, private_target_node_counter) = private_hop_key_cache.get(&prev_hop_id).unwrap();
2515 let (_src_id, private_source_node_counter) = private_hop_key_cache.get(&hop.src_node_id).unwrap();
2517 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2518 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2519 log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2520 hop.short_channel_id);
2525 let candidate = network_channels
2526 .get(&hop.short_channel_id)
2527 .and_then(|channel| channel.as_directed_to(&target))
2528 .map(|(info, _)| CandidateRouteHop::PublicHop {
2530 short_channel_id: hop.short_channel_id,
2532 .unwrap_or_else(|| CandidateRouteHop::PrivateHop {
2533 hint: hop, target_node_id: target,
2534 source_node_counter: *private_source_node_counter,
2535 target_node_counter: *private_target_node_counter,
2538 if let Some(hop_used_msat) = add_entry!(&candidate,
2539 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2540 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2541 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2543 aggregate_path_contribution_msat = hop_used_msat;
2545 // If this hop was not used then there is no use checking the preceding
2546 // hops in the RouteHint. We can break by just searching for a direct
2547 // channel between last checked hop and first_hop_targets.
2551 let used_liquidity_msat = used_liquidities
2552 .get(&candidate.id()).copied()
2554 let channel_usage = ChannelUsage {
2555 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2556 inflight_htlc_msat: used_liquidity_msat,
2557 effective_capacity: candidate.effective_capacity(),
2559 let channel_penalty_msat = scorer.channel_penalty_msat(
2560 &candidate, channel_usage, score_params
2562 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2563 .saturating_add(channel_penalty_msat);
2565 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2566 .saturating_add(hop.cltv_expiry_delta as u32);
2568 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2571 // Searching for a direct channel between last checked hop and first_hop_targets
2572 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&target) {
2573 sort_first_hop_channels(first_channels, &used_liquidities,
2574 recommended_value_msat, our_node_pubkey);
2575 for details in first_channels {
2576 let first_hop_candidate = CandidateRouteHop::FirstHop {
2577 details, payer_node_id: &our_node_id, payer_node_counter,
2578 target_node_counter: *peer_node_counter,
2580 add_entry!(&first_hop_candidate,
2581 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2582 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2583 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2591 // In the next values of the iterator, the aggregate fees already reflects
2592 // the sum of value sent from payer (final_value_msat) and routing fees
2593 // for the last node in the RouteHint. We need to just add the fees to
2594 // route through the current node so that the preceding node (next iteration)
2596 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2597 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2598 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2600 // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2601 // this route hint's source node to forward said min over this channel.
2602 aggregate_next_hops_path_htlc_minimum_msat = {
2603 let curr_htlc_min = cmp::max(
2604 candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2606 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2607 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2610 if idx == route.0.len() - 1 {
2611 // The last hop in this iterator is the first hop in
2612 // overall RouteHint.
2613 // If this hop connects to a node with which we have a direct channel,
2614 // ignore the network graph and, if the last hop was added, add our
2615 // direct channel to the candidate set.
2617 // Note that we *must* check if the last hop was added as `add_entry`
2618 // always assumes that the third argument is a node to which we have a
2620 if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2621 sort_first_hop_channels(first_channels, &used_liquidities,
2622 recommended_value_msat, our_node_pubkey);
2623 for details in first_channels {
2624 let first_hop_candidate = CandidateRouteHop::FirstHop {
2625 details, payer_node_id: &our_node_id, payer_node_counter,
2626 target_node_counter: *peer_node_counter,
2628 add_entry!(&first_hop_candidate,
2629 aggregate_next_hops_fee_msat,
2630 aggregate_path_contribution_msat,
2631 aggregate_next_hops_path_htlc_minimum_msat,
2632 aggregate_next_hops_path_penalty_msat,
2633 aggregate_next_hops_cltv_delta,
2634 aggregate_next_hops_path_length);
2642 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2644 // At this point, targets are filled with the data from first and
2645 // last hops communicated by the caller, and the payment receiver.
2646 let mut found_new_path = false;
2649 // If this loop terminates due the exhaustion of targets, two situations are possible:
2650 // - not enough outgoing liquidity:
2651 // 0 < already_collected_value_msat < final_value_msat
2652 // - enough outgoing liquidity:
2653 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2654 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2655 // paths_collection will be stopped because found_new_path==false.
2656 // This is not necessarily a routing failure.
2657 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2659 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2660 // traversing the graph and arrange the path out of what we found.
2661 if node_id == our_node_id {
2662 let mut new_entry = dist[payer_node_counter as usize].take().unwrap();
2663 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2666 let mut features_set = false;
2667 let candidate = &ordered_hops.last().unwrap().0.candidate;
2668 let target = candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2669 let target_node_counter = candidate.target_node_counter();
2670 if let Some((first_channels, _)) = first_hop_targets.get(&target) {
2671 for details in first_channels {
2672 if let CandidateRouteHop::FirstHop { details: last_hop_details, .. }
2673 = ordered_hops.last().unwrap().0.candidate
2675 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2676 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2677 features_set = true;
2684 if let Some(node) = network_nodes.get(&target) {
2685 if let Some(node_info) = node.announcement_info.as_ref() {
2686 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2688 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2691 // We can fill in features for everything except hops which were
2692 // provided via the invoice we're paying. We could guess based on the
2693 // recipient's features but for now we simply avoid guessing at all.
2697 // Means we succesfully traversed from the payer to the payee, now
2698 // save this path for the payment route. Also, update the liquidity
2699 // remaining on the used hops, so that we take them into account
2700 // while looking for more paths.
2701 if target_node_counter.is_none() {
2704 if target_node_counter == Some(payee_node_counter) { break 'path_walk; }
2706 new_entry = match dist[target_node_counter.unwrap() as usize].take() {
2707 Some(payment_hop) => payment_hop,
2708 // We can't arrive at None because, if we ever add an entry to targets,
2709 // we also fill in the entry in dist (see add_entry!).
2710 None => unreachable!(),
2712 // We "propagate" the fees one hop backward (topologically) here,
2713 // so that fees paid for a HTLC forwarding on the current channel are
2714 // associated with the previous channel (where they will be subtracted).
2715 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2716 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2718 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2719 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2721 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2722 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2724 let mut payment_path = PaymentPath {hops: ordered_hops};
2726 // We could have possibly constructed a slightly inconsistent path: since we reduce
2727 // value being transferred along the way, we could have violated htlc_minimum_msat
2728 // on some channels we already passed (assuming dest->source direction). Here, we
2729 // recompute the fees again, so that if that's the case, we match the currently
2730 // underpaid htlc_minimum_msat with fees.
2731 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2732 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2733 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2735 // Since a path allows to transfer as much value as
2736 // the smallest channel it has ("bottleneck"), we should recompute
2737 // the fees so sender HTLC don't overpay fees when traversing
2738 // larger channels than the bottleneck. This may happen because
2739 // when we were selecting those channels we were not aware how much value
2740 // this path will transfer, and the relative fee for them
2741 // might have been computed considering a larger value.
2742 // Remember that we used these channels so that we don't rely
2743 // on the same liquidity in future paths.
2744 let mut prevented_redundant_path_selection = false;
2745 for (hop, _) in payment_path.hops.iter() {
2746 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2747 let used_liquidity_msat = used_liquidities
2748 .entry(hop.candidate.id())
2749 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2750 .or_insert(spent_on_hop_msat);
2751 let hop_capacity = hop.candidate.effective_capacity();
2752 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2753 if *used_liquidity_msat == hop_max_msat {
2754 // If this path used all of this channel's available liquidity, we know
2755 // this path will not be selected again in the next loop iteration.
2756 prevented_redundant_path_selection = true;
2758 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2760 if !prevented_redundant_path_selection {
2761 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2762 // we'll probably end up picking the same path again on the next iteration.
2763 // Decrease the available liquidity of a hop in the middle of the path.
2764 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2765 let exhausted = u64::max_value();
2767 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2768 LoggedCandidateHop(victim_candidate));
2769 if let Some(scid) = victim_candidate.short_channel_id() {
2770 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2771 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2775 // Track the total amount all our collected paths allow to send so that we know
2776 // when to stop looking for more paths
2777 already_collected_value_msat += value_contribution_msat;
2779 payment_paths.push(payment_path);
2780 found_new_path = true;
2781 break 'path_construction;
2784 // If we found a path back to the payee, we shouldn't try to process it again. This is
2785 // the equivalent of the `elem.was_processed` check in
2786 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2787 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2789 // Otherwise, since the current target node is not us,
2790 // keep "unrolling" the payment graph from payee to payer by
2791 // finding a way to reach the current target from the payer side.
2792 match network_nodes.get(&node_id) {
2795 add_entries_to_cheapest_to_target_node!(node, node_id,
2796 value_contribution_msat,
2797 total_cltv_delta, path_length_to_node);
2803 if !found_new_path && channel_saturation_pow_half != 0 {
2804 channel_saturation_pow_half = 0;
2805 continue 'paths_collection;
2807 // If we don't support MPP, no use trying to gather more value ever.
2808 break 'paths_collection;
2812 // Stop either when the recommended value is reached or if no new path was found in this
2814 // In the latter case, making another path finding attempt won't help,
2815 // because we deterministically terminated the search due to low liquidity.
2816 if !found_new_path && channel_saturation_pow_half != 0 {
2817 channel_saturation_pow_half = 0;
2818 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2819 log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2820 path_value_msat = recommended_value_msat;
2821 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2822 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2823 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2824 break 'paths_collection;
2825 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2826 // Further, if this was our first walk of the graph, and we weren't limited by an
2827 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2828 // limited by an htlc_minimum_msat value, find another path with a higher value,
2829 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2830 // still keeping a lower total fee than this path.
2831 if !hit_minimum_limit {
2832 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2833 break 'paths_collection;
2835 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.");
2836 path_value_msat = recommended_value_msat;
2840 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2841 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2842 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2843 num_ignored_total_fee_limit;
2844 if num_ignored_total > 0 {
2846 "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.",
2847 num_ignored_value_contribution, num_ignored_path_length_limit,
2848 num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2849 num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2850 num_ignored_total_fee_limit, num_ignored_total);
2854 if payment_paths.len() == 0 {
2855 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2858 if already_collected_value_msat < final_value_msat {
2859 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2863 let mut selected_route = payment_paths;
2865 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2866 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2868 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2869 // the value they contribute towards the payment amount.
2870 // We sort in descending order as we will remove from the front in `retain`, next.
2871 selected_route.sort_unstable_by(|a, b|
2872 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2873 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2876 // We should make sure that at least 1 path left.
2877 let mut paths_left = selected_route.len();
2878 selected_route.retain(|path| {
2879 if paths_left == 1 {
2882 let path_value_msat = path.get_value_msat();
2883 if path_value_msat <= overpaid_value_msat {
2884 overpaid_value_msat -= path_value_msat;
2890 debug_assert!(selected_route.len() > 0);
2892 if overpaid_value_msat != 0 {
2894 // Now, subtract the remaining overpaid value from the most-expensive path.
2895 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2896 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2897 selected_route.sort_unstable_by(|a, b| {
2898 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2899 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2900 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2902 let expensive_payment_path = selected_route.first_mut().unwrap();
2904 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2905 // can't go negative.
2906 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2907 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2911 // Sort by the path itself and combine redundant paths.
2912 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2913 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2915 selected_route.sort_unstable_by_key(|path| {
2916 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2917 debug_assert!(path.hops.len() <= key.len());
2918 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
2923 for idx in 0..(selected_route.len() - 1) {
2924 if idx + 1 >= selected_route.len() { break; }
2925 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
2926 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
2927 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2928 selected_route[idx].update_value_and_recompute_fees(new_value);
2929 selected_route.remove(idx + 1);
2933 let mut paths = Vec::new();
2934 for payment_path in selected_route {
2935 let mut hops = Vec::with_capacity(payment_path.hops.len());
2936 for (hop, node_features) in payment_path.hops.iter()
2937 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2939 let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
2940 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2941 // If we sourced the hop from the graph we're sure the target node is announced.
2943 } else if let CandidateRouteHop::FirstHop { details, .. } = hop.candidate {
2944 // If this is a first hop we also know if it's announced.
2947 // If we sourced it any other way, we double-check the network graph to see if
2948 // there are announced channels between the endpoints. If so, the hop might be
2949 // referring to any of the announced channels, as its `short_channel_id` might be
2950 // an alias, in which case we don't take any chances here.
2951 network_graph.node(&target).map_or(false, |hop_node|
2952 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2953 .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
2957 hops.push(RouteHop {
2958 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2959 node_features: node_features.clone(),
2960 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2961 channel_features: hop.candidate.features(),
2962 fee_msat: hop.fee_msat,
2963 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2964 maybe_announced_channel,
2967 let mut final_cltv_delta = final_cltv_expiry_delta;
2968 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2969 if let Some(blinded_path) = h.candidate.blinded_path() {
2970 final_cltv_delta = h.candidate.cltv_expiry_delta();
2972 hops: blinded_path.blinded_hops.clone(),
2973 blinding_point: blinded_path.blinding_point,
2974 excess_final_cltv_expiry_delta: 0,
2975 final_value_msat: h.fee_msat,
2979 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2980 // applicable for the previous hop.
2981 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2982 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2985 paths.push(Path { hops, blinded_tail });
2987 // Make sure we would never create a route with more paths than we allow.
2988 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2990 if let Some(node_features) = payment_params.payee.node_features() {
2991 for path in paths.iter_mut() {
2992 path.hops.last_mut().unwrap().node_features = node_features.clone();
2996 let route = Route { paths, route_params: Some(route_params.clone()) };
2998 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2999 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3000 if route.get_total_fees() > max_total_routing_fee_msat {
3001 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3002 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3006 log_info!(logger, "Got route: {}", log_route!(route));
3010 // When an adversarial intermediary node observes a payment, it may be able to infer its
3011 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3012 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3013 // payment path by adding a randomized 'shadow route' offset to the final hop.
3014 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3015 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3017 let network_channels = network_graph.channels();
3018 let network_nodes = network_graph.nodes();
3020 for path in route.paths.iter_mut() {
3021 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3023 // Remember the last three nodes of the random walk and avoid looping back on them.
3024 // Init with the last three nodes from the actual path, if possible.
3025 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3026 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3027 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3029 // Choose the last publicly known node as the starting point for the random walk.
3030 let mut cur_hop: Option<NodeId> = None;
3031 let mut path_nonce = [0u8; 12];
3032 if let Some(starting_hop) = path.hops.iter().rev()
3033 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3034 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3035 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3038 // Init PRNG with the path-dependant nonce, which is static for private paths.
3039 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3040 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3042 // Pick a random path length in [1 .. 3]
3043 prng.process_in_place(&mut random_path_bytes);
3044 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3046 for random_hop in 0..random_walk_length {
3047 // If we don't find a suitable offset in the public network graph, we default to
3048 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3049 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3051 if let Some(cur_node_id) = cur_hop {
3052 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3053 // Randomly choose the next unvisited hop.
3054 prng.process_in_place(&mut random_path_bytes);
3055 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3056 .checked_rem(cur_node.channels.len())
3057 .and_then(|index| cur_node.channels.get(index))
3058 .and_then(|id| network_channels.get(id)) {
3059 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3060 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3061 nodes_to_avoid[random_hop] = *next_id;
3062 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3063 cur_hop = Some(*next_id);
3070 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3071 .checked_add(random_hop_offset)
3072 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3075 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3076 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3077 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3079 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3080 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3081 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3082 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3083 max_path_offset = cmp::max(
3084 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3085 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3086 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3088 // Add 'shadow' CLTV offset to the final hop
3089 if let Some(tail) = path.blinded_tail.as_mut() {
3090 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3091 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3093 if let Some(last_hop) = path.hops.last_mut() {
3094 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3095 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3100 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3101 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3103 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3104 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3105 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3106 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3107 ) -> Result<Route, LightningError>
3108 where L::Target: Logger, GL::Target: Logger {
3109 let graph_lock = network_graph.read_only();
3110 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3111 &graph_lock, logger, random_seed_bytes)?;
3112 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3116 fn build_route_from_hops_internal<L: Deref>(
3117 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3118 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3119 ) -> Result<Route, LightningError> where L::Target: Logger {
3122 our_node_id: NodeId,
3123 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3126 impl ScoreLookUp for HopScorer {
3127 type ScoreParams = ();
3128 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3129 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3131 let mut cur_id = self.our_node_id;
3132 for i in 0..self.hop_ids.len() {
3133 if let Some(next_id) = self.hop_ids[i] {
3134 if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3146 impl<'a> Writeable for HopScorer {
3148 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3153 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3154 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3157 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3158 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3159 for i in 0..hops.len() {
3160 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3163 let scorer = HopScorer { our_node_id, hop_ids };
3165 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3170 use crate::blinded_path::{BlindedHop, BlindedPath};
3171 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3172 use crate::routing::utxo::UtxoResult;
3173 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3174 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3175 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop};
3176 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3177 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3178 use crate::chain::transaction::OutPoint;
3179 use crate::sign::EntropySource;
3180 use crate::ln::ChannelId;
3181 use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3182 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3183 use crate::ln::channelmanager;
3184 use crate::offers::invoice::BlindedPayInfo;
3185 use crate::util::config::UserConfig;
3186 use crate::util::test_utils as ln_test_utils;
3187 use crate::util::chacha20::ChaCha20;
3188 use crate::util::ser::{Readable, Writeable};
3190 use crate::util::ser::Writer;
3192 use bitcoin::hashes::Hash;
3193 use bitcoin::network::constants::Network;
3194 use bitcoin::blockdata::constants::ChainHash;
3195 use bitcoin::blockdata::script::Builder;
3196 use bitcoin::blockdata::opcodes;
3197 use bitcoin::blockdata::transaction::TxOut;
3198 use bitcoin::hashes::hex::FromHex;
3199 use bitcoin::secp256k1::{PublicKey,SecretKey};
3200 use bitcoin::secp256k1::Secp256k1;
3202 use crate::io::Cursor;
3203 use crate::prelude::*;
3204 use crate::sync::Arc;
3206 use core::convert::TryInto;
3208 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3209 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
3210 channelmanager::ChannelDetails {
3211 channel_id: ChannelId::new_zero(),
3212 counterparty: channelmanager::ChannelCounterparty {
3215 unspendable_punishment_reserve: 0,
3216 forwarding_info: None,
3217 outbound_htlc_minimum_msat: None,
3218 outbound_htlc_maximum_msat: None,
3220 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3223 outbound_scid_alias: None,
3224 inbound_scid_alias: None,
3225 channel_value_satoshis: 0,
3228 outbound_capacity_msat,
3229 next_outbound_htlc_limit_msat: outbound_capacity_msat,
3230 next_outbound_htlc_minimum_msat: 0,
3231 inbound_capacity_msat: 42,
3232 unspendable_punishment_reserve: None,
3233 confirmations_required: None,
3234 confirmations: None,
3235 force_close_spend_delay: None,
3236 is_outbound: true, is_channel_ready: true,
3237 is_usable: true, is_public: true,
3238 inbound_htlc_minimum_msat: None,
3239 inbound_htlc_maximum_msat: None,
3241 feerate_sat_per_1000_weight: None,
3242 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
3247 fn simple_route_test() {
3248 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3249 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3250 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3251 let scorer = ln_test_utils::TestScorer::new();
3252 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3253 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3255 // Simple route to 2 via 1
3257 let route_params = RouteParameters::from_payment_params_and_value(
3258 payment_params.clone(), 0);
3259 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3260 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3261 &Default::default(), &random_seed_bytes) {
3262 assert_eq!(err, "Cannot send a payment of 0 msat");
3263 } else { panic!(); }
3265 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3266 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3267 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3268 assert_eq!(route.paths[0].hops.len(), 2);
3270 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3271 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3272 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3273 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3274 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3275 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3277 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3278 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3279 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3280 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3281 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3282 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3286 fn invalid_first_hop_test() {
3287 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3288 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3289 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3290 let scorer = ln_test_utils::TestScorer::new();
3291 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3292 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3294 // Simple route to 2 via 1
3296 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3298 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3299 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3300 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3301 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3302 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3303 } else { panic!(); }
3305 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3306 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3307 assert_eq!(route.paths[0].hops.len(), 2);
3311 fn htlc_minimum_test() {
3312 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3313 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3314 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3315 let scorer = ln_test_utils::TestScorer::new();
3316 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3317 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3319 // Simple route to 2 via 1
3321 // Disable other paths
3322 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3323 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3324 short_channel_id: 12,
3326 flags: 2, // to disable
3327 cltv_expiry_delta: 0,
3328 htlc_minimum_msat: 0,
3329 htlc_maximum_msat: MAX_VALUE_MSAT,
3331 fee_proportional_millionths: 0,
3332 excess_data: Vec::new()
3334 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3335 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3336 short_channel_id: 3,
3338 flags: 2, // to disable
3339 cltv_expiry_delta: 0,
3340 htlc_minimum_msat: 0,
3341 htlc_maximum_msat: MAX_VALUE_MSAT,
3343 fee_proportional_millionths: 0,
3344 excess_data: Vec::new()
3346 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3347 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3348 short_channel_id: 13,
3350 flags: 2, // to disable
3351 cltv_expiry_delta: 0,
3352 htlc_minimum_msat: 0,
3353 htlc_maximum_msat: MAX_VALUE_MSAT,
3355 fee_proportional_millionths: 0,
3356 excess_data: Vec::new()
3358 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3359 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3360 short_channel_id: 6,
3362 flags: 2, // to disable
3363 cltv_expiry_delta: 0,
3364 htlc_minimum_msat: 0,
3365 htlc_maximum_msat: MAX_VALUE_MSAT,
3367 fee_proportional_millionths: 0,
3368 excess_data: Vec::new()
3370 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3371 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3372 short_channel_id: 7,
3374 flags: 2, // to disable
3375 cltv_expiry_delta: 0,
3376 htlc_minimum_msat: 0,
3377 htlc_maximum_msat: MAX_VALUE_MSAT,
3379 fee_proportional_millionths: 0,
3380 excess_data: Vec::new()
3383 // Check against amount_to_transfer_over_msat.
3384 // Set minimal HTLC of 200_000_000 msat.
3385 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3386 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3387 short_channel_id: 2,
3390 cltv_expiry_delta: 0,
3391 htlc_minimum_msat: 200_000_000,
3392 htlc_maximum_msat: MAX_VALUE_MSAT,
3394 fee_proportional_millionths: 0,
3395 excess_data: Vec::new()
3398 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3400 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3401 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3402 short_channel_id: 4,
3405 cltv_expiry_delta: 0,
3406 htlc_minimum_msat: 0,
3407 htlc_maximum_msat: 199_999_999,
3409 fee_proportional_millionths: 0,
3410 excess_data: Vec::new()
3413 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3414 let route_params = RouteParameters::from_payment_params_and_value(
3415 payment_params, 199_999_999);
3416 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3417 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3418 &Default::default(), &random_seed_bytes) {
3419 assert_eq!(err, "Failed to find a path to the given destination");
3420 } else { panic!(); }
3422 // Lift the restriction on the first hop.
3423 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3424 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3425 short_channel_id: 2,
3428 cltv_expiry_delta: 0,
3429 htlc_minimum_msat: 0,
3430 htlc_maximum_msat: MAX_VALUE_MSAT,
3432 fee_proportional_millionths: 0,
3433 excess_data: Vec::new()
3436 // A payment above the minimum should pass
3437 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3438 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3439 assert_eq!(route.paths[0].hops.len(), 2);
3443 fn htlc_minimum_overpay_test() {
3444 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3445 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3446 let config = UserConfig::default();
3447 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3448 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3450 let scorer = ln_test_utils::TestScorer::new();
3451 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3452 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3454 // A route to node#2 via two paths.
3455 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3456 // Thus, they can't send 60 without overpaying.
3457 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3458 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3459 short_channel_id: 2,
3462 cltv_expiry_delta: 0,
3463 htlc_minimum_msat: 35_000,
3464 htlc_maximum_msat: 40_000,
3466 fee_proportional_millionths: 0,
3467 excess_data: Vec::new()
3469 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3470 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3471 short_channel_id: 12,
3474 cltv_expiry_delta: 0,
3475 htlc_minimum_msat: 35_000,
3476 htlc_maximum_msat: 40_000,
3478 fee_proportional_millionths: 0,
3479 excess_data: Vec::new()
3483 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3484 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3485 short_channel_id: 13,
3488 cltv_expiry_delta: 0,
3489 htlc_minimum_msat: 0,
3490 htlc_maximum_msat: MAX_VALUE_MSAT,
3492 fee_proportional_millionths: 0,
3493 excess_data: Vec::new()
3495 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3496 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3497 short_channel_id: 4,
3500 cltv_expiry_delta: 0,
3501 htlc_minimum_msat: 0,
3502 htlc_maximum_msat: MAX_VALUE_MSAT,
3504 fee_proportional_millionths: 0,
3505 excess_data: Vec::new()
3508 // Disable other paths
3509 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3510 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3511 short_channel_id: 1,
3513 flags: 2, // to disable
3514 cltv_expiry_delta: 0,
3515 htlc_minimum_msat: 0,
3516 htlc_maximum_msat: MAX_VALUE_MSAT,
3518 fee_proportional_millionths: 0,
3519 excess_data: Vec::new()
3522 let mut route_params = RouteParameters::from_payment_params_and_value(
3523 payment_params.clone(), 60_000);
3524 route_params.max_total_routing_fee_msat = Some(15_000);
3525 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3526 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3527 // Overpay fees to hit htlc_minimum_msat.
3528 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3529 // TODO: this could be better balanced to overpay 10k and not 15k.
3530 assert_eq!(overpaid_fees, 15_000);
3532 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3533 // while taking even more fee to match htlc_minimum_msat.
3534 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3535 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3536 short_channel_id: 12,
3539 cltv_expiry_delta: 0,
3540 htlc_minimum_msat: 65_000,
3541 htlc_maximum_msat: 80_000,
3543 fee_proportional_millionths: 0,
3544 excess_data: Vec::new()
3546 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3547 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3548 short_channel_id: 2,
3551 cltv_expiry_delta: 0,
3552 htlc_minimum_msat: 0,
3553 htlc_maximum_msat: MAX_VALUE_MSAT,
3555 fee_proportional_millionths: 0,
3556 excess_data: Vec::new()
3558 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3559 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3560 short_channel_id: 4,
3563 cltv_expiry_delta: 0,
3564 htlc_minimum_msat: 0,
3565 htlc_maximum_msat: MAX_VALUE_MSAT,
3567 fee_proportional_millionths: 100_000,
3568 excess_data: Vec::new()
3571 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3572 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3573 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3574 assert_eq!(route.paths.len(), 1);
3575 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3576 let fees = route.paths[0].hops[0].fee_msat;
3577 assert_eq!(fees, 5_000);
3579 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3580 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3581 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3582 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3583 // the other channel.
3584 assert_eq!(route.paths.len(), 1);
3585 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3586 let fees = route.paths[0].hops[0].fee_msat;
3587 assert_eq!(fees, 5_000);
3591 fn htlc_minimum_recipient_overpay_test() {
3592 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3593 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3594 let config = UserConfig::default();
3595 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3596 let scorer = ln_test_utils::TestScorer::new();
3597 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3598 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3600 // Route to node2 over a single path which requires overpaying the recipient themselves.
3602 // First disable all paths except the us -> node1 -> node2 path
3603 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3604 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3605 short_channel_id: 13,
3608 cltv_expiry_delta: 0,
3609 htlc_minimum_msat: 0,
3610 htlc_maximum_msat: 0,
3612 fee_proportional_millionths: 0,
3613 excess_data: Vec::new()
3616 // Set channel 4 to free but with a high htlc_minimum_msat
3617 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3618 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3619 short_channel_id: 4,
3622 cltv_expiry_delta: 0,
3623 htlc_minimum_msat: 15_000,
3624 htlc_maximum_msat: MAX_VALUE_MSAT,
3626 fee_proportional_millionths: 0,
3627 excess_data: Vec::new()
3630 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3631 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3632 // what we try to find a route for, so this test only just happens to work out to exactly
3634 let mut route_params = RouteParameters::from_payment_params_and_value(
3635 payment_params.clone(), 5_000);
3636 route_params.max_total_routing_fee_msat = Some(9_999);
3637 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3638 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3639 &Default::default(), &random_seed_bytes) {
3640 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3641 } else { panic!(); }
3643 let mut route_params = RouteParameters::from_payment_params_and_value(
3644 payment_params.clone(), 5_000);
3645 route_params.max_total_routing_fee_msat = Some(10_000);
3646 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3647 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3648 assert_eq!(route.get_total_fees(), 10_000);
3652 fn disable_channels_test() {
3653 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3654 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3655 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3656 let scorer = ln_test_utils::TestScorer::new();
3657 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3658 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3660 // // Disable channels 4 and 12 by flags=2
3661 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3662 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3663 short_channel_id: 4,
3665 flags: 2, // to disable
3666 cltv_expiry_delta: 0,
3667 htlc_minimum_msat: 0,
3668 htlc_maximum_msat: MAX_VALUE_MSAT,
3670 fee_proportional_millionths: 0,
3671 excess_data: Vec::new()
3673 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3674 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3675 short_channel_id: 12,
3677 flags: 2, // to disable
3678 cltv_expiry_delta: 0,
3679 htlc_minimum_msat: 0,
3680 htlc_maximum_msat: MAX_VALUE_MSAT,
3682 fee_proportional_millionths: 0,
3683 excess_data: Vec::new()
3686 // If all the channels require some features we don't understand, route should fail
3687 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3688 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3689 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3690 &Default::default(), &random_seed_bytes) {
3691 assert_eq!(err, "Failed to find a path to the given destination");
3692 } else { panic!(); }
3694 // If we specify a channel to node7, that overrides our local channel view and that gets used
3695 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3696 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3697 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3698 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3699 &Default::default(), &random_seed_bytes).unwrap();
3700 assert_eq!(route.paths[0].hops.len(), 2);
3702 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3703 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3704 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3705 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3706 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3707 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3709 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3710 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3711 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3712 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3713 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3714 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3718 fn disable_node_test() {
3719 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3720 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3721 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3722 let scorer = ln_test_utils::TestScorer::new();
3723 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3724 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3726 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3727 let mut unknown_features = NodeFeatures::empty();
3728 unknown_features.set_unknown_feature_required();
3729 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3730 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3731 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3733 // If all nodes require some features we don't understand, route should fail
3734 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3735 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3736 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3737 &Default::default(), &random_seed_bytes) {
3738 assert_eq!(err, "Failed to find a path to the given destination");
3739 } else { panic!(); }
3741 // If we specify a channel to node7, that overrides our local channel view and that gets used
3742 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3743 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3744 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3745 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3746 &Default::default(), &random_seed_bytes).unwrap();
3747 assert_eq!(route.paths[0].hops.len(), 2);
3749 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3750 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3751 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3752 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3753 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3754 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3756 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3757 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3758 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3759 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3760 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3761 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3763 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3764 // naively) assume that the user checked the feature bits on the invoice, which override
3765 // the node_announcement.
3769 fn our_chans_test() {
3770 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3771 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3772 let scorer = ln_test_utils::TestScorer::new();
3773 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3774 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3776 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3777 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3778 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3779 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3780 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3781 assert_eq!(route.paths[0].hops.len(), 3);
3783 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3784 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3785 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3786 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3787 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3788 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3790 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3791 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3792 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3793 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3794 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3795 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3797 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3798 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3799 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3800 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3801 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3802 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3804 // If we specify a channel to node7, that overrides our local channel view and that gets used
3805 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3806 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3807 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3808 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3809 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3810 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3811 &Default::default(), &random_seed_bytes).unwrap();
3812 assert_eq!(route.paths[0].hops.len(), 2);
3814 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3815 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3816 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3817 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3818 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3819 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3821 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3822 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3823 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3824 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3825 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3826 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3829 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3830 let zero_fees = RoutingFees {
3832 proportional_millionths: 0,
3834 vec![RouteHint(vec![RouteHintHop {
3835 src_node_id: nodes[3],
3836 short_channel_id: 8,
3838 cltv_expiry_delta: (8 << 4) | 1,
3839 htlc_minimum_msat: None,
3840 htlc_maximum_msat: None,
3842 ]), RouteHint(vec![RouteHintHop {
3843 src_node_id: nodes[4],
3844 short_channel_id: 9,
3847 proportional_millionths: 0,
3849 cltv_expiry_delta: (9 << 4) | 1,
3850 htlc_minimum_msat: None,
3851 htlc_maximum_msat: None,
3852 }]), RouteHint(vec![RouteHintHop {
3853 src_node_id: nodes[5],
3854 short_channel_id: 10,
3856 cltv_expiry_delta: (10 << 4) | 1,
3857 htlc_minimum_msat: None,
3858 htlc_maximum_msat: None,
3862 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3863 let zero_fees = RoutingFees {
3865 proportional_millionths: 0,
3867 vec![RouteHint(vec![RouteHintHop {
3868 src_node_id: nodes[2],
3869 short_channel_id: 5,
3872 proportional_millionths: 0,
3874 cltv_expiry_delta: (5 << 4) | 1,
3875 htlc_minimum_msat: None,
3876 htlc_maximum_msat: None,
3878 src_node_id: nodes[3],
3879 short_channel_id: 8,
3881 cltv_expiry_delta: (8 << 4) | 1,
3882 htlc_minimum_msat: None,
3883 htlc_maximum_msat: None,
3885 ]), RouteHint(vec![RouteHintHop {
3886 src_node_id: nodes[4],
3887 short_channel_id: 9,
3890 proportional_millionths: 0,
3892 cltv_expiry_delta: (9 << 4) | 1,
3893 htlc_minimum_msat: None,
3894 htlc_maximum_msat: None,
3895 }]), RouteHint(vec![RouteHintHop {
3896 src_node_id: nodes[5],
3897 short_channel_id: 10,
3899 cltv_expiry_delta: (10 << 4) | 1,
3900 htlc_minimum_msat: None,
3901 htlc_maximum_msat: None,
3906 fn partial_route_hint_test() {
3907 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3908 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3909 let scorer = ln_test_utils::TestScorer::new();
3910 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3911 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3913 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3914 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3915 // RouteHint may be partially used by the algo to build the best path.
3917 // First check that last hop can't have its source as the payee.
3918 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3919 src_node_id: nodes[6],
3920 short_channel_id: 8,
3923 proportional_millionths: 0,
3925 cltv_expiry_delta: (8 << 4) | 1,
3926 htlc_minimum_msat: None,
3927 htlc_maximum_msat: None,
3930 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3931 invalid_last_hops.push(invalid_last_hop);
3933 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3934 .with_route_hints(invalid_last_hops).unwrap();
3935 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3936 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3937 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3938 &Default::default(), &random_seed_bytes) {
3939 assert_eq!(err, "Route hint cannot have the payee as the source.");
3940 } else { panic!(); }
3943 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3944 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3945 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3946 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3947 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3948 assert_eq!(route.paths[0].hops.len(), 5);
3950 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3951 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3952 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3953 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3954 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3955 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3957 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3958 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3959 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3960 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3961 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3962 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3964 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3965 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3966 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3967 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3968 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3969 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3971 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3972 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3973 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3974 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3975 // If we have a peer in the node map, we'll use their features here since we don't have
3976 // a way of figuring out their features from the invoice:
3977 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3978 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3980 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3981 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3982 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3983 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3984 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3985 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3988 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3989 let zero_fees = RoutingFees {
3991 proportional_millionths: 0,
3993 vec![RouteHint(vec![RouteHintHop {
3994 src_node_id: nodes[3],
3995 short_channel_id: 8,
3997 cltv_expiry_delta: (8 << 4) | 1,
3998 htlc_minimum_msat: None,
3999 htlc_maximum_msat: None,
4000 }]), RouteHint(vec![
4002 ]), RouteHint(vec![RouteHintHop {
4003 src_node_id: nodes[5],
4004 short_channel_id: 10,
4006 cltv_expiry_delta: (10 << 4) | 1,
4007 htlc_minimum_msat: None,
4008 htlc_maximum_msat: None,
4013 fn ignores_empty_last_hops_test() {
4014 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4015 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4016 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4017 let scorer = ln_test_utils::TestScorer::new();
4018 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4019 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4021 // Test handling of an empty RouteHint passed in Invoice.
4022 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4023 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4024 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4025 assert_eq!(route.paths[0].hops.len(), 5);
4027 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4028 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4029 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4030 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4031 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4032 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4034 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4035 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4036 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4037 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4038 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4039 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4041 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4042 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4043 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4044 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4045 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4046 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4048 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4049 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4050 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4051 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4052 // If we have a peer in the node map, we'll use their features here since we don't have
4053 // a way of figuring out their features from the invoice:
4054 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4055 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4057 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4058 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4059 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4060 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4061 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4062 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4065 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4067 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4068 let zero_fees = RoutingFees {
4070 proportional_millionths: 0,
4072 vec![RouteHint(vec![RouteHintHop {
4073 src_node_id: hint_hops[0],
4074 short_channel_id: 0xff00,
4077 proportional_millionths: 0,
4079 cltv_expiry_delta: (5 << 4) | 1,
4080 htlc_minimum_msat: None,
4081 htlc_maximum_msat: None,
4083 src_node_id: hint_hops[1],
4084 short_channel_id: 0xff01,
4086 cltv_expiry_delta: (8 << 4) | 1,
4087 htlc_minimum_msat: None,
4088 htlc_maximum_msat: None,
4093 fn multi_hint_last_hops_test() {
4094 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4095 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4096 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4097 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4098 let scorer = ln_test_utils::TestScorer::new();
4099 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4100 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4101 // Test through channels 2, 3, 0xff00, 0xff01.
4102 // Test shows that multiple hop hints are considered.
4104 // Disabling channels 6 & 7 by flags=2
4105 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4106 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4107 short_channel_id: 6,
4109 flags: 2, // to disable
4110 cltv_expiry_delta: 0,
4111 htlc_minimum_msat: 0,
4112 htlc_maximum_msat: MAX_VALUE_MSAT,
4114 fee_proportional_millionths: 0,
4115 excess_data: Vec::new()
4117 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4118 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4119 short_channel_id: 7,
4121 flags: 2, // to disable
4122 cltv_expiry_delta: 0,
4123 htlc_minimum_msat: 0,
4124 htlc_maximum_msat: MAX_VALUE_MSAT,
4126 fee_proportional_millionths: 0,
4127 excess_data: Vec::new()
4130 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4131 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4132 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4133 assert_eq!(route.paths[0].hops.len(), 4);
4135 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4136 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4137 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4138 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4139 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4140 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4142 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4143 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4144 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4145 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4146 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4147 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4149 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4150 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4151 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4152 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4153 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4154 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4156 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4157 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4158 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4159 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4160 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4161 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4165 fn private_multi_hint_last_hops_test() {
4166 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4167 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4169 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4170 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4172 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4173 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4174 let scorer = ln_test_utils::TestScorer::new();
4175 // Test through channels 2, 3, 0xff00, 0xff01.
4176 // Test shows that multiple hop hints are considered.
4178 // Disabling channels 6 & 7 by flags=2
4179 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4180 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4181 short_channel_id: 6,
4183 flags: 2, // to disable
4184 cltv_expiry_delta: 0,
4185 htlc_minimum_msat: 0,
4186 htlc_maximum_msat: MAX_VALUE_MSAT,
4188 fee_proportional_millionths: 0,
4189 excess_data: Vec::new()
4191 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4192 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4193 short_channel_id: 7,
4195 flags: 2, // to disable
4196 cltv_expiry_delta: 0,
4197 htlc_minimum_msat: 0,
4198 htlc_maximum_msat: MAX_VALUE_MSAT,
4200 fee_proportional_millionths: 0,
4201 excess_data: Vec::new()
4204 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4205 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4206 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4207 assert_eq!(route.paths[0].hops.len(), 4);
4209 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4210 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4211 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4212 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4213 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4214 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4216 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4217 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4218 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4219 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4220 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4221 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4223 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4224 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4225 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4226 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4227 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4228 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4230 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4231 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4232 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4233 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4234 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4235 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4238 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4239 let zero_fees = RoutingFees {
4241 proportional_millionths: 0,
4243 vec![RouteHint(vec![RouteHintHop {
4244 src_node_id: nodes[4],
4245 short_channel_id: 11,
4247 cltv_expiry_delta: (11 << 4) | 1,
4248 htlc_minimum_msat: None,
4249 htlc_maximum_msat: None,
4251 src_node_id: nodes[3],
4252 short_channel_id: 8,
4254 cltv_expiry_delta: (8 << 4) | 1,
4255 htlc_minimum_msat: None,
4256 htlc_maximum_msat: None,
4257 }]), RouteHint(vec![RouteHintHop {
4258 src_node_id: nodes[4],
4259 short_channel_id: 9,
4262 proportional_millionths: 0,
4264 cltv_expiry_delta: (9 << 4) | 1,
4265 htlc_minimum_msat: None,
4266 htlc_maximum_msat: None,
4267 }]), RouteHint(vec![RouteHintHop {
4268 src_node_id: nodes[5],
4269 short_channel_id: 10,
4271 cltv_expiry_delta: (10 << 4) | 1,
4272 htlc_minimum_msat: None,
4273 htlc_maximum_msat: None,
4278 fn last_hops_with_public_channel_test() {
4279 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4280 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4281 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4282 let scorer = ln_test_utils::TestScorer::new();
4283 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4284 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4285 // This test shows that public routes can be present in the invoice
4286 // which would be handled in the same manner.
4288 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4289 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4290 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4291 assert_eq!(route.paths[0].hops.len(), 5);
4293 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4294 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4295 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4296 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4297 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4298 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4300 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4301 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4302 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4303 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4304 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4305 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4307 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4308 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4309 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4310 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4311 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4312 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4314 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4315 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4316 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4317 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4318 // If we have a peer in the node map, we'll use their features here since we don't have
4319 // a way of figuring out their features from the invoice:
4320 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4321 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4323 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4324 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4325 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4326 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4327 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4328 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4332 fn our_chans_last_hop_connect_test() {
4333 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4334 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4335 let scorer = ln_test_utils::TestScorer::new();
4336 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4337 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4339 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4340 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4341 let mut last_hops = last_hops(&nodes);
4342 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4343 .with_route_hints(last_hops.clone()).unwrap();
4344 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4345 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4346 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4347 &Default::default(), &random_seed_bytes).unwrap();
4348 assert_eq!(route.paths[0].hops.len(), 2);
4350 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4351 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4352 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4353 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4354 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4355 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4357 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4358 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4359 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4360 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4361 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4362 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4364 last_hops[0].0[0].fees.base_msat = 1000;
4366 // Revert to via 6 as the fee on 8 goes up
4367 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4368 .with_route_hints(last_hops).unwrap();
4369 let route_params = RouteParameters::from_payment_params_and_value(
4370 payment_params.clone(), 100);
4371 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4372 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4373 assert_eq!(route.paths[0].hops.len(), 4);
4375 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4376 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4377 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4378 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4379 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4380 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4382 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4383 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4384 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4385 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4386 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4387 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4389 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4390 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4391 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4392 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4393 // If we have a peer in the node map, we'll use their features here since we don't have
4394 // a way of figuring out their features from the invoice:
4395 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4396 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4398 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4399 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4400 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4401 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4402 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4403 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4405 // ...but still use 8 for larger payments as 6 has a variable feerate
4406 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4407 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4408 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4409 assert_eq!(route.paths[0].hops.len(), 5);
4411 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4412 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4413 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4414 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4415 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4416 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4418 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4419 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4420 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4421 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4422 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4423 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4425 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4426 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4427 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4428 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4429 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4430 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4432 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4433 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4434 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4435 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4436 // If we have a peer in the node map, we'll use their features here since we don't have
4437 // a way of figuring out their features from the invoice:
4438 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4439 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4441 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4442 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4443 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4444 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4445 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4446 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4449 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> {
4450 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4451 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4452 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4454 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4455 let last_hops = RouteHint(vec![RouteHintHop {
4456 src_node_id: middle_node_id,
4457 short_channel_id: 8,
4460 proportional_millionths: last_hop_fee_prop,
4462 cltv_expiry_delta: (8 << 4) | 1,
4463 htlc_minimum_msat: None,
4464 htlc_maximum_msat: last_hop_htlc_max,
4466 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4467 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4468 let scorer = ln_test_utils::TestScorer::new();
4469 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4470 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4471 let logger = ln_test_utils::TestLogger::new();
4472 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4473 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4474 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4475 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4476 &random_seed_bytes);
4481 fn unannounced_path_test() {
4482 // We should be able to send a payment to a destination without any help of a routing graph
4483 // if we have a channel with a common counterparty that appears in the first and last hop
4485 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4487 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4488 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4489 assert_eq!(route.paths[0].hops.len(), 2);
4491 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4492 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4493 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4494 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4495 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4496 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4498 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4499 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4500 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4501 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4502 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4503 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4507 fn overflow_unannounced_path_test_liquidity_underflow() {
4508 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4509 // the last-hop had a fee which overflowed a u64, we'd panic.
4510 // This was due to us adding the first-hop from us unconditionally, causing us to think
4511 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4512 // In this test, we previously hit a subtraction underflow due to having less available
4513 // liquidity at the last hop than 0.
4514 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());
4518 fn overflow_unannounced_path_test_feerate_overflow() {
4519 // This tests for the same case as above, except instead of hitting a subtraction
4520 // underflow, we hit a case where the fee charged at a hop overflowed.
4521 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());
4525 fn available_amount_while_routing_test() {
4526 // Tests whether we choose the correct available channel amount while routing.
4528 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4529 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4530 let scorer = ln_test_utils::TestScorer::new();
4531 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4532 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4533 let config = UserConfig::default();
4534 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4535 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4538 // We will use a simple single-path route from
4539 // our node to node2 via node0: channels {1, 3}.
4541 // First disable all other paths.
4542 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4543 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4544 short_channel_id: 2,
4547 cltv_expiry_delta: 0,
4548 htlc_minimum_msat: 0,
4549 htlc_maximum_msat: 100_000,
4551 fee_proportional_millionths: 0,
4552 excess_data: Vec::new()
4554 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4555 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4556 short_channel_id: 12,
4559 cltv_expiry_delta: 0,
4560 htlc_minimum_msat: 0,
4561 htlc_maximum_msat: 100_000,
4563 fee_proportional_millionths: 0,
4564 excess_data: Vec::new()
4567 // Make the first channel (#1) very permissive,
4568 // and we will be testing all limits on the second channel.
4569 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4570 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4571 short_channel_id: 1,
4574 cltv_expiry_delta: 0,
4575 htlc_minimum_msat: 0,
4576 htlc_maximum_msat: 1_000_000_000,
4578 fee_proportional_millionths: 0,
4579 excess_data: Vec::new()
4582 // First, let's see if routing works if we have absolutely no idea about the available amount.
4583 // In this case, it should be set to 250_000 sats.
4584 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4585 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4586 short_channel_id: 3,
4589 cltv_expiry_delta: 0,
4590 htlc_minimum_msat: 0,
4591 htlc_maximum_msat: 250_000_000,
4593 fee_proportional_millionths: 0,
4594 excess_data: Vec::new()
4598 // Attempt to route more than available results in a failure.
4599 let route_params = RouteParameters::from_payment_params_and_value(
4600 payment_params.clone(), 250_000_001);
4601 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4602 &our_id, &route_params, &network_graph.read_only(), None,
4603 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4604 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4605 } else { panic!(); }
4609 // Now, attempt to route an exact amount we have should be fine.
4610 let route_params = RouteParameters::from_payment_params_and_value(
4611 payment_params.clone(), 250_000_000);
4612 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4613 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4614 assert_eq!(route.paths.len(), 1);
4615 let path = route.paths.last().unwrap();
4616 assert_eq!(path.hops.len(), 2);
4617 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4618 assert_eq!(path.final_value_msat(), 250_000_000);
4621 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4622 // Disable channel #1 and use another first hop.
4623 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4624 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4625 short_channel_id: 1,
4628 cltv_expiry_delta: 0,
4629 htlc_minimum_msat: 0,
4630 htlc_maximum_msat: 1_000_000_000,
4632 fee_proportional_millionths: 0,
4633 excess_data: Vec::new()
4636 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4637 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4640 // Attempt to route more than available results in a failure.
4641 let route_params = RouteParameters::from_payment_params_and_value(
4642 payment_params.clone(), 200_000_001);
4643 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4644 &our_id, &route_params, &network_graph.read_only(),
4645 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4646 &Default::default(), &random_seed_bytes) {
4647 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4648 } else { panic!(); }
4652 // Now, attempt to route an exact amount we have should be fine.
4653 let route_params = RouteParameters::from_payment_params_and_value(
4654 payment_params.clone(), 200_000_000);
4655 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4656 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4657 &Default::default(), &random_seed_bytes).unwrap();
4658 assert_eq!(route.paths.len(), 1);
4659 let path = route.paths.last().unwrap();
4660 assert_eq!(path.hops.len(), 2);
4661 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4662 assert_eq!(path.final_value_msat(), 200_000_000);
4665 // Enable channel #1 back.
4666 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4667 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4668 short_channel_id: 1,
4671 cltv_expiry_delta: 0,
4672 htlc_minimum_msat: 0,
4673 htlc_maximum_msat: 1_000_000_000,
4675 fee_proportional_millionths: 0,
4676 excess_data: Vec::new()
4680 // Now let's see if routing works if we know only htlc_maximum_msat.
4681 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4682 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4683 short_channel_id: 3,
4686 cltv_expiry_delta: 0,
4687 htlc_minimum_msat: 0,
4688 htlc_maximum_msat: 15_000,
4690 fee_proportional_millionths: 0,
4691 excess_data: Vec::new()
4695 // Attempt to route more than available results in a failure.
4696 let route_params = RouteParameters::from_payment_params_and_value(
4697 payment_params.clone(), 15_001);
4698 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4699 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4700 &scorer, &Default::default(), &random_seed_bytes) {
4701 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4702 } else { panic!(); }
4706 // Now, attempt to route an exact amount we have should be fine.
4707 let route_params = RouteParameters::from_payment_params_and_value(
4708 payment_params.clone(), 15_000);
4709 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4710 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4711 assert_eq!(route.paths.len(), 1);
4712 let path = route.paths.last().unwrap();
4713 assert_eq!(path.hops.len(), 2);
4714 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4715 assert_eq!(path.final_value_msat(), 15_000);
4718 // Now let's see if routing works if we know only capacity from the UTXO.
4720 // We can't change UTXO capacity on the fly, so we'll disable
4721 // the existing channel and add another one with the capacity we need.
4722 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4723 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4724 short_channel_id: 3,
4727 cltv_expiry_delta: 0,
4728 htlc_minimum_msat: 0,
4729 htlc_maximum_msat: MAX_VALUE_MSAT,
4731 fee_proportional_millionths: 0,
4732 excess_data: Vec::new()
4735 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4736 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4737 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4738 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4739 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4741 *chain_monitor.utxo_ret.lock().unwrap() =
4742 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4743 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4745 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4746 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4747 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4748 short_channel_id: 333,
4751 cltv_expiry_delta: (3 << 4) | 1,
4752 htlc_minimum_msat: 0,
4753 htlc_maximum_msat: 15_000,
4755 fee_proportional_millionths: 0,
4756 excess_data: Vec::new()
4758 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4759 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4760 short_channel_id: 333,
4763 cltv_expiry_delta: (3 << 4) | 2,
4764 htlc_minimum_msat: 0,
4765 htlc_maximum_msat: 15_000,
4767 fee_proportional_millionths: 0,
4768 excess_data: Vec::new()
4772 // Attempt to route more than available results in a failure.
4773 let route_params = RouteParameters::from_payment_params_and_value(
4774 payment_params.clone(), 15_001);
4775 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4776 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4777 &scorer, &Default::default(), &random_seed_bytes) {
4778 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4779 } else { panic!(); }
4783 // Now, attempt to route an exact amount we have should be fine.
4784 let route_params = RouteParameters::from_payment_params_and_value(
4785 payment_params.clone(), 15_000);
4786 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4787 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4788 assert_eq!(route.paths.len(), 1);
4789 let path = route.paths.last().unwrap();
4790 assert_eq!(path.hops.len(), 2);
4791 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4792 assert_eq!(path.final_value_msat(), 15_000);
4795 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4796 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4797 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4798 short_channel_id: 333,
4801 cltv_expiry_delta: 0,
4802 htlc_minimum_msat: 0,
4803 htlc_maximum_msat: 10_000,
4805 fee_proportional_millionths: 0,
4806 excess_data: Vec::new()
4810 // Attempt to route more than available results in a failure.
4811 let route_params = RouteParameters::from_payment_params_and_value(
4812 payment_params.clone(), 10_001);
4813 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4814 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4815 &scorer, &Default::default(), &random_seed_bytes) {
4816 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4817 } else { panic!(); }
4821 // Now, attempt to route an exact amount we have should be fine.
4822 let route_params = RouteParameters::from_payment_params_and_value(
4823 payment_params.clone(), 10_000);
4824 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4825 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4826 assert_eq!(route.paths.len(), 1);
4827 let path = route.paths.last().unwrap();
4828 assert_eq!(path.hops.len(), 2);
4829 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4830 assert_eq!(path.final_value_msat(), 10_000);
4835 fn available_liquidity_last_hop_test() {
4836 // Check that available liquidity properly limits the path even when only
4837 // one of the latter hops is limited.
4838 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4839 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4840 let scorer = ln_test_utils::TestScorer::new();
4841 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4842 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4843 let config = UserConfig::default();
4844 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4845 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4848 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4849 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4850 // Total capacity: 50 sats.
4852 // Disable other potential paths.
4853 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4854 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4855 short_channel_id: 2,
4858 cltv_expiry_delta: 0,
4859 htlc_minimum_msat: 0,
4860 htlc_maximum_msat: 100_000,
4862 fee_proportional_millionths: 0,
4863 excess_data: Vec::new()
4865 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4866 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4867 short_channel_id: 7,
4870 cltv_expiry_delta: 0,
4871 htlc_minimum_msat: 0,
4872 htlc_maximum_msat: 100_000,
4874 fee_proportional_millionths: 0,
4875 excess_data: Vec::new()
4880 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4881 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4882 short_channel_id: 12,
4885 cltv_expiry_delta: 0,
4886 htlc_minimum_msat: 0,
4887 htlc_maximum_msat: 100_000,
4889 fee_proportional_millionths: 0,
4890 excess_data: Vec::new()
4892 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4893 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4894 short_channel_id: 13,
4897 cltv_expiry_delta: 0,
4898 htlc_minimum_msat: 0,
4899 htlc_maximum_msat: 100_000,
4901 fee_proportional_millionths: 0,
4902 excess_data: Vec::new()
4905 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4906 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4907 short_channel_id: 6,
4910 cltv_expiry_delta: 0,
4911 htlc_minimum_msat: 0,
4912 htlc_maximum_msat: 50_000,
4914 fee_proportional_millionths: 0,
4915 excess_data: Vec::new()
4917 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4918 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4919 short_channel_id: 11,
4922 cltv_expiry_delta: 0,
4923 htlc_minimum_msat: 0,
4924 htlc_maximum_msat: 100_000,
4926 fee_proportional_millionths: 0,
4927 excess_data: Vec::new()
4930 // Attempt to route more than available results in a failure.
4931 let route_params = RouteParameters::from_payment_params_and_value(
4932 payment_params.clone(), 60_000);
4933 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4934 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4935 &scorer, &Default::default(), &random_seed_bytes) {
4936 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4937 } else { panic!(); }
4941 // Now, attempt to route 49 sats (just a bit below the capacity).
4942 let route_params = RouteParameters::from_payment_params_and_value(
4943 payment_params.clone(), 49_000);
4944 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4945 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4946 assert_eq!(route.paths.len(), 1);
4947 let mut total_amount_paid_msat = 0;
4948 for path in &route.paths {
4949 assert_eq!(path.hops.len(), 4);
4950 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4951 total_amount_paid_msat += path.final_value_msat();
4953 assert_eq!(total_amount_paid_msat, 49_000);
4957 // Attempt to route an exact amount is also fine
4958 let route_params = RouteParameters::from_payment_params_and_value(
4959 payment_params, 50_000);
4960 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4961 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4962 assert_eq!(route.paths.len(), 1);
4963 let mut total_amount_paid_msat = 0;
4964 for path in &route.paths {
4965 assert_eq!(path.hops.len(), 4);
4966 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4967 total_amount_paid_msat += path.final_value_msat();
4969 assert_eq!(total_amount_paid_msat, 50_000);
4974 fn ignore_fee_first_hop_test() {
4975 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4976 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4977 let scorer = ln_test_utils::TestScorer::new();
4978 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4979 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4980 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4982 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4983 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4984 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4985 short_channel_id: 1,
4988 cltv_expiry_delta: 0,
4989 htlc_minimum_msat: 0,
4990 htlc_maximum_msat: 100_000,
4991 fee_base_msat: 1_000_000,
4992 fee_proportional_millionths: 0,
4993 excess_data: Vec::new()
4995 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4996 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4997 short_channel_id: 3,
5000 cltv_expiry_delta: 0,
5001 htlc_minimum_msat: 0,
5002 htlc_maximum_msat: 50_000,
5004 fee_proportional_millionths: 0,
5005 excess_data: Vec::new()
5009 let route_params = RouteParameters::from_payment_params_and_value(
5010 payment_params, 50_000);
5011 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5012 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5013 assert_eq!(route.paths.len(), 1);
5014 let mut total_amount_paid_msat = 0;
5015 for path in &route.paths {
5016 assert_eq!(path.hops.len(), 2);
5017 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5018 total_amount_paid_msat += path.final_value_msat();
5020 assert_eq!(total_amount_paid_msat, 50_000);
5025 fn simple_mpp_route_test() {
5026 let (secp_ctx, _, _, _, _) = build_graph();
5027 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5028 let config = UserConfig::default();
5029 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5030 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5032 do_simple_mpp_route_test(clear_payment_params);
5034 // MPP to a 1-hop blinded path for nodes[2]
5035 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5036 let blinded_path = BlindedPath {
5037 introduction_node_id: nodes[2],
5038 blinding_point: ln_test_utils::pubkey(42),
5039 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5041 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5043 fee_proportional_millionths: 0,
5044 htlc_minimum_msat: 0,
5045 htlc_maximum_msat: 0,
5046 cltv_expiry_delta: 0,
5047 features: BlindedHopFeatures::empty(),
5049 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5050 .with_bolt12_features(bolt12_features.clone()).unwrap();
5051 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5053 // MPP to 3 2-hop blinded paths
5054 let mut blinded_path_node_0 = blinded_path.clone();
5055 blinded_path_node_0.introduction_node_id = nodes[0];
5056 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5057 let mut node_0_payinfo = blinded_payinfo.clone();
5058 node_0_payinfo.htlc_maximum_msat = 50_000;
5060 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5061 blinded_path_node_7.introduction_node_id = nodes[7];
5062 let mut node_7_payinfo = blinded_payinfo.clone();
5063 node_7_payinfo.htlc_maximum_msat = 60_000;
5065 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5066 blinded_path_node_1.introduction_node_id = nodes[1];
5067 let mut node_1_payinfo = blinded_payinfo.clone();
5068 node_1_payinfo.htlc_maximum_msat = 180_000;
5070 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5072 (node_0_payinfo, blinded_path_node_0),
5073 (node_7_payinfo, blinded_path_node_7),
5074 (node_1_payinfo, blinded_path_node_1)
5076 .with_bolt12_features(bolt12_features).unwrap();
5077 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5081 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5082 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5083 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5084 let scorer = ln_test_utils::TestScorer::new();
5085 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5086 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5088 // We need a route consisting of 3 paths:
5089 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5090 // To achieve this, the amount being transferred should be around
5091 // the total capacity of these 3 paths.
5093 // First, we set limits on these (previously unlimited) channels.
5094 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5096 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5097 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5098 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5099 short_channel_id: 1,
5102 cltv_expiry_delta: 0,
5103 htlc_minimum_msat: 0,
5104 htlc_maximum_msat: 100_000,
5106 fee_proportional_millionths: 0,
5107 excess_data: Vec::new()
5109 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5110 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5111 short_channel_id: 3,
5114 cltv_expiry_delta: 0,
5115 htlc_minimum_msat: 0,
5116 htlc_maximum_msat: 50_000,
5118 fee_proportional_millionths: 0,
5119 excess_data: Vec::new()
5122 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5123 // (total limit 60).
5124 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5125 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5126 short_channel_id: 12,
5129 cltv_expiry_delta: 0,
5130 htlc_minimum_msat: 0,
5131 htlc_maximum_msat: 60_000,
5133 fee_proportional_millionths: 0,
5134 excess_data: Vec::new()
5136 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5137 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5138 short_channel_id: 13,
5141 cltv_expiry_delta: 0,
5142 htlc_minimum_msat: 0,
5143 htlc_maximum_msat: 60_000,
5145 fee_proportional_millionths: 0,
5146 excess_data: Vec::new()
5149 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5150 // (total capacity 180 sats).
5151 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5152 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5153 short_channel_id: 2,
5156 cltv_expiry_delta: 0,
5157 htlc_minimum_msat: 0,
5158 htlc_maximum_msat: 200_000,
5160 fee_proportional_millionths: 0,
5161 excess_data: Vec::new()
5163 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5164 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5165 short_channel_id: 4,
5168 cltv_expiry_delta: 0,
5169 htlc_minimum_msat: 0,
5170 htlc_maximum_msat: 180_000,
5172 fee_proportional_millionths: 0,
5173 excess_data: Vec::new()
5177 // Attempt to route more than available results in a failure.
5178 let route_params = RouteParameters::from_payment_params_and_value(
5179 payment_params.clone(), 300_000);
5180 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5181 &our_id, &route_params, &network_graph.read_only(), None,
5182 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5183 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5184 } else { panic!(); }
5188 // Attempt to route while setting max_path_count to 0 results in a failure.
5189 let zero_payment_params = payment_params.clone().with_max_path_count(0);
5190 let route_params = RouteParameters::from_payment_params_and_value(
5191 zero_payment_params, 100);
5192 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5193 &our_id, &route_params, &network_graph.read_only(), None,
5194 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5195 assert_eq!(err, "Can't find a route with no paths allowed.");
5196 } else { panic!(); }
5200 // Attempt to route while setting max_path_count to 3 results in a failure.
5201 // This is the case because the minimal_value_contribution_msat would require each path
5202 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5203 let fail_payment_params = payment_params.clone().with_max_path_count(3);
5204 let route_params = RouteParameters::from_payment_params_and_value(
5205 fail_payment_params, 250_000);
5206 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5207 &our_id, &route_params, &network_graph.read_only(), None,
5208 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5209 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5210 } else { panic!(); }
5214 // Now, attempt to route 250 sats (just a bit below the capacity).
5215 // Our algorithm should provide us with these 3 paths.
5216 let route_params = RouteParameters::from_payment_params_and_value(
5217 payment_params.clone(), 250_000);
5218 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5219 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5220 assert_eq!(route.paths.len(), 3);
5221 let mut total_amount_paid_msat = 0;
5222 for path in &route.paths {
5223 if let Some(bt) = &path.blinded_tail {
5224 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5226 assert_eq!(path.hops.len(), 2);
5227 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5229 total_amount_paid_msat += path.final_value_msat();
5231 assert_eq!(total_amount_paid_msat, 250_000);
5235 // Attempt to route an exact amount is also fine
5236 let route_params = RouteParameters::from_payment_params_and_value(
5237 payment_params.clone(), 290_000);
5238 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5239 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5240 assert_eq!(route.paths.len(), 3);
5241 let mut total_amount_paid_msat = 0;
5242 for path in &route.paths {
5243 if payment_params.payee.blinded_route_hints().len() != 0 {
5244 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5245 if let Some(bt) = &path.blinded_tail {
5246 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5247 if bt.hops.len() > 1 {
5248 assert_eq!(path.hops.last().unwrap().pubkey,
5249 payment_params.payee.blinded_route_hints().iter()
5250 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5251 .map(|(_, p)| p.introduction_node_id).unwrap());
5253 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5256 assert_eq!(path.hops.len(), 2);
5257 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5259 total_amount_paid_msat += path.final_value_msat();
5261 assert_eq!(total_amount_paid_msat, 290_000);
5266 fn long_mpp_route_test() {
5267 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5268 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5269 let scorer = ln_test_utils::TestScorer::new();
5270 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5271 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5272 let config = UserConfig::default();
5273 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5274 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5277 // We need a route consisting of 3 paths:
5278 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5279 // Note that these paths overlap (channels 5, 12, 13).
5280 // We will route 300 sats.
5281 // Each path will have 100 sats capacity, those channels which
5282 // are used twice will have 200 sats capacity.
5284 // Disable other potential paths.
5285 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5286 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5287 short_channel_id: 2,
5290 cltv_expiry_delta: 0,
5291 htlc_minimum_msat: 0,
5292 htlc_maximum_msat: 100_000,
5294 fee_proportional_millionths: 0,
5295 excess_data: Vec::new()
5297 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5298 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5299 short_channel_id: 7,
5302 cltv_expiry_delta: 0,
5303 htlc_minimum_msat: 0,
5304 htlc_maximum_msat: 100_000,
5306 fee_proportional_millionths: 0,
5307 excess_data: Vec::new()
5310 // Path via {node0, node2} is channels {1, 3, 5}.
5311 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5312 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5313 short_channel_id: 1,
5316 cltv_expiry_delta: 0,
5317 htlc_minimum_msat: 0,
5318 htlc_maximum_msat: 100_000,
5320 fee_proportional_millionths: 0,
5321 excess_data: Vec::new()
5323 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5324 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5325 short_channel_id: 3,
5328 cltv_expiry_delta: 0,
5329 htlc_minimum_msat: 0,
5330 htlc_maximum_msat: 100_000,
5332 fee_proportional_millionths: 0,
5333 excess_data: Vec::new()
5336 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5337 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5338 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5339 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5340 short_channel_id: 5,
5343 cltv_expiry_delta: 0,
5344 htlc_minimum_msat: 0,
5345 htlc_maximum_msat: 200_000,
5347 fee_proportional_millionths: 0,
5348 excess_data: Vec::new()
5351 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5352 // Add 100 sats to the capacities of {12, 13}, because these channels
5353 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5354 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5355 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5356 short_channel_id: 12,
5359 cltv_expiry_delta: 0,
5360 htlc_minimum_msat: 0,
5361 htlc_maximum_msat: 200_000,
5363 fee_proportional_millionths: 0,
5364 excess_data: Vec::new()
5366 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5367 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5368 short_channel_id: 13,
5371 cltv_expiry_delta: 0,
5372 htlc_minimum_msat: 0,
5373 htlc_maximum_msat: 200_000,
5375 fee_proportional_millionths: 0,
5376 excess_data: Vec::new()
5379 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5380 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5381 short_channel_id: 6,
5384 cltv_expiry_delta: 0,
5385 htlc_minimum_msat: 0,
5386 htlc_maximum_msat: 100_000,
5388 fee_proportional_millionths: 0,
5389 excess_data: Vec::new()
5391 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5392 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5393 short_channel_id: 11,
5396 cltv_expiry_delta: 0,
5397 htlc_minimum_msat: 0,
5398 htlc_maximum_msat: 100_000,
5400 fee_proportional_millionths: 0,
5401 excess_data: Vec::new()
5404 // Path via {node7, node2} is channels {12, 13, 5}.
5405 // We already limited them to 200 sats (they are used twice for 100 sats).
5406 // Nothing to do here.
5409 // Attempt to route more than available results in a failure.
5410 let route_params = RouteParameters::from_payment_params_and_value(
5411 payment_params.clone(), 350_000);
5412 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5413 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5414 &scorer, &Default::default(), &random_seed_bytes) {
5415 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5416 } else { panic!(); }
5420 // Now, attempt to route 300 sats (exact amount we can route).
5421 // Our algorithm should provide us with these 3 paths, 100 sats each.
5422 let route_params = RouteParameters::from_payment_params_and_value(
5423 payment_params, 300_000);
5424 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5425 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5426 assert_eq!(route.paths.len(), 3);
5428 let mut total_amount_paid_msat = 0;
5429 for path in &route.paths {
5430 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5431 total_amount_paid_msat += path.final_value_msat();
5433 assert_eq!(total_amount_paid_msat, 300_000);
5439 fn mpp_cheaper_route_test() {
5440 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5441 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5442 let scorer = ln_test_utils::TestScorer::new();
5443 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5444 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5445 let config = UserConfig::default();
5446 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5447 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5450 // This test checks that if we have two cheaper paths and one more expensive path,
5451 // so that liquidity-wise any 2 of 3 combination is sufficient,
5452 // two cheaper paths will be taken.
5453 // These paths have equal available liquidity.
5455 // We need a combination of 3 paths:
5456 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5457 // Note that these paths overlap (channels 5, 12, 13).
5458 // Each path will have 100 sats capacity, those channels which
5459 // are used twice will have 200 sats capacity.
5461 // Disable other potential paths.
5462 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5463 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5464 short_channel_id: 2,
5467 cltv_expiry_delta: 0,
5468 htlc_minimum_msat: 0,
5469 htlc_maximum_msat: 100_000,
5471 fee_proportional_millionths: 0,
5472 excess_data: Vec::new()
5474 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5475 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5476 short_channel_id: 7,
5479 cltv_expiry_delta: 0,
5480 htlc_minimum_msat: 0,
5481 htlc_maximum_msat: 100_000,
5483 fee_proportional_millionths: 0,
5484 excess_data: Vec::new()
5487 // Path via {node0, node2} is channels {1, 3, 5}.
5488 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5489 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5490 short_channel_id: 1,
5493 cltv_expiry_delta: 0,
5494 htlc_minimum_msat: 0,
5495 htlc_maximum_msat: 100_000,
5497 fee_proportional_millionths: 0,
5498 excess_data: Vec::new()
5500 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5501 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5502 short_channel_id: 3,
5505 cltv_expiry_delta: 0,
5506 htlc_minimum_msat: 0,
5507 htlc_maximum_msat: 100_000,
5509 fee_proportional_millionths: 0,
5510 excess_data: Vec::new()
5513 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5514 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5515 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5516 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5517 short_channel_id: 5,
5520 cltv_expiry_delta: 0,
5521 htlc_minimum_msat: 0,
5522 htlc_maximum_msat: 200_000,
5524 fee_proportional_millionths: 0,
5525 excess_data: Vec::new()
5528 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5529 // Add 100 sats to the capacities of {12, 13}, because these channels
5530 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5531 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5532 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5533 short_channel_id: 12,
5536 cltv_expiry_delta: 0,
5537 htlc_minimum_msat: 0,
5538 htlc_maximum_msat: 200_000,
5540 fee_proportional_millionths: 0,
5541 excess_data: Vec::new()
5543 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5544 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5545 short_channel_id: 13,
5548 cltv_expiry_delta: 0,
5549 htlc_minimum_msat: 0,
5550 htlc_maximum_msat: 200_000,
5552 fee_proportional_millionths: 0,
5553 excess_data: Vec::new()
5556 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5557 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5558 short_channel_id: 6,
5561 cltv_expiry_delta: 0,
5562 htlc_minimum_msat: 0,
5563 htlc_maximum_msat: 100_000,
5564 fee_base_msat: 1_000,
5565 fee_proportional_millionths: 0,
5566 excess_data: Vec::new()
5568 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5569 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5570 short_channel_id: 11,
5573 cltv_expiry_delta: 0,
5574 htlc_minimum_msat: 0,
5575 htlc_maximum_msat: 100_000,
5577 fee_proportional_millionths: 0,
5578 excess_data: Vec::new()
5581 // Path via {node7, node2} is channels {12, 13, 5}.
5582 // We already limited them to 200 sats (they are used twice for 100 sats).
5583 // Nothing to do here.
5586 // Now, attempt to route 180 sats.
5587 // Our algorithm should provide us with these 2 paths.
5588 let route_params = RouteParameters::from_payment_params_and_value(
5589 payment_params, 180_000);
5590 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5591 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5592 assert_eq!(route.paths.len(), 2);
5594 let mut total_value_transferred_msat = 0;
5595 let mut total_paid_msat = 0;
5596 for path in &route.paths {
5597 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5598 total_value_transferred_msat += path.final_value_msat();
5599 for hop in &path.hops {
5600 total_paid_msat += hop.fee_msat;
5603 // If we paid fee, this would be higher.
5604 assert_eq!(total_value_transferred_msat, 180_000);
5605 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5606 assert_eq!(total_fees_paid, 0);
5611 fn fees_on_mpp_route_test() {
5612 // This test makes sure that MPP algorithm properly takes into account
5613 // fees charged on the channels, by making the fees impactful:
5614 // if the fee is not properly accounted for, the behavior is different.
5615 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5616 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5617 let scorer = ln_test_utils::TestScorer::new();
5618 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5619 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5620 let config = UserConfig::default();
5621 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5622 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5625 // We need a route consisting of 2 paths:
5626 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5627 // We will route 200 sats, Each path will have 100 sats capacity.
5629 // This test is not particularly stable: e.g.,
5630 // there's a way to route via {node0, node2, node4}.
5631 // It works while pathfinding is deterministic, but can be broken otherwise.
5632 // It's fine to ignore this concern for now.
5634 // Disable other potential paths.
5635 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5636 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5637 short_channel_id: 2,
5640 cltv_expiry_delta: 0,
5641 htlc_minimum_msat: 0,
5642 htlc_maximum_msat: 100_000,
5644 fee_proportional_millionths: 0,
5645 excess_data: Vec::new()
5648 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5649 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5650 short_channel_id: 7,
5653 cltv_expiry_delta: 0,
5654 htlc_minimum_msat: 0,
5655 htlc_maximum_msat: 100_000,
5657 fee_proportional_millionths: 0,
5658 excess_data: Vec::new()
5661 // Path via {node0, node2} is channels {1, 3, 5}.
5662 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5663 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5664 short_channel_id: 1,
5667 cltv_expiry_delta: 0,
5668 htlc_minimum_msat: 0,
5669 htlc_maximum_msat: 100_000,
5671 fee_proportional_millionths: 0,
5672 excess_data: Vec::new()
5674 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5675 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5676 short_channel_id: 3,
5679 cltv_expiry_delta: 0,
5680 htlc_minimum_msat: 0,
5681 htlc_maximum_msat: 100_000,
5683 fee_proportional_millionths: 0,
5684 excess_data: Vec::new()
5687 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5688 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5689 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5690 short_channel_id: 5,
5693 cltv_expiry_delta: 0,
5694 htlc_minimum_msat: 0,
5695 htlc_maximum_msat: 100_000,
5697 fee_proportional_millionths: 0,
5698 excess_data: Vec::new()
5701 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5702 // All channels should be 100 sats capacity. But for the fee experiment,
5703 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5704 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5705 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5706 // so no matter how large are other channels,
5707 // the whole path will be limited by 100 sats with just these 2 conditions:
5708 // - channel 12 capacity is 250 sats
5709 // - fee for channel 6 is 150 sats
5710 // Let's test this by enforcing these 2 conditions and removing other limits.
5711 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5712 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5713 short_channel_id: 12,
5716 cltv_expiry_delta: 0,
5717 htlc_minimum_msat: 0,
5718 htlc_maximum_msat: 250_000,
5720 fee_proportional_millionths: 0,
5721 excess_data: Vec::new()
5723 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5724 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5725 short_channel_id: 13,
5728 cltv_expiry_delta: 0,
5729 htlc_minimum_msat: 0,
5730 htlc_maximum_msat: MAX_VALUE_MSAT,
5732 fee_proportional_millionths: 0,
5733 excess_data: Vec::new()
5736 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5737 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5738 short_channel_id: 6,
5741 cltv_expiry_delta: 0,
5742 htlc_minimum_msat: 0,
5743 htlc_maximum_msat: MAX_VALUE_MSAT,
5744 fee_base_msat: 150_000,
5745 fee_proportional_millionths: 0,
5746 excess_data: Vec::new()
5748 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5749 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5750 short_channel_id: 11,
5753 cltv_expiry_delta: 0,
5754 htlc_minimum_msat: 0,
5755 htlc_maximum_msat: MAX_VALUE_MSAT,
5757 fee_proportional_millionths: 0,
5758 excess_data: Vec::new()
5762 // Attempt to route more than available results in a failure.
5763 let route_params = RouteParameters::from_payment_params_and_value(
5764 payment_params.clone(), 210_000);
5765 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5766 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5767 &scorer, &Default::default(), &random_seed_bytes) {
5768 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5769 } else { panic!(); }
5773 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5774 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5775 max_total_routing_fee_msat: Some(149_999) };
5776 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5777 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5778 &scorer, &Default::default(), &random_seed_bytes) {
5779 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5780 } else { panic!(); }
5784 // Now, attempt to route 200 sats (exact amount we can route).
5785 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5786 max_total_routing_fee_msat: Some(150_000) };
5787 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5788 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5789 assert_eq!(route.paths.len(), 2);
5791 let mut total_amount_paid_msat = 0;
5792 for path in &route.paths {
5793 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5794 total_amount_paid_msat += path.final_value_msat();
5796 assert_eq!(total_amount_paid_msat, 200_000);
5797 assert_eq!(route.get_total_fees(), 150_000);
5802 fn mpp_with_last_hops() {
5803 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5804 // via a single last-hop route hint, we'd fail to route if we first collected routes
5805 // totaling close but not quite enough to fund the full payment.
5807 // This was because we considered last-hop hints to have exactly the sought payment amount
5808 // instead of the amount we were trying to collect, needlessly limiting our path searching
5809 // at the very first hop.
5811 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5812 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5813 // to only have the remaining to-collect amount in available liquidity.
5815 // This bug appeared in production in some specific channel configurations.
5816 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5817 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5818 let scorer = ln_test_utils::TestScorer::new();
5819 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5820 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5821 let config = UserConfig::default();
5822 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5823 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5824 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5825 src_node_id: nodes[2],
5826 short_channel_id: 42,
5827 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5828 cltv_expiry_delta: 42,
5829 htlc_minimum_msat: None,
5830 htlc_maximum_msat: None,
5831 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5833 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5834 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5835 // would first use the no-fee route and then fail to find a path along the second route as
5836 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5837 // under 5% of our payment amount.
5838 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5839 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5840 short_channel_id: 1,
5843 cltv_expiry_delta: (5 << 4) | 5,
5844 htlc_minimum_msat: 0,
5845 htlc_maximum_msat: 99_000,
5846 fee_base_msat: u32::max_value(),
5847 fee_proportional_millionths: u32::max_value(),
5848 excess_data: Vec::new()
5850 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5851 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5852 short_channel_id: 2,
5855 cltv_expiry_delta: (5 << 4) | 3,
5856 htlc_minimum_msat: 0,
5857 htlc_maximum_msat: 99_000,
5858 fee_base_msat: u32::max_value(),
5859 fee_proportional_millionths: u32::max_value(),
5860 excess_data: Vec::new()
5862 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5863 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5864 short_channel_id: 4,
5867 cltv_expiry_delta: (4 << 4) | 1,
5868 htlc_minimum_msat: 0,
5869 htlc_maximum_msat: MAX_VALUE_MSAT,
5871 fee_proportional_millionths: 0,
5872 excess_data: Vec::new()
5874 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5875 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5876 short_channel_id: 13,
5878 flags: 0|2, // Channel disabled
5879 cltv_expiry_delta: (13 << 4) | 1,
5880 htlc_minimum_msat: 0,
5881 htlc_maximum_msat: MAX_VALUE_MSAT,
5883 fee_proportional_millionths: 2000000,
5884 excess_data: Vec::new()
5887 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5889 let route_params = RouteParameters::from_payment_params_and_value(
5890 payment_params, 100_000);
5891 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5892 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5893 assert_eq!(route.paths.len(), 2);
5894 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5895 // Paths are manually ordered ordered by SCID, so:
5896 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5897 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5898 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5899 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5900 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5901 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5902 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5903 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5904 assert_eq!(route.get_total_fees(), 1);
5905 assert_eq!(route.get_total_amount(), 100_000);
5909 fn drop_lowest_channel_mpp_route_test() {
5910 // This test checks that low-capacity channel is dropped when after
5911 // path finding we realize that we found more capacity than we need.
5912 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5913 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5914 let scorer = ln_test_utils::TestScorer::new();
5915 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5916 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5917 let config = UserConfig::default();
5918 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5919 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5921 .with_max_channel_saturation_power_of_half(0);
5923 // We need a route consisting of 3 paths:
5924 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5926 // The first and the second paths should be sufficient, but the third should be
5927 // cheaper, so that we select it but drop later.
5929 // First, we set limits on these (previously unlimited) channels.
5930 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5932 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5933 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5934 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5935 short_channel_id: 1,
5938 cltv_expiry_delta: 0,
5939 htlc_minimum_msat: 0,
5940 htlc_maximum_msat: 100_000,
5942 fee_proportional_millionths: 0,
5943 excess_data: Vec::new()
5945 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5946 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5947 short_channel_id: 3,
5950 cltv_expiry_delta: 0,
5951 htlc_minimum_msat: 0,
5952 htlc_maximum_msat: 50_000,
5954 fee_proportional_millionths: 0,
5955 excess_data: Vec::new()
5958 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5959 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5960 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5961 short_channel_id: 12,
5964 cltv_expiry_delta: 0,
5965 htlc_minimum_msat: 0,
5966 htlc_maximum_msat: 60_000,
5968 fee_proportional_millionths: 0,
5969 excess_data: Vec::new()
5971 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5972 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5973 short_channel_id: 13,
5976 cltv_expiry_delta: 0,
5977 htlc_minimum_msat: 0,
5978 htlc_maximum_msat: 60_000,
5980 fee_proportional_millionths: 0,
5981 excess_data: Vec::new()
5984 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5985 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5986 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5987 short_channel_id: 2,
5990 cltv_expiry_delta: 0,
5991 htlc_minimum_msat: 0,
5992 htlc_maximum_msat: 20_000,
5994 fee_proportional_millionths: 0,
5995 excess_data: Vec::new()
5997 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5998 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5999 short_channel_id: 4,
6002 cltv_expiry_delta: 0,
6003 htlc_minimum_msat: 0,
6004 htlc_maximum_msat: 20_000,
6006 fee_proportional_millionths: 0,
6007 excess_data: Vec::new()
6011 // Attempt to route more than available results in a failure.
6012 let route_params = RouteParameters::from_payment_params_and_value(
6013 payment_params.clone(), 150_000);
6014 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6015 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6016 &scorer, &Default::default(), &random_seed_bytes) {
6017 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6018 } else { panic!(); }
6022 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6023 // Our algorithm should provide us with these 3 paths.
6024 let route_params = RouteParameters::from_payment_params_and_value(
6025 payment_params.clone(), 125_000);
6026 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6027 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6028 assert_eq!(route.paths.len(), 3);
6029 let mut total_amount_paid_msat = 0;
6030 for path in &route.paths {
6031 assert_eq!(path.hops.len(), 2);
6032 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6033 total_amount_paid_msat += path.final_value_msat();
6035 assert_eq!(total_amount_paid_msat, 125_000);
6039 // Attempt to route without the last small cheap channel
6040 let route_params = RouteParameters::from_payment_params_and_value(
6041 payment_params, 90_000);
6042 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6043 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6044 assert_eq!(route.paths.len(), 2);
6045 let mut total_amount_paid_msat = 0;
6046 for path in &route.paths {
6047 assert_eq!(path.hops.len(), 2);
6048 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6049 total_amount_paid_msat += path.final_value_msat();
6051 assert_eq!(total_amount_paid_msat, 90_000);
6056 fn min_criteria_consistency() {
6057 // Test that we don't use an inconsistent metric between updating and walking nodes during
6058 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6059 // was updated with a different criterion from the heap sorting, resulting in loops in
6060 // calculated paths. We test for that specific case here.
6062 // We construct a network that looks like this:
6064 // node2 -1(3)2- node3
6068 // node1 -1(5)2- node4 -1(1)2- node6
6074 // We create a loop on the side of our real path - our destination is node 6, with a
6075 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6076 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6077 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6078 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6079 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6080 // "previous hop" being set to node 3, creating a loop in the path.
6081 let secp_ctx = Secp256k1::new();
6082 let logger = Arc::new(ln_test_utils::TestLogger::new());
6083 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6084 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6085 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6086 let scorer = ln_test_utils::TestScorer::new();
6087 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6088 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6089 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6091 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6092 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6093 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6094 short_channel_id: 6,
6097 cltv_expiry_delta: (6 << 4) | 0,
6098 htlc_minimum_msat: 0,
6099 htlc_maximum_msat: MAX_VALUE_MSAT,
6101 fee_proportional_millionths: 0,
6102 excess_data: Vec::new()
6104 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6106 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6107 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6108 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6109 short_channel_id: 5,
6112 cltv_expiry_delta: (5 << 4) | 0,
6113 htlc_minimum_msat: 0,
6114 htlc_maximum_msat: MAX_VALUE_MSAT,
6116 fee_proportional_millionths: 0,
6117 excess_data: Vec::new()
6119 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6121 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6122 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6123 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6124 short_channel_id: 4,
6127 cltv_expiry_delta: (4 << 4) | 0,
6128 htlc_minimum_msat: 0,
6129 htlc_maximum_msat: MAX_VALUE_MSAT,
6131 fee_proportional_millionths: 0,
6132 excess_data: Vec::new()
6134 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6136 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6137 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6138 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6139 short_channel_id: 3,
6142 cltv_expiry_delta: (3 << 4) | 0,
6143 htlc_minimum_msat: 0,
6144 htlc_maximum_msat: MAX_VALUE_MSAT,
6146 fee_proportional_millionths: 0,
6147 excess_data: Vec::new()
6149 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6151 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6152 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6153 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6154 short_channel_id: 2,
6157 cltv_expiry_delta: (2 << 4) | 0,
6158 htlc_minimum_msat: 0,
6159 htlc_maximum_msat: MAX_VALUE_MSAT,
6161 fee_proportional_millionths: 0,
6162 excess_data: Vec::new()
6165 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6166 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6167 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6168 short_channel_id: 1,
6171 cltv_expiry_delta: (1 << 4) | 0,
6172 htlc_minimum_msat: 100,
6173 htlc_maximum_msat: MAX_VALUE_MSAT,
6175 fee_proportional_millionths: 0,
6176 excess_data: Vec::new()
6178 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6181 // Now ensure the route flows simply over nodes 1 and 4 to 6.
6182 let route_params = RouteParameters::from_payment_params_and_value(
6183 payment_params, 10_000);
6184 let route = get_route(&our_id, &route_params, &network.read_only(), None,
6185 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6186 assert_eq!(route.paths.len(), 1);
6187 assert_eq!(route.paths[0].hops.len(), 3);
6189 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6190 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6191 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6192 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6193 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6194 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6196 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6197 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6198 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6199 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6200 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6201 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6203 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6204 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6205 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6206 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6207 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6208 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6214 fn exact_fee_liquidity_limit() {
6215 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6216 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6217 // we calculated fees on a higher value, resulting in us ignoring such paths.
6218 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6219 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6220 let scorer = ln_test_utils::TestScorer::new();
6221 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6222 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6223 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6225 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6227 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6228 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6229 short_channel_id: 2,
6232 cltv_expiry_delta: 0,
6233 htlc_minimum_msat: 0,
6234 htlc_maximum_msat: 85_000,
6236 fee_proportional_millionths: 0,
6237 excess_data: Vec::new()
6240 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6241 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6242 short_channel_id: 12,
6245 cltv_expiry_delta: (4 << 4) | 1,
6246 htlc_minimum_msat: 0,
6247 htlc_maximum_msat: 270_000,
6249 fee_proportional_millionths: 1000000,
6250 excess_data: Vec::new()
6254 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6255 // 200% fee charged channel 13 in the 1-to-2 direction.
6256 let mut route_params = RouteParameters::from_payment_params_and_value(
6257 payment_params, 90_000);
6258 route_params.max_total_routing_fee_msat = Some(90_000*2);
6259 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6260 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6261 assert_eq!(route.paths.len(), 1);
6262 assert_eq!(route.paths[0].hops.len(), 2);
6264 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6265 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6266 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6267 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6268 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6269 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6271 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6272 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6273 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6274 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6275 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6276 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6281 fn htlc_max_reduction_below_min() {
6282 // Test that if, while walking the graph, we reduce the value being sent to meet an
6283 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6284 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6285 // resulting in us thinking there is no possible path, even if other paths exist.
6286 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6287 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6288 let scorer = ln_test_utils::TestScorer::new();
6289 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6290 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6291 let config = UserConfig::default();
6292 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6293 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6296 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6297 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6298 // then try to send 90_000.
6299 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6300 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6301 short_channel_id: 2,
6304 cltv_expiry_delta: 0,
6305 htlc_minimum_msat: 0,
6306 htlc_maximum_msat: 80_000,
6308 fee_proportional_millionths: 0,
6309 excess_data: Vec::new()
6311 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6312 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6313 short_channel_id: 4,
6316 cltv_expiry_delta: (4 << 4) | 1,
6317 htlc_minimum_msat: 90_000,
6318 htlc_maximum_msat: MAX_VALUE_MSAT,
6320 fee_proportional_millionths: 0,
6321 excess_data: Vec::new()
6325 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6326 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6327 // expensive) channels 12-13 path.
6328 let mut route_params = RouteParameters::from_payment_params_and_value(
6329 payment_params, 90_000);
6330 route_params.max_total_routing_fee_msat = Some(90_000*2);
6331 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6332 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6333 assert_eq!(route.paths.len(), 1);
6334 assert_eq!(route.paths[0].hops.len(), 2);
6336 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6337 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6338 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6339 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6340 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6341 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6343 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6344 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6345 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6346 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6347 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6348 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6353 fn multiple_direct_first_hops() {
6354 // Previously we'd only ever considered one first hop path per counterparty.
6355 // However, as we don't restrict users to one channel per peer, we really need to support
6356 // looking at all first hop paths.
6357 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6358 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6359 // route over multiple channels with the same first hop.
6360 let secp_ctx = Secp256k1::new();
6361 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6362 let logger = Arc::new(ln_test_utils::TestLogger::new());
6363 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6364 let scorer = ln_test_utils::TestScorer::new();
6365 let config = UserConfig::default();
6366 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6367 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6369 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6370 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6373 let route_params = RouteParameters::from_payment_params_and_value(
6374 payment_params.clone(), 100_000);
6375 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6376 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6377 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6378 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6379 assert_eq!(route.paths.len(), 1);
6380 assert_eq!(route.paths[0].hops.len(), 1);
6382 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6383 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6384 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6387 let route_params = RouteParameters::from_payment_params_and_value(
6388 payment_params.clone(), 100_000);
6389 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6390 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6391 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6392 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6393 assert_eq!(route.paths.len(), 2);
6394 assert_eq!(route.paths[0].hops.len(), 1);
6395 assert_eq!(route.paths[1].hops.len(), 1);
6397 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6398 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6400 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6401 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6403 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6404 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6408 // If we have a bunch of outbound channels to the same node, where most are not
6409 // sufficient to pay the full payment, but one is, we should default to just using the
6410 // one single channel that has sufficient balance, avoiding MPP.
6412 // If we have several options above the 3xpayment value threshold, we should pick the
6413 // smallest of them, avoiding further fragmenting our available outbound balance to
6415 let route_params = RouteParameters::from_payment_params_and_value(
6416 payment_params, 100_000);
6417 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6418 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6419 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6420 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6421 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6422 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6423 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6424 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6425 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6426 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6427 assert_eq!(route.paths.len(), 1);
6428 assert_eq!(route.paths[0].hops.len(), 1);
6430 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6431 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6432 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6437 fn prefers_shorter_route_with_higher_fees() {
6438 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6439 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6440 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6442 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6443 let scorer = ln_test_utils::TestScorer::new();
6444 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6445 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6446 let route_params = RouteParameters::from_payment_params_and_value(
6447 payment_params.clone(), 100);
6448 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6449 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6450 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6452 assert_eq!(route.get_total_fees(), 100);
6453 assert_eq!(route.get_total_amount(), 100);
6454 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6456 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6457 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6458 let scorer = FixedPenaltyScorer::with_penalty(100);
6459 let route_params = RouteParameters::from_payment_params_and_value(
6460 payment_params, 100);
6461 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6462 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6463 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6465 assert_eq!(route.get_total_fees(), 300);
6466 assert_eq!(route.get_total_amount(), 100);
6467 assert_eq!(path, vec![2, 4, 7, 10]);
6470 struct BadChannelScorer {
6471 short_channel_id: u64,
6475 impl Writeable for BadChannelScorer {
6476 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6478 impl ScoreLookUp for BadChannelScorer {
6479 type ScoreParams = ();
6480 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6481 if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value() } else { 0 }
6485 struct BadNodeScorer {
6490 impl Writeable for BadNodeScorer {
6491 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6494 impl ScoreLookUp for BadNodeScorer {
6495 type ScoreParams = ();
6496 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6497 if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6502 fn avoids_routing_through_bad_channels_and_nodes() {
6503 let (secp_ctx, network, _, _, logger) = build_graph();
6504 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6505 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6506 let network_graph = network.read_only();
6508 // A path to nodes[6] exists when no penalties are applied to any channel.
6509 let scorer = ln_test_utils::TestScorer::new();
6510 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6511 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6512 let route_params = RouteParameters::from_payment_params_and_value(
6513 payment_params, 100);
6514 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6515 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6516 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6518 assert_eq!(route.get_total_fees(), 100);
6519 assert_eq!(route.get_total_amount(), 100);
6520 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6522 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6523 let scorer = BadChannelScorer { short_channel_id: 6 };
6524 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6525 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6526 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6528 assert_eq!(route.get_total_fees(), 300);
6529 assert_eq!(route.get_total_amount(), 100);
6530 assert_eq!(path, vec![2, 4, 7, 10]);
6532 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6533 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6534 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6535 &scorer, &Default::default(), &random_seed_bytes) {
6536 Err(LightningError { err, .. } ) => {
6537 assert_eq!(err, "Failed to find a path to the given destination");
6539 Ok(_) => panic!("Expected error"),
6544 fn total_fees_single_path() {
6546 paths: vec![Path { hops: vec![
6548 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6549 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6550 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6553 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6554 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6555 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6558 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6559 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6560 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6562 ], blinded_tail: None }],
6566 assert_eq!(route.get_total_fees(), 250);
6567 assert_eq!(route.get_total_amount(), 225);
6571 fn total_fees_multi_path() {
6573 paths: vec![Path { hops: vec![
6575 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6576 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6577 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6580 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6581 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6582 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6584 ], blinded_tail: None }, Path { hops: vec![
6586 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6587 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6588 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6591 pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6592 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6593 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6595 ], blinded_tail: None }],
6599 assert_eq!(route.get_total_fees(), 200);
6600 assert_eq!(route.get_total_amount(), 300);
6604 fn total_empty_route_no_panic() {
6605 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6606 // would both panic if the route was completely empty. We test to ensure they return 0
6607 // here, even though its somewhat nonsensical as a route.
6608 let route = Route { paths: Vec::new(), route_params: None };
6610 assert_eq!(route.get_total_fees(), 0);
6611 assert_eq!(route.get_total_amount(), 0);
6615 fn limits_total_cltv_delta() {
6616 let (secp_ctx, network, _, _, logger) = build_graph();
6617 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6618 let network_graph = network.read_only();
6620 let scorer = ln_test_utils::TestScorer::new();
6622 // Make sure that generally there is at least one route available
6623 let feasible_max_total_cltv_delta = 1008;
6624 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6625 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6626 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6627 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6628 let route_params = RouteParameters::from_payment_params_and_value(
6629 feasible_payment_params, 100);
6630 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6631 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6632 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6633 assert_ne!(path.len(), 0);
6635 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6636 let fail_max_total_cltv_delta = 23;
6637 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6638 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6639 let route_params = RouteParameters::from_payment_params_and_value(
6640 fail_payment_params, 100);
6641 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6642 &Default::default(), &random_seed_bytes)
6644 Err(LightningError { err, .. } ) => {
6645 assert_eq!(err, "Failed to find a path to the given destination");
6647 Ok(_) => panic!("Expected error"),
6652 fn avoids_recently_failed_paths() {
6653 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6654 // randomly inserting channels into it until we can't find a route anymore.
6655 let (secp_ctx, network, _, _, logger) = build_graph();
6656 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6657 let network_graph = network.read_only();
6659 let scorer = ln_test_utils::TestScorer::new();
6660 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6661 .with_max_path_count(1);
6662 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6663 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6665 // We should be able to find a route initially, and then after we fail a few random
6666 // channels eventually we won't be able to any longer.
6667 let route_params = RouteParameters::from_payment_params_and_value(
6668 payment_params.clone(), 100);
6669 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6670 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6672 let route_params = RouteParameters::from_payment_params_and_value(
6673 payment_params.clone(), 100);
6674 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6675 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6677 for chan in route.paths[0].hops.iter() {
6678 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6680 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6681 % route.paths[0].hops.len();
6682 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6688 fn limits_path_length() {
6689 let (secp_ctx, network, _, _, logger) = build_line_graph();
6690 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6691 let network_graph = network.read_only();
6693 let scorer = ln_test_utils::TestScorer::new();
6694 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6695 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6697 // First check we can actually create a long route on this graph.
6698 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6699 let route_params = RouteParameters::from_payment_params_and_value(
6700 feasible_payment_params, 100);
6701 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6702 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6703 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6704 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6706 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6707 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6708 let route_params = RouteParameters::from_payment_params_and_value(
6709 fail_payment_params, 100);
6710 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6711 &Default::default(), &random_seed_bytes)
6713 Err(LightningError { err, .. } ) => {
6714 assert_eq!(err, "Failed to find a path to the given destination");
6716 Ok(_) => panic!("Expected error"),
6721 fn adds_and_limits_cltv_offset() {
6722 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6723 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6725 let scorer = ln_test_utils::TestScorer::new();
6727 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6728 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6729 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6730 let route_params = RouteParameters::from_payment_params_and_value(
6731 payment_params.clone(), 100);
6732 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6733 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6734 assert_eq!(route.paths.len(), 1);
6736 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6738 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6739 let mut route_default = route.clone();
6740 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6741 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6742 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6743 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6744 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6746 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6747 let mut route_limited = route.clone();
6748 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6749 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6750 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6751 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6752 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6756 fn adds_plausible_cltv_offset() {
6757 let (secp_ctx, network, _, _, logger) = build_graph();
6758 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6759 let network_graph = network.read_only();
6760 let network_nodes = network_graph.nodes();
6761 let network_channels = network_graph.channels();
6762 let scorer = ln_test_utils::TestScorer::new();
6763 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6764 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6765 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6767 let route_params = RouteParameters::from_payment_params_and_value(
6768 payment_params.clone(), 100);
6769 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6770 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6771 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6773 let mut path_plausibility = vec![];
6775 for p in route.paths {
6776 // 1. Select random observation point
6777 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6778 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6780 prng.process_in_place(&mut random_bytes);
6781 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6782 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6784 // 2. Calculate what CLTV expiry delta we would observe there
6785 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6787 // 3. Starting from the observation point, find candidate paths
6788 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6789 candidates.push_back((observation_point, vec![]));
6791 let mut found_plausible_candidate = false;
6793 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6794 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6795 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6796 found_plausible_candidate = true;
6797 break 'candidate_loop;
6801 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6802 for channel_id in &cur_node.channels {
6803 if let Some(channel_info) = network_channels.get(&channel_id) {
6804 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6805 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6806 if cur_path_cltv_deltas.iter().sum::<u32>()
6807 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6808 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6809 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6810 candidates.push_back((*next_id, new_path_cltv_deltas));
6818 path_plausibility.push(found_plausible_candidate);
6820 assert!(path_plausibility.iter().all(|x| *x));
6824 fn builds_correct_path_from_hops() {
6825 let (secp_ctx, network, _, _, logger) = build_graph();
6826 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6827 let network_graph = network.read_only();
6829 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6830 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6832 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6833 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6834 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6835 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6836 Arc::clone(&logger), &random_seed_bytes).unwrap();
6837 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6838 assert_eq!(hops.len(), route.paths[0].hops.len());
6839 for (idx, hop_pubkey) in hops.iter().enumerate() {
6840 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6845 fn avoids_saturating_channels() {
6846 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6847 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6848 let decay_params = ProbabilisticScoringDecayParameters::default();
6849 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6851 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6852 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6853 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6854 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6855 short_channel_id: 4,
6858 cltv_expiry_delta: (4 << 4) | 1,
6859 htlc_minimum_msat: 0,
6860 htlc_maximum_msat: 250_000_000,
6862 fee_proportional_millionths: 0,
6863 excess_data: Vec::new()
6865 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6866 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6867 short_channel_id: 13,
6870 cltv_expiry_delta: (13 << 4) | 1,
6871 htlc_minimum_msat: 0,
6872 htlc_maximum_msat: 250_000_000,
6874 fee_proportional_millionths: 0,
6875 excess_data: Vec::new()
6878 let config = UserConfig::default();
6879 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6880 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6882 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6883 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6884 // 100,000 sats is less than the available liquidity on each channel, set above.
6885 let route_params = RouteParameters::from_payment_params_and_value(
6886 payment_params, 100_000_000);
6887 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6888 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6889 assert_eq!(route.paths.len(), 2);
6890 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6891 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6894 #[cfg(not(feature = "no-std"))]
6895 pub(super) fn random_init_seed() -> u64 {
6896 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6897 use core::hash::{BuildHasher, Hasher};
6898 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6899 println!("Using seed of {}", seed);
6904 #[cfg(not(feature = "no-std"))]
6905 fn generate_routes() {
6906 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6908 let logger = ln_test_utils::TestLogger::new();
6909 let graph = match super::bench_utils::read_network_graph(&logger) {
6917 let params = ProbabilisticScoringFeeParameters::default();
6918 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6919 let features = super::Bolt11InvoiceFeatures::empty();
6921 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6925 #[cfg(not(feature = "no-std"))]
6926 fn generate_routes_mpp() {
6927 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6929 let logger = ln_test_utils::TestLogger::new();
6930 let graph = match super::bench_utils::read_network_graph(&logger) {
6938 let params = ProbabilisticScoringFeeParameters::default();
6939 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6940 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6942 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6946 #[cfg(not(feature = "no-std"))]
6947 fn generate_large_mpp_routes() {
6948 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6950 let logger = ln_test_utils::TestLogger::new();
6951 let graph = match super::bench_utils::read_network_graph(&logger) {
6959 let params = ProbabilisticScoringFeeParameters::default();
6960 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6961 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6963 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6967 fn honors_manual_penalties() {
6968 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6969 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6971 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6972 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6974 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6975 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6977 // First check set manual penalties are returned by the scorer.
6978 let usage = ChannelUsage {
6980 inflight_htlc_msat: 0,
6981 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6983 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6984 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6985 let network_graph = network_graph.read_only();
6986 let channels = network_graph.channels();
6987 let channel = channels.get(&5).unwrap();
6988 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
6989 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop {
6991 short_channel_id: 5,
6993 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
6995 // Then check we can get a normal route
6996 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6997 let route_params = RouteParameters::from_payment_params_and_value(
6998 payment_params, 100);
6999 let route = get_route(&our_id, &route_params, &network_graph, None,
7000 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7001 assert!(route.is_ok());
7003 // Then check that we can't get a route if we ban an intermediate node.
7004 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7005 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7006 assert!(route.is_err());
7008 // Finally make sure we can route again, when we remove the ban.
7009 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7010 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7011 assert!(route.is_ok());
7015 fn abide_by_route_hint_max_htlc() {
7016 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7017 // params in the final route.
7018 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7019 let netgraph = network_graph.read_only();
7020 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7021 let scorer = ln_test_utils::TestScorer::new();
7022 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7023 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7024 let config = UserConfig::default();
7026 let max_htlc_msat = 50_000;
7027 let route_hint_1 = RouteHint(vec![RouteHintHop {
7028 src_node_id: nodes[2],
7029 short_channel_id: 42,
7032 proportional_millionths: 0,
7034 cltv_expiry_delta: 10,
7035 htlc_minimum_msat: None,
7036 htlc_maximum_msat: Some(max_htlc_msat),
7038 let dest_node_id = ln_test_utils::pubkey(42);
7039 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7040 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7041 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7044 // Make sure we'll error if our route hints don't have enough liquidity according to their
7045 // htlc_maximum_msat.
7046 let mut route_params = RouteParameters::from_payment_params_and_value(
7047 payment_params, max_htlc_msat + 1);
7048 route_params.max_total_routing_fee_msat = None;
7049 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7050 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7053 assert_eq!(err, "Failed to find a sufficient route to the given destination");
7054 } else { panic!(); }
7056 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7057 let mut route_hint_2 = route_hint_1.clone();
7058 route_hint_2.0[0].short_channel_id = 43;
7059 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7060 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7061 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7063 let mut route_params = RouteParameters::from_payment_params_and_value(
7064 payment_params, max_htlc_msat + 1);
7065 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7066 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7067 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7068 assert_eq!(route.paths.len(), 2);
7069 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7070 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7074 fn direct_channel_to_hints_with_max_htlc() {
7075 // Check that if we have a first hop channel peer that's connected to multiple provided route
7076 // hints, that we properly split the payment between the route hints if needed.
7077 let logger = Arc::new(ln_test_utils::TestLogger::new());
7078 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7079 let scorer = ln_test_utils::TestScorer::new();
7080 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7081 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7082 let config = UserConfig::default();
7084 let our_node_id = ln_test_utils::pubkey(42);
7085 let intermed_node_id = ln_test_utils::pubkey(43);
7086 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7088 let amt_msat = 900_000;
7089 let max_htlc_msat = 500_000;
7090 let route_hint_1 = RouteHint(vec![RouteHintHop {
7091 src_node_id: intermed_node_id,
7092 short_channel_id: 44,
7095 proportional_millionths: 0,
7097 cltv_expiry_delta: 10,
7098 htlc_minimum_msat: None,
7099 htlc_maximum_msat: Some(max_htlc_msat),
7101 src_node_id: intermed_node_id,
7102 short_channel_id: 45,
7105 proportional_millionths: 0,
7107 cltv_expiry_delta: 10,
7108 htlc_minimum_msat: None,
7109 // Check that later route hint max htlcs don't override earlier ones
7110 htlc_maximum_msat: Some(max_htlc_msat - 50),
7112 let mut route_hint_2 = route_hint_1.clone();
7113 route_hint_2.0[0].short_channel_id = 46;
7114 route_hint_2.0[1].short_channel_id = 47;
7115 let dest_node_id = ln_test_utils::pubkey(44);
7116 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7117 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7118 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7121 let route_params = RouteParameters::from_payment_params_and_value(
7122 payment_params, amt_msat);
7123 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7124 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7125 &Default::default(), &random_seed_bytes).unwrap();
7126 assert_eq!(route.paths.len(), 2);
7127 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7128 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7129 assert_eq!(route.get_total_amount(), amt_msat);
7131 // Re-run but with two first hop channels connected to the same route hint peers that must be
7133 let first_hops = vec![
7134 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7135 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7137 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7138 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7139 &Default::default(), &random_seed_bytes).unwrap();
7140 assert_eq!(route.paths.len(), 2);
7141 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7142 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7143 assert_eq!(route.get_total_amount(), amt_msat);
7145 // Make sure this works for blinded route hints.
7146 let blinded_path = BlindedPath {
7147 introduction_node_id: intermed_node_id,
7148 blinding_point: ln_test_utils::pubkey(42),
7150 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7151 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7154 let blinded_payinfo = BlindedPayInfo {
7156 fee_proportional_millionths: 0,
7157 htlc_minimum_msat: 1,
7158 htlc_maximum_msat: max_htlc_msat,
7159 cltv_expiry_delta: 10,
7160 features: BlindedHopFeatures::empty(),
7162 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7163 let payment_params = PaymentParameters::blinded(vec![
7164 (blinded_payinfo.clone(), blinded_path.clone()),
7165 (blinded_payinfo.clone(), blinded_path.clone())])
7166 .with_bolt12_features(bolt12_features).unwrap();
7167 let route_params = RouteParameters::from_payment_params_and_value(
7168 payment_params, amt_msat);
7169 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7170 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7171 &Default::default(), &random_seed_bytes).unwrap();
7172 assert_eq!(route.paths.len(), 2);
7173 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7174 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7175 assert_eq!(route.get_total_amount(), amt_msat);
7179 fn blinded_route_ser() {
7180 let blinded_path_1 = BlindedPath {
7181 introduction_node_id: ln_test_utils::pubkey(42),
7182 blinding_point: ln_test_utils::pubkey(43),
7184 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7185 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7188 let blinded_path_2 = BlindedPath {
7189 introduction_node_id: ln_test_utils::pubkey(46),
7190 blinding_point: ln_test_utils::pubkey(47),
7192 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7193 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7196 // (De)serialize a Route with 1 blinded path out of two total paths.
7197 let mut route = Route { paths: vec![Path {
7198 hops: vec![RouteHop {
7199 pubkey: ln_test_utils::pubkey(50),
7200 node_features: NodeFeatures::empty(),
7201 short_channel_id: 42,
7202 channel_features: ChannelFeatures::empty(),
7204 cltv_expiry_delta: 0,
7205 maybe_announced_channel: true,
7207 blinded_tail: Some(BlindedTail {
7208 hops: blinded_path_1.blinded_hops,
7209 blinding_point: blinded_path_1.blinding_point,
7210 excess_final_cltv_expiry_delta: 40,
7211 final_value_msat: 100,
7213 hops: vec![RouteHop {
7214 pubkey: ln_test_utils::pubkey(51),
7215 node_features: NodeFeatures::empty(),
7216 short_channel_id: 43,
7217 channel_features: ChannelFeatures::empty(),
7219 cltv_expiry_delta: 0,
7220 maybe_announced_channel: true,
7221 }], blinded_tail: None }],
7224 let encoded_route = route.encode();
7225 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7226 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7227 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7229 // (De)serialize a Route with two paths, each containing a blinded tail.
7230 route.paths[1].blinded_tail = Some(BlindedTail {
7231 hops: blinded_path_2.blinded_hops,
7232 blinding_point: blinded_path_2.blinding_point,
7233 excess_final_cltv_expiry_delta: 41,
7234 final_value_msat: 101,
7236 let encoded_route = route.encode();
7237 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7238 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7239 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7243 fn blinded_path_inflight_processing() {
7244 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7245 // account for the blinded tail's final amount_msat.
7246 let mut inflight_htlcs = InFlightHtlcs::new();
7247 let blinded_path = BlindedPath {
7248 introduction_node_id: ln_test_utils::pubkey(43),
7249 blinding_point: ln_test_utils::pubkey(48),
7250 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7253 hops: vec![RouteHop {
7254 pubkey: ln_test_utils::pubkey(42),
7255 node_features: NodeFeatures::empty(),
7256 short_channel_id: 42,
7257 channel_features: ChannelFeatures::empty(),
7259 cltv_expiry_delta: 0,
7260 maybe_announced_channel: false,
7263 pubkey: blinded_path.introduction_node_id,
7264 node_features: NodeFeatures::empty(),
7265 short_channel_id: 43,
7266 channel_features: ChannelFeatures::empty(),
7268 cltv_expiry_delta: 0,
7269 maybe_announced_channel: false,
7271 blinded_tail: Some(BlindedTail {
7272 hops: blinded_path.blinded_hops,
7273 blinding_point: blinded_path.blinding_point,
7274 excess_final_cltv_expiry_delta: 0,
7275 final_value_msat: 200,
7278 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7279 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7280 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7284 fn blinded_path_cltv_shadow_offset() {
7285 // Make sure we add a shadow offset when sending to blinded paths.
7286 let blinded_path = BlindedPath {
7287 introduction_node_id: ln_test_utils::pubkey(43),
7288 blinding_point: ln_test_utils::pubkey(44),
7290 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7291 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7294 let mut route = Route { paths: vec![Path {
7295 hops: vec![RouteHop {
7296 pubkey: ln_test_utils::pubkey(42),
7297 node_features: NodeFeatures::empty(),
7298 short_channel_id: 42,
7299 channel_features: ChannelFeatures::empty(),
7301 cltv_expiry_delta: 0,
7302 maybe_announced_channel: false,
7305 pubkey: blinded_path.introduction_node_id,
7306 node_features: NodeFeatures::empty(),
7307 short_channel_id: 43,
7308 channel_features: ChannelFeatures::empty(),
7310 cltv_expiry_delta: 0,
7311 maybe_announced_channel: false,
7314 blinded_tail: Some(BlindedTail {
7315 hops: blinded_path.blinded_hops,
7316 blinding_point: blinded_path.blinding_point,
7317 excess_final_cltv_expiry_delta: 0,
7318 final_value_msat: 200,
7320 }], route_params: None};
7322 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7323 let (_, network_graph, _, _, _) = build_line_graph();
7324 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7325 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7326 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7330 fn simple_blinded_route_hints() {
7331 do_simple_blinded_route_hints(1);
7332 do_simple_blinded_route_hints(2);
7333 do_simple_blinded_route_hints(3);
7336 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7337 // Check that we can generate a route to a blinded path with the expected hops.
7338 let (secp_ctx, network, _, _, logger) = build_graph();
7339 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7340 let network_graph = network.read_only();
7342 let scorer = ln_test_utils::TestScorer::new();
7343 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7344 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7346 let mut blinded_path = BlindedPath {
7347 introduction_node_id: nodes[2],
7348 blinding_point: ln_test_utils::pubkey(42),
7349 blinded_hops: Vec::with_capacity(num_blinded_hops),
7351 for i in 0..num_blinded_hops {
7352 blinded_path.blinded_hops.push(
7353 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7356 let blinded_payinfo = BlindedPayInfo {
7358 fee_proportional_millionths: 500,
7359 htlc_minimum_msat: 1000,
7360 htlc_maximum_msat: 100_000_000,
7361 cltv_expiry_delta: 15,
7362 features: BlindedHopFeatures::empty(),
7365 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7366 let route_params = RouteParameters::from_payment_params_and_value(
7367 payment_params, 1001);
7368 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7369 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7370 assert_eq!(route.paths.len(), 1);
7371 assert_eq!(route.paths[0].hops.len(), 2);
7373 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7374 assert_eq!(tail.hops, blinded_path.blinded_hops);
7375 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7376 assert_eq!(tail.final_value_msat, 1001);
7378 let final_hop = route.paths[0].hops.last().unwrap();
7379 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7380 if tail.hops.len() > 1 {
7381 assert_eq!(final_hop.fee_msat,
7382 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7383 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7385 assert_eq!(final_hop.fee_msat, 0);
7386 assert_eq!(final_hop.cltv_expiry_delta, 0);
7391 fn blinded_path_routing_errors() {
7392 // Check that we can generate a route to a blinded path with the expected hops.
7393 let (secp_ctx, network, _, _, logger) = build_graph();
7394 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7395 let network_graph = network.read_only();
7397 let scorer = ln_test_utils::TestScorer::new();
7398 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7399 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7401 let mut invalid_blinded_path = BlindedPath {
7402 introduction_node_id: nodes[2],
7403 blinding_point: ln_test_utils::pubkey(42),
7405 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7408 let blinded_payinfo = BlindedPayInfo {
7410 fee_proportional_millionths: 500,
7411 htlc_minimum_msat: 1000,
7412 htlc_maximum_msat: 100_000_000,
7413 cltv_expiry_delta: 15,
7414 features: BlindedHopFeatures::empty(),
7417 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7418 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7419 let payment_params = PaymentParameters::blinded(vec![
7420 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7421 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7422 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7423 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7424 &scorer, &Default::default(), &random_seed_bytes)
7426 Err(LightningError { err, .. }) => {
7427 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7429 _ => panic!("Expected error")
7432 invalid_blinded_path.introduction_node_id = our_id;
7433 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7434 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7435 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7436 &Default::default(), &random_seed_bytes)
7438 Err(LightningError { err, .. }) => {
7439 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7441 _ => panic!("Expected error")
7444 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7445 invalid_blinded_path.blinded_hops.clear();
7446 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7447 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7448 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7449 &Default::default(), &random_seed_bytes)
7451 Err(LightningError { err, .. }) => {
7452 assert_eq!(err, "0-hop blinded path provided");
7454 _ => panic!("Expected error")
7459 fn matching_intro_node_paths_provided() {
7460 // Check that if multiple blinded paths with the same intro node are provided in payment
7461 // parameters, we'll return the correct paths in the resulting MPP route.
7462 let (secp_ctx, network, _, _, logger) = build_graph();
7463 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7464 let network_graph = network.read_only();
7466 let scorer = ln_test_utils::TestScorer::new();
7467 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7468 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7469 let config = UserConfig::default();
7471 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7472 let blinded_path_1 = BlindedPath {
7473 introduction_node_id: nodes[2],
7474 blinding_point: ln_test_utils::pubkey(42),
7476 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7477 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7480 let blinded_payinfo_1 = BlindedPayInfo {
7482 fee_proportional_millionths: 0,
7483 htlc_minimum_msat: 0,
7484 htlc_maximum_msat: 30_000,
7485 cltv_expiry_delta: 0,
7486 features: BlindedHopFeatures::empty(),
7489 let mut blinded_path_2 = blinded_path_1.clone();
7490 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7491 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7492 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7494 let blinded_hints = vec![
7495 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7496 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7498 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7499 .with_bolt12_features(bolt12_features).unwrap();
7501 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7502 route_params.max_total_routing_fee_msat = Some(100_000);
7503 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7504 &scorer, &Default::default(), &random_seed_bytes).unwrap();
7505 assert_eq!(route.paths.len(), 2);
7506 let mut total_amount_paid_msat = 0;
7507 for path in route.paths.into_iter() {
7508 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7509 if let Some(bt) = &path.blinded_tail {
7510 assert_eq!(bt.blinding_point,
7511 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7512 .map(|(_, bp)| bp.blinding_point).unwrap());
7513 } else { panic!(); }
7514 total_amount_paid_msat += path.final_value_msat();
7516 assert_eq!(total_amount_paid_msat, 100_000);
7520 fn direct_to_intro_node() {
7521 // This previously caused a debug panic in the router when asserting
7522 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7523 // direct channels we failed to account for the fee charged for use of the blinded path.
7526 // node0 -1(1)2 - node1
7527 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7528 // doesn't account for the blinded path fee.
7530 let secp_ctx = Secp256k1::new();
7531 let logger = Arc::new(ln_test_utils::TestLogger::new());
7532 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7533 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7534 let scorer = ln_test_utils::TestScorer::new();
7535 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7536 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7538 let amt_msat = 10_000_000;
7539 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7540 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7541 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7542 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7543 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7544 short_channel_id: 1,
7547 cltv_expiry_delta: 42,
7548 htlc_minimum_msat: 1_000,
7549 htlc_maximum_msat: 10_000_000,
7551 fee_proportional_millionths: 0,
7552 excess_data: Vec::new()
7554 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7555 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7556 short_channel_id: 1,
7559 cltv_expiry_delta: 42,
7560 htlc_minimum_msat: 1_000,
7561 htlc_maximum_msat: 10_000_000,
7563 fee_proportional_millionths: 0,
7564 excess_data: Vec::new()
7566 let first_hops = vec![
7567 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7569 let blinded_path = BlindedPath {
7570 introduction_node_id: nodes[1],
7571 blinding_point: ln_test_utils::pubkey(42),
7573 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7574 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7577 let blinded_payinfo = BlindedPayInfo {
7578 fee_base_msat: 1000,
7579 fee_proportional_millionths: 0,
7580 htlc_minimum_msat: 1000,
7581 htlc_maximum_msat: MAX_VALUE_MSAT,
7582 cltv_expiry_delta: 0,
7583 features: BlindedHopFeatures::empty(),
7585 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7587 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7589 let netgraph = network_graph.read_only();
7590 let route_params = RouteParameters::from_payment_params_and_value(
7591 payment_params.clone(), amt_msat);
7592 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7593 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7594 &Default::default(), &random_seed_bytes) {
7595 assert_eq!(err, "Failed to find a path to the given destination");
7596 } else { panic!("Expected error") }
7598 // Sending an exact amount accounting for the blinded path fee works.
7599 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7600 let route_params = RouteParameters::from_payment_params_and_value(
7601 payment_params, amt_minus_blinded_path_fee);
7602 let route = get_route(&nodes[0], &route_params, &netgraph,
7603 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7604 &Default::default(), &random_seed_bytes).unwrap();
7605 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7606 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7610 fn direct_to_matching_intro_nodes() {
7611 // This previously caused us to enter `unreachable` code in the following situation:
7612 // 1. We add a route candidate for intro_node contributing a high amount
7613 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7614 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7615 // amount, and update our route candidate for intro_node for the lower amount
7616 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7617 // lower contribution amount, but fail (this was previously caused by failure to account for
7618 // blinded path fees when adding first_hop<>intro_node candidates)
7619 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7620 // candidate still thinks its path is contributing the original higher amount. This caused us
7621 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7623 let secp_ctx = Secp256k1::new();
7624 let logger = Arc::new(ln_test_utils::TestLogger::new());
7625 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7626 let scorer = ln_test_utils::TestScorer::new();
7627 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7628 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7629 let config = UserConfig::default();
7631 // Values are taken from the fuzz input that uncovered this panic.
7632 let amt_msat = 21_7020_5185_1403_2640;
7633 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7634 let first_hops = vec![
7635 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7636 18446744073709551615)];
7638 let blinded_path = BlindedPath {
7639 introduction_node_id: nodes[1],
7640 blinding_point: ln_test_utils::pubkey(42),
7642 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7643 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7646 let blinded_payinfo = BlindedPayInfo {
7647 fee_base_msat: 5046_2720,
7648 fee_proportional_millionths: 0,
7649 htlc_minimum_msat: 4503_5996_2737_0496,
7650 htlc_maximum_msat: 45_0359_9627_3704_9600,
7651 cltv_expiry_delta: 0,
7652 features: BlindedHopFeatures::empty(),
7654 let mut blinded_hints = vec![
7655 (blinded_payinfo.clone(), blinded_path.clone()),
7656 (blinded_payinfo.clone(), blinded_path.clone()),
7658 blinded_hints[1].0.fee_base_msat = 419_4304;
7659 blinded_hints[1].0.fee_proportional_millionths = 257;
7660 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7661 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7662 blinded_hints[1].0.cltv_expiry_delta = 0;
7664 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7665 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7666 .with_bolt12_features(bolt12_features).unwrap();
7668 let netgraph = network_graph.read_only();
7669 let route_params = RouteParameters::from_payment_params_and_value(
7670 payment_params, amt_msat);
7671 let route = get_route(&nodes[0], &route_params, &netgraph,
7672 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7673 &Default::default(), &random_seed_bytes).unwrap();
7674 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7675 assert_eq!(route.get_total_amount(), amt_msat);
7679 fn we_are_intro_node_candidate_hops() {
7680 // This previously led to a panic in the router because we'd generate a Path with only a
7681 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7682 // where the origin node is the intro node. We now fully disallow considering candidate hops
7683 // where the origin node is the intro node.
7684 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7685 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7686 let scorer = ln_test_utils::TestScorer::new();
7687 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7688 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7689 let config = UserConfig::default();
7691 // Values are taken from the fuzz input that uncovered this panic.
7692 let amt_msat = 21_7020_5185_1423_0019;
7694 let blinded_path = BlindedPath {
7695 introduction_node_id: our_id,
7696 blinding_point: ln_test_utils::pubkey(42),
7698 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7699 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7702 let blinded_payinfo = BlindedPayInfo {
7703 fee_base_msat: 5052_9027,
7704 fee_proportional_millionths: 0,
7705 htlc_minimum_msat: 21_7020_5185_1423_0019,
7706 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7707 cltv_expiry_delta: 0,
7708 features: BlindedHopFeatures::empty(),
7710 let mut blinded_hints = vec![
7711 (blinded_payinfo.clone(), blinded_path.clone()),
7712 (blinded_payinfo.clone(), blinded_path.clone()),
7714 blinded_hints[1].1.introduction_node_id = nodes[6];
7716 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7717 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7718 .with_bolt12_features(bolt12_features.clone()).unwrap();
7720 let netgraph = network_graph.read_only();
7721 let route_params = RouteParameters::from_payment_params_and_value(
7722 payment_params, amt_msat);
7723 if let Err(LightningError { err, .. }) = get_route(
7724 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7726 assert_eq!(err, "Failed to find a path to the given destination");
7731 fn we_are_intro_node_bp_in_final_path_fee_calc() {
7732 // This previously led to a debug panic in the router because we'd find an invalid Path with
7733 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7734 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7735 // the payment, when it was intended to only include the final value of the payment.
7736 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7737 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7738 let scorer = ln_test_utils::TestScorer::new();
7739 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7740 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7741 let config = UserConfig::default();
7743 // Values are taken from the fuzz input that uncovered this panic.
7744 let amt_msat = 21_7020_5185_1423_0019;
7746 let blinded_path = BlindedPath {
7747 introduction_node_id: our_id,
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() }
7754 let blinded_payinfo = BlindedPayInfo {
7755 fee_base_msat: 10_4425_1395,
7756 fee_proportional_millionths: 0,
7757 htlc_minimum_msat: 21_7301_9934_9094_0931,
7758 htlc_maximum_msat: 1844_6744_0737_0955_1615,
7759 cltv_expiry_delta: 0,
7760 features: BlindedHopFeatures::empty(),
7762 let mut blinded_hints = vec![
7763 (blinded_payinfo.clone(), blinded_path.clone()),
7764 (blinded_payinfo.clone(), blinded_path.clone()),
7765 (blinded_payinfo.clone(), blinded_path.clone()),
7767 blinded_hints[1].0.fee_base_msat = 5052_9027;
7768 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7769 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7771 blinded_hints[2].1.introduction_node_id = nodes[6];
7773 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7774 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7775 .with_bolt12_features(bolt12_features.clone()).unwrap();
7777 let netgraph = network_graph.read_only();
7778 let route_params = RouteParameters::from_payment_params_and_value(
7779 payment_params, amt_msat);
7780 if let Err(LightningError { err, .. }) = get_route(
7781 &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7783 assert_eq!(err, "Failed to find a path to the given destination");
7788 fn min_htlc_overpay_violates_max_htlc() {
7789 do_min_htlc_overpay_violates_max_htlc(true);
7790 do_min_htlc_overpay_violates_max_htlc(false);
7792 fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7793 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7794 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7795 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7796 // that the used liquidity for a hop was less than its available liquidity limit.
7797 let secp_ctx = Secp256k1::new();
7798 let logger = Arc::new(ln_test_utils::TestLogger::new());
7799 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7800 let scorer = ln_test_utils::TestScorer::new();
7801 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7802 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7803 let config = UserConfig::default();
7805 // Values are taken from the fuzz input that uncovered this panic.
7806 let amt_msat = 7_4009_8048;
7807 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7808 let first_hop_outbound_capacity = 2_7345_2000;
7809 let first_hops = vec![get_channel_details(
7810 Some(200), nodes[0], channelmanager::provided_init_features(&config),
7811 first_hop_outbound_capacity
7814 let base_fee = 1_6778_3453;
7815 let htlc_min = 2_5165_8240;
7816 let payment_params = if blinded_payee {
7817 let blinded_path = BlindedPath {
7818 introduction_node_id: nodes[0],
7819 blinding_point: ln_test_utils::pubkey(42),
7821 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7822 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7825 let blinded_payinfo = BlindedPayInfo {
7826 fee_base_msat: base_fee,
7827 fee_proportional_millionths: 0,
7828 htlc_minimum_msat: htlc_min,
7829 htlc_maximum_msat: htlc_min * 1000,
7830 cltv_expiry_delta: 0,
7831 features: BlindedHopFeatures::empty(),
7833 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7834 PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7835 .with_bolt12_features(bolt12_features.clone()).unwrap()
7837 let route_hint = RouteHint(vec![RouteHintHop {
7838 src_node_id: nodes[0],
7839 short_channel_id: 42,
7841 base_msat: base_fee,
7842 proportional_millionths: 0,
7844 cltv_expiry_delta: 10,
7845 htlc_minimum_msat: Some(htlc_min),
7846 htlc_maximum_msat: None,
7849 PaymentParameters::from_node_id(nodes[1], 42)
7850 .with_route_hints(vec![route_hint]).unwrap()
7851 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7854 let netgraph = network_graph.read_only();
7855 let route_params = RouteParameters::from_payment_params_and_value(
7856 payment_params, amt_msat);
7857 if let Err(LightningError { err, .. }) = get_route(
7858 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7859 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7861 assert_eq!(err, "Failed to find a path to the given destination");
7866 fn previously_used_liquidity_violates_max_htlc() {
7867 do_previously_used_liquidity_violates_max_htlc(true);
7868 do_previously_used_liquidity_violates_max_htlc(false);
7871 fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7872 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7873 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7874 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7875 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7876 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7877 let secp_ctx = Secp256k1::new();
7878 let logger = Arc::new(ln_test_utils::TestLogger::new());
7879 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7880 let scorer = ln_test_utils::TestScorer::new();
7881 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7882 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7883 let config = UserConfig::default();
7885 // Values are taken from the fuzz input that uncovered this panic.
7886 let amt_msat = 52_4288;
7887 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7888 let first_hops = vec![get_channel_details(
7889 Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7890 ), get_channel_details(
7891 Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7894 let base_fees = [0, 425_9840, 0, 0];
7895 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7896 let payment_params = if blinded_payee {
7897 let blinded_path = BlindedPath {
7898 introduction_node_id: nodes[0],
7899 blinding_point: ln_test_utils::pubkey(42),
7901 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7902 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7905 let mut blinded_hints = Vec::new();
7906 for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7907 blinded_hints.push((BlindedPayInfo {
7908 fee_base_msat: *base_fee,
7909 fee_proportional_millionths: 0,
7910 htlc_minimum_msat: *htlc_min,
7911 htlc_maximum_msat: htlc_min * 100,
7912 cltv_expiry_delta: 10,
7913 features: BlindedHopFeatures::empty(),
7914 }, blinded_path.clone()));
7916 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7917 PaymentParameters::blinded(blinded_hints.clone())
7918 .with_bolt12_features(bolt12_features.clone()).unwrap()
7920 let mut route_hints = Vec::new();
7921 for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7922 route_hints.push(RouteHint(vec![RouteHintHop {
7923 src_node_id: nodes[0],
7924 short_channel_id: 42 + idx as u64,
7926 base_msat: *base_fee,
7927 proportional_millionths: 0,
7929 cltv_expiry_delta: 10,
7930 htlc_minimum_msat: Some(*htlc_min),
7931 htlc_maximum_msat: Some(htlc_min * 100),
7934 PaymentParameters::from_node_id(nodes[1], 42)
7935 .with_route_hints(route_hints).unwrap()
7936 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7939 let netgraph = network_graph.read_only();
7940 let route_params = RouteParameters::from_payment_params_and_value(
7941 payment_params, amt_msat);
7943 let route = get_route(
7944 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7945 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7947 assert_eq!(route.paths.len(), 1);
7948 assert_eq!(route.get_total_amount(), amt_msat);
7952 fn candidate_path_min() {
7953 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7954 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7955 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7956 // would add a connecting first_hop node that did not have enough contribution amount, leading
7957 // to a debug panic upon invalid path construction.
7958 let secp_ctx = Secp256k1::new();
7959 let logger = Arc::new(ln_test_utils::TestLogger::new());
7960 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7961 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7962 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7963 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7964 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7965 let config = UserConfig::default();
7967 // Values are taken from the fuzz input that uncovered this panic.
7968 let amt_msat = 7_4009_8048;
7969 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7970 let first_hops = vec![get_channel_details(
7971 Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7974 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7975 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7976 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7977 short_channel_id: 6,
7980 cltv_expiry_delta: (6 << 4) | 0,
7981 htlc_minimum_msat: 0,
7982 htlc_maximum_msat: MAX_VALUE_MSAT,
7984 fee_proportional_millionths: 0,
7985 excess_data: Vec::new()
7987 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
7989 let htlc_min = 2_5165_8240;
7990 let blinded_hints = vec![
7992 fee_base_msat: 1_6778_3453,
7993 fee_proportional_millionths: 0,
7994 htlc_minimum_msat: htlc_min,
7995 htlc_maximum_msat: htlc_min * 100,
7996 cltv_expiry_delta: 10,
7997 features: BlindedHopFeatures::empty(),
7999 introduction_node_id: nodes[0],
8000 blinding_point: ln_test_utils::pubkey(42),
8002 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8003 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8007 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8008 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8009 .with_bolt12_features(bolt12_features.clone()).unwrap();
8010 let route_params = RouteParameters::from_payment_params_and_value(
8011 payment_params, amt_msat);
8012 let netgraph = network_graph.read_only();
8014 if let Err(LightningError { err, .. }) = get_route(
8015 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8016 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8019 assert_eq!(err, "Failed to find a path to the given destination");
8024 fn path_contribution_includes_min_htlc_overpay() {
8025 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8026 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8027 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8028 // selection, both tested here.
8029 let secp_ctx = Secp256k1::new();
8030 let logger = Arc::new(ln_test_utils::TestLogger::new());
8031 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8032 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8033 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8034 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8035 let config = UserConfig::default();
8037 // Values are taken from the fuzz input that uncovered this panic.
8038 let amt_msat = 562_0000;
8039 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8040 let first_hops = vec![
8041 get_channel_details(
8042 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8046 let htlc_mins = [49_0000, 1125_0000];
8047 let payment_params = {
8048 let blinded_path = BlindedPath {
8049 introduction_node_id: nodes[0],
8050 blinding_point: ln_test_utils::pubkey(42),
8052 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8053 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8056 let mut blinded_hints = Vec::new();
8057 for htlc_min in htlc_mins.iter() {
8058 blinded_hints.push((BlindedPayInfo {
8060 fee_proportional_millionths: 0,
8061 htlc_minimum_msat: *htlc_min,
8062 htlc_maximum_msat: *htlc_min * 100,
8063 cltv_expiry_delta: 10,
8064 features: BlindedHopFeatures::empty(),
8065 }, blinded_path.clone()));
8067 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8068 PaymentParameters::blinded(blinded_hints.clone())
8069 .with_bolt12_features(bolt12_features.clone()).unwrap()
8072 let netgraph = network_graph.read_only();
8073 let route_params = RouteParameters::from_payment_params_and_value(
8074 payment_params, amt_msat);
8075 let route = get_route(
8076 &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8077 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8080 assert_eq!(route.paths.len(), 1);
8081 assert_eq!(route.get_total_amount(), amt_msat);
8085 fn first_hop_preferred_over_hint() {
8086 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8087 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8088 let secp_ctx = Secp256k1::new();
8089 let logger = Arc::new(ln_test_utils::TestLogger::new());
8090 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8091 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8092 let scorer = ln_test_utils::TestScorer::new();
8093 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8094 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8095 let config = UserConfig::default();
8097 let amt_msat = 1_000_000;
8098 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8100 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8101 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8102 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8103 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8104 short_channel_id: 1,
8107 cltv_expiry_delta: 42,
8108 htlc_minimum_msat: 1_000,
8109 htlc_maximum_msat: 10_000_000,
8111 fee_proportional_millionths: 0,
8112 excess_data: Vec::new()
8114 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8115 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8116 short_channel_id: 1,
8119 cltv_expiry_delta: 42,
8120 htlc_minimum_msat: 1_000,
8121 htlc_maximum_msat: 10_000_000,
8123 fee_proportional_millionths: 0,
8124 excess_data: Vec::new()
8127 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8128 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8129 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8130 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8131 short_channel_id: 2,
8134 cltv_expiry_delta: 42,
8135 htlc_minimum_msat: 1_000,
8136 htlc_maximum_msat: 10_000_000,
8138 fee_proportional_millionths: 0,
8139 excess_data: Vec::new()
8141 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8142 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8143 short_channel_id: 2,
8146 cltv_expiry_delta: 42,
8147 htlc_minimum_msat: 1_000,
8148 htlc_maximum_msat: 10_000_000,
8150 fee_proportional_millionths: 0,
8151 excess_data: Vec::new()
8154 let dest_node_id = nodes[2];
8156 let route_hint = RouteHint(vec![RouteHintHop {
8157 src_node_id: our_node_id,
8158 short_channel_id: 44,
8161 proportional_millionths: 0,
8163 cltv_expiry_delta: 10,
8164 htlc_minimum_msat: None,
8165 htlc_maximum_msat: Some(5_000_000),
8168 src_node_id: nodes[0],
8169 short_channel_id: 45,
8172 proportional_millionths: 0,
8174 cltv_expiry_delta: 10,
8175 htlc_minimum_msat: None,
8176 htlc_maximum_msat: None,
8179 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8180 .with_route_hints(vec![route_hint]).unwrap()
8181 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8182 let route_params = RouteParameters::from_payment_params_and_value(
8183 payment_params, amt_msat);
8185 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8187 let first_hop = get_channel_details(Some(1), nodes[0],
8188 channelmanager::provided_init_features(&config), 999_999);
8189 let first_hops = vec![first_hop];
8191 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8192 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8193 &Default::default(), &random_seed_bytes).unwrap();
8194 assert_eq!(route.paths.len(), 1);
8195 assert_eq!(route.get_total_amount(), amt_msat);
8196 assert_eq!(route.paths[0].hops.len(), 2);
8197 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8198 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8199 assert_eq!(route.get_total_fees(), 123);
8201 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8202 // for a first hop channel.
8203 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8204 first_hop.outbound_scid_alias = Some(44);
8205 let first_hops = vec![first_hop];
8207 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8208 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8209 &Default::default(), &random_seed_bytes);
8210 assert!(route_res.is_err());
8212 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8213 // use the cheaper second hop of the route hint.
8214 let mut first_hop = get_channel_details(Some(1), nodes[0],
8215 channelmanager::provided_init_features(&config), 10_000_000);
8216 first_hop.outbound_scid_alias = Some(44);
8217 let first_hops = vec![first_hop];
8219 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8220 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8221 &Default::default(), &random_seed_bytes).unwrap();
8222 assert_eq!(route.paths.len(), 1);
8223 assert_eq!(route.get_total_amount(), amt_msat);
8224 assert_eq!(route.paths[0].hops.len(), 2);
8225 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8226 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8227 assert_eq!(route.get_total_fees(), 123);
8231 fn allow_us_being_first_hint() {
8232 // Check that we consider a route hint even if we are the src of the first hop.
8233 let secp_ctx = Secp256k1::new();
8234 let logger = Arc::new(ln_test_utils::TestLogger::new());
8235 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8236 let scorer = ln_test_utils::TestScorer::new();
8237 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8238 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8239 let config = UserConfig::default();
8241 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8243 let amt_msat = 1_000_000;
8244 let dest_node_id = nodes[1];
8246 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8247 let first_hops = vec![first_hop];
8249 let route_hint = RouteHint(vec![RouteHintHop {
8250 src_node_id: our_node_id,
8251 short_channel_id: 44,
8254 proportional_millionths: 0,
8256 cltv_expiry_delta: 10,
8257 htlc_minimum_msat: None,
8258 htlc_maximum_msat: None,
8261 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8262 .with_route_hints(vec![route_hint]).unwrap()
8263 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8265 let route_params = RouteParameters::from_payment_params_and_value(
8266 payment_params, amt_msat);
8269 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8270 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8271 &Default::default(), &random_seed_bytes).unwrap();
8273 assert_eq!(route.paths.len(), 1);
8274 assert_eq!(route.get_total_amount(), amt_msat);
8275 assert_eq!(route.get_total_fees(), 0);
8276 assert_eq!(route.paths[0].hops.len(), 1);
8278 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8282 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
8283 pub(crate) mod bench_utils {
8286 use std::time::Duration;
8288 use bitcoin::hashes::Hash;
8289 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8291 use crate::chain::transaction::OutPoint;
8292 use crate::routing::scoring::ScoreUpdate;
8293 use crate::sign::{EntropySource, KeysManager};
8294 use crate::ln::ChannelId;
8295 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8296 use crate::ln::features::Bolt11InvoiceFeatures;
8297 use crate::routing::gossip::NetworkGraph;
8298 use crate::util::config::UserConfig;
8299 use crate::util::ser::ReadableArgs;
8300 use crate::util::test_utils::TestLogger;
8302 /// Tries to open a network graph file, or panics with a URL to fetch it.
8303 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8304 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8305 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8306 .or_else(|_| { // Fall back to guessing based on the binary location
8307 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8308 let mut path = std::env::current_exe().unwrap();
8309 path.pop(); // lightning-...
8311 path.pop(); // debug
8312 path.pop(); // target
8313 path.push("lightning");
8314 path.push("net_graph-2023-01-18.bin");
8317 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8318 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8319 let mut path = std::env::current_exe().unwrap();
8320 path.pop(); // bench...
8322 path.pop(); // debug
8323 path.pop(); // target
8324 path.pop(); // bench
8325 path.push("lightning");
8326 path.push("net_graph-2023-01-18.bin");
8329 .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");
8330 #[cfg(require_route_graph_test)]
8331 return Ok(res.unwrap());
8332 #[cfg(not(require_route_graph_test))]
8336 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8337 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8340 pub(crate) fn payer_pubkey() -> PublicKey {
8341 let secp_ctx = Secp256k1::new();
8342 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8346 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8348 channel_id: ChannelId::new_zero(),
8349 counterparty: ChannelCounterparty {
8350 features: channelmanager::provided_init_features(&UserConfig::default()),
8352 unspendable_punishment_reserve: 0,
8353 forwarding_info: None,
8354 outbound_htlc_minimum_msat: None,
8355 outbound_htlc_maximum_msat: None,
8357 funding_txo: Some(OutPoint {
8358 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8361 short_channel_id: Some(1),
8362 inbound_scid_alias: None,
8363 outbound_scid_alias: None,
8364 channel_value_satoshis: 10_000_000_000,
8366 balance_msat: 10_000_000_000,
8367 outbound_capacity_msat: 10_000_000_000,
8368 next_outbound_htlc_minimum_msat: 0,
8369 next_outbound_htlc_limit_msat: 10_000_000_000,
8370 inbound_capacity_msat: 0,
8371 unspendable_punishment_reserve: None,
8372 confirmations_required: None,
8373 confirmations: None,
8374 force_close_spend_delay: None,
8376 is_channel_ready: true,
8379 inbound_htlc_minimum_msat: None,
8380 inbound_htlc_maximum_msat: None,
8382 feerate_sat_per_1000_weight: None,
8383 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8387 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8388 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8389 starting_amount: u64, route_count: usize,
8390 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8391 let payer = payer_pubkey();
8392 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8393 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8395 let nodes = graph.read_only().nodes().clone();
8396 let mut route_endpoints = Vec::new();
8397 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8398 // with some routes we picked being un-routable.
8399 for _ in 0..route_count * 3 / 2 {
8401 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8402 let src = PublicKey::from_slice(nodes.unordered_keys()
8403 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8404 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8405 let dst = PublicKey::from_slice(nodes.unordered_keys()
8406 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8407 let params = PaymentParameters::from_node_id(dst, 42)
8408 .with_bolt11_features(features.clone()).unwrap();
8409 let first_hop = first_hop(src);
8410 let amt_msat = starting_amount + seed % 1_000_000;
8411 let route_params = RouteParameters::from_payment_params_and_value(
8412 params.clone(), amt_msat);
8414 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8415 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8417 // ...and seed the scorer with success and failure data...
8418 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8419 let mut score_amt = seed % 1_000_000_000;
8421 // Generate fail/success paths for a wider range of potential amounts with
8422 // MPP enabled to give us a chance to apply penalties for more potential
8424 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8425 let params = PaymentParameters::from_node_id(dst, 42)
8426 .with_bolt11_features(mpp_features).unwrap();
8427 let route_params = RouteParameters::from_payment_params_and_value(
8428 params.clone(), score_amt);
8429 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8430 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8431 &random_seed_bytes);
8432 if let Ok(route) = route_res {
8433 for path in route.paths {
8434 if seed & 0x80 == 0 {
8435 scorer.payment_path_successful(&path, Duration::ZERO);
8437 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8438 scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8440 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8444 // If we couldn't find a path with a higer amount, reduce and try again.
8448 route_endpoints.push((first_hop, params, amt_msat));
8454 // Because we've changed channel scores, it's possible we'll take different routes to the
8455 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8456 // requires a too-high CLTV delta.
8457 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8458 let route_params = RouteParameters::from_payment_params_and_value(
8459 params.clone(), *amt_msat);
8460 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8461 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8463 route_endpoints.truncate(route_count);
8464 assert_eq!(route_endpoints.len(), route_count);
8472 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8473 use crate::sign::{EntropySource, KeysManager};
8474 use crate::ln::channelmanager;
8475 use crate::ln::features::Bolt11InvoiceFeatures;
8476 use crate::routing::gossip::NetworkGraph;
8477 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8478 use crate::util::config::UserConfig;
8479 use crate::util::logger::{Logger, Record};
8480 use crate::util::test_utils::TestLogger;
8482 use criterion::Criterion;
8484 struct DummyLogger {}
8485 impl Logger for DummyLogger {
8486 fn log(&self, _record: Record) {}
8489 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8490 let logger = TestLogger::new();
8491 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8492 let scorer = FixedPenaltyScorer::with_penalty(0);
8493 generate_routes(bench, &network_graph, scorer, &Default::default(),
8494 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8497 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8498 let logger = TestLogger::new();
8499 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8500 let scorer = FixedPenaltyScorer::with_penalty(0);
8501 generate_routes(bench, &network_graph, scorer, &Default::default(),
8502 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8503 "generate_mpp_routes_with_zero_penalty_scorer");
8506 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8507 let logger = TestLogger::new();
8508 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8509 let params = ProbabilisticScoringFeeParameters::default();
8510 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8511 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
8512 "generate_routes_with_probabilistic_scorer");
8515 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8516 let logger = TestLogger::new();
8517 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8518 let params = ProbabilisticScoringFeeParameters::default();
8519 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8520 generate_routes(bench, &network_graph, scorer, ¶ms,
8521 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8522 "generate_mpp_routes_with_probabilistic_scorer");
8525 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8526 let logger = TestLogger::new();
8527 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8528 let params = ProbabilisticScoringFeeParameters::default();
8529 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8530 generate_routes(bench, &network_graph, scorer, ¶ms,
8531 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8532 "generate_large_mpp_routes_with_probabilistic_scorer");
8535 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8536 let logger = TestLogger::new();
8537 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8538 let mut params = ProbabilisticScoringFeeParameters::default();
8539 params.linear_success_probability = false;
8540 let scorer = ProbabilisticScorer::new(
8541 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8542 generate_routes(bench, &network_graph, scorer, ¶ms,
8543 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8544 "generate_routes_with_nonlinear_probabilistic_scorer");
8547 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8548 let logger = TestLogger::new();
8549 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8550 let mut params = ProbabilisticScoringFeeParameters::default();
8551 params.linear_success_probability = false;
8552 let scorer = ProbabilisticScorer::new(
8553 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8554 generate_routes(bench, &network_graph, scorer, ¶ms,
8555 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8556 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8559 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8560 let logger = TestLogger::new();
8561 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8562 let mut params = ProbabilisticScoringFeeParameters::default();
8563 params.linear_success_probability = false;
8564 let scorer = ProbabilisticScorer::new(
8565 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8566 generate_routes(bench, &network_graph, scorer, ¶ms,
8567 channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8568 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8571 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8572 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8573 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8574 bench_name: &'static str,
8576 let payer = bench_utils::payer_pubkey();
8577 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8578 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8580 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8581 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8583 // ...then benchmark finding paths between the nodes we learned.
8585 bench.bench_function(bench_name, |b| b.iter(|| {
8586 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8587 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8588 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8589 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());