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).into_inner();
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>;
93 /// Finds a [`Route`] for a payment between the given `payer` and a payee.
95 /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
96 /// and [`RouteParameters::final_value_msat`], respectively.
98 /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
100 fn find_route_with_id(
101 &self, payer: &PublicKey, route_params: &RouteParameters,
102 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
103 _payment_hash: PaymentHash, _payment_id: PaymentId
104 ) -> Result<Route, LightningError> {
105 self.find_route(payer, route_params, first_hops, inflight_htlcs)
109 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
111 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
114 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
115 pub struct ScorerAccountingForInFlightHtlcs<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> {
117 // Maps a channel's short channel id and its direction to the liquidity used up.
118 inflight_htlcs: &'a InFlightHtlcs,
120 impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
121 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
122 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
123 ScorerAccountingForInFlightHtlcs {
131 impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> Writeable for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
132 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
135 impl<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
136 type ScoreParams = Sc::ScoreParams;
137 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
138 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
139 source, target, short_channel_id
141 let usage = ChannelUsage {
142 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
146 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
148 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
153 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
154 /// in-use channel liquidity.
156 pub struct InFlightHtlcs(
157 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
158 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
159 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
161 HashMap<(u64, bool), u64>
165 /// Constructs an empty `InFlightHtlcs`.
166 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
168 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
169 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
170 if path.hops.is_empty() { return };
172 let mut cumulative_msat = 0;
173 if let Some(tail) = &path.blinded_tail {
174 cumulative_msat += tail.final_value_msat;
177 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
178 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
179 // the router excludes the payer node. In the following lines, the payer's information is
180 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
181 // in our sliding window of two.
182 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
183 .map(|hop| hop.pubkey)
184 .chain(core::iter::once(payer_node_id));
186 // Taking the reversed vector from above, we zip it with just the reversed hops list to
187 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
188 // the total amount sent.
189 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
190 cumulative_msat += next_hop.fee_msat;
192 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
193 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
194 .or_insert(cumulative_msat);
198 /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
200 pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
202 .entry((channel_scid, source < target))
203 .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
204 .or_insert(used_msat);
207 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
209 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
210 self.0.get(&(channel_scid, source < target)).map(|v| *v)
214 impl Writeable for InFlightHtlcs {
215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
218 impl Readable for InFlightHtlcs {
219 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
220 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
221 Ok(Self(infight_map))
225 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
226 /// that leads to it.
227 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
228 pub struct RouteHop {
229 /// The node_id of the node at this hop.
230 pub pubkey: PublicKey,
231 /// The node_announcement features of the node at this hop. For the last hop, these may be
232 /// amended to match the features present in the invoice this node generated.
233 pub node_features: NodeFeatures,
234 /// The channel that should be used from the previous hop to reach this node.
235 pub short_channel_id: u64,
236 /// The channel_announcement features of the channel that should be used from the previous hop
237 /// to reach this node.
238 pub channel_features: ChannelFeatures,
239 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
240 /// If this is the last hop in [`Path::hops`]:
241 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
242 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
244 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
246 /// The CLTV delta added for this hop.
247 /// If this is the last hop in [`Path::hops`]:
248 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
249 /// * otherwise, this is the CLTV delta expected at the destination
251 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
252 pub cltv_expiry_delta: u32,
253 /// Indicates whether this hop is possibly announced in the public network graph.
255 /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
256 /// either know for sure it's announced in the public graph, or if any public channels exist
257 /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
258 /// the channel to be unannounced.
260 /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
261 pub maybe_announced_channel: bool,
264 impl_writeable_tlv_based!(RouteHop, {
265 (0, pubkey, required),
266 (1, maybe_announced_channel, (default_value, true)),
267 (2, node_features, required),
268 (4, short_channel_id, required),
269 (6, channel_features, required),
270 (8, fee_msat, required),
271 (10, cltv_expiry_delta, required),
274 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
275 /// their [`Bolt12Invoice`].
277 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
278 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
279 pub struct BlindedTail {
280 /// The hops of the [`BlindedPath`] provided by the recipient.
282 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
283 pub hops: Vec<BlindedHop>,
284 /// The blinding point of the [`BlindedPath`] provided by the recipient.
286 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
287 pub blinding_point: PublicKey,
288 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
289 /// inferring the destination. May be 0.
290 pub excess_final_cltv_expiry_delta: u32,
291 /// The total amount paid on this [`Path`], excluding the fees.
292 pub final_value_msat: u64,
295 impl_writeable_tlv_based!(BlindedTail, {
296 (0, hops, required_vec),
297 (2, blinding_point, required),
298 (4, excess_final_cltv_expiry_delta, required),
299 (6, final_value_msat, required),
302 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
303 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
304 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
306 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
307 pub hops: Vec<RouteHop>,
308 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
309 pub blinded_tail: Option<BlindedTail>,
313 /// Gets the fees for a given path, excluding any excess paid to the recipient.
314 pub fn fee_msat(&self) -> u64 {
315 match &self.blinded_tail {
316 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
318 // Do not count last hop of each path since that's the full value of the payment
319 self.hops.split_last().map_or(0,
320 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
325 /// Gets the total amount paid on this [`Path`], excluding the fees.
326 pub fn final_value_msat(&self) -> u64 {
327 match &self.blinded_tail {
328 Some(blinded_tail) => blinded_tail.final_value_msat,
329 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
333 /// Gets the final hop's CLTV expiry delta.
334 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
335 match &self.blinded_tail {
337 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
342 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
343 /// it can take multiple paths. Each path is composed of one or more hops through the network.
344 #[derive(Clone, Hash, PartialEq, Eq)]
346 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
347 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
349 pub paths: Vec<Path>,
350 /// The `route_params` parameter passed to [`find_route`].
352 /// This is used by `ChannelManager` to track information which may be required for retries.
354 /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
355 pub route_params: Option<RouteParameters>,
359 /// Returns the total amount of fees paid on this [`Route`].
361 /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
362 /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
363 /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
365 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
366 pub fn get_total_fees(&self) -> u64 {
367 let overpaid_value_msat = self.route_params.as_ref()
368 .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
369 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
372 /// Returns the total amount paid on this [`Route`], excluding the fees.
374 /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
375 /// we had to reach the [`htlc_minimum_msat`] limits.
377 /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
378 pub fn get_total_amount(&self) -> u64 {
379 self.paths.iter().map(|path| path.final_value_msat()).sum()
383 const SERIALIZATION_VERSION: u8 = 1;
384 const MIN_SERIALIZATION_VERSION: u8 = 1;
386 impl Writeable for Route {
387 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
388 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
389 (self.paths.len() as u64).write(writer)?;
390 let mut blinded_tails = Vec::new();
391 for path in self.paths.iter() {
392 (path.hops.len() as u8).write(writer)?;
393 for (idx, hop) in path.hops.iter().enumerate() {
395 if let Some(blinded_tail) = &path.blinded_tail {
396 if blinded_tails.is_empty() {
397 blinded_tails = Vec::with_capacity(path.hops.len());
399 blinded_tails.push(None);
402 blinded_tails.push(Some(blinded_tail));
403 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
406 write_tlv_fields!(writer, {
407 // For compatibility with LDK versions prior to 0.0.117, we take the individual
408 // RouteParameters' fields and reconstruct them on read.
409 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
410 (2, blinded_tails, optional_vec),
411 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
412 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
418 impl Readable for Route {
419 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
420 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
421 let path_count: u64 = Readable::read(reader)?;
422 if path_count == 0 { return Err(DecodeError::InvalidValue); }
423 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
424 let mut min_final_cltv_expiry_delta = u32::max_value();
425 for _ in 0..path_count {
426 let hop_count: u8 = Readable::read(reader)?;
427 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
428 for _ in 0..hop_count {
429 hops.push(Readable::read(reader)?);
431 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
432 min_final_cltv_expiry_delta =
433 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
434 paths.push(Path { hops, blinded_tail: None });
436 _init_and_read_len_prefixed_tlv_fields!(reader, {
437 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
438 (2, blinded_tails, optional_vec),
439 (3, final_value_msat, option),
440 (5, max_total_routing_fee_msat, option)
442 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
443 if blinded_tails.len() != 0 {
444 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
445 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
446 path.blinded_tail = blinded_tail_opt;
450 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
451 let route_params = match (payment_params, final_value_msat) {
452 (Some(payment_params), Some(final_value_msat)) => {
453 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
458 Ok(Route { paths, route_params })
462 /// Parameters needed to find a [`Route`].
464 /// Passed to [`find_route`] and [`build_route_from_hops`].
465 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
466 pub struct RouteParameters {
467 /// The parameters of the failed payment path.
468 pub payment_params: PaymentParameters,
470 /// The amount in msats sent on the failed payment path.
471 pub final_value_msat: u64,
473 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
475 /// This limit also applies to the total fees that may arise while retrying failed payment
478 /// Default value: `None`
479 pub max_total_routing_fee_msat: Option<u64>,
482 impl RouteParameters {
483 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
484 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
485 Self { payment_params, final_value_msat, max_total_routing_fee_msat: None }
489 impl Writeable for RouteParameters {
490 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
491 write_tlv_fields!(writer, {
492 (0, self.payment_params, required),
493 (1, self.max_total_routing_fee_msat, option),
494 (2, self.final_value_msat, required),
495 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
496 // `RouteParameters` directly. For compatibility, we write it here.
497 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
503 impl Readable for RouteParameters {
504 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
505 _init_and_read_len_prefixed_tlv_fields!(reader, {
506 (0, payment_params, (required: ReadableArgs, 0)),
507 (1, max_total_routing_fee_msat, option),
508 (2, final_value_msat, required),
509 (4, final_cltv_delta, option),
511 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
512 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
513 if final_cltv_expiry_delta == &0 {
514 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
519 final_value_msat: final_value_msat.0.unwrap(),
520 max_total_routing_fee_msat,
525 /// Maximum total CTLV difference we allow for a full payment path.
526 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
528 /// Maximum number of paths we allow an (MPP) payment to have.
529 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
530 // limits, but for now more than 10 paths likely carries too much one-path failure.
531 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
533 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
535 // The median hop CLTV expiry delta currently seen in the network.
536 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
538 // During routing, we only consider paths shorter than our maximum length estimate.
539 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
540 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
541 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
543 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
544 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
545 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
546 // (payment_secret and total_msat) = 93 bytes for the final hop.
547 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
548 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
549 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
551 /// Information used to route a payment.
552 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
553 pub struct PaymentParameters {
554 /// Information about the payee, such as their features and route hints for their channels.
557 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
558 pub expiry_time: Option<u64>,
560 /// The maximum total CLTV delta we accept for the route.
561 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
562 pub max_total_cltv_expiry_delta: u32,
564 /// The maximum number of paths that may be used by (MPP) payments.
565 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
566 pub max_path_count: u8,
568 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
569 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
570 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
571 /// increasing failure probability for those paths.
573 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
574 /// restriction have been found. While paths which meet this criteria will be searched for, it
575 /// is ultimately up to the scorer to select them over other paths.
577 /// A value of 0 will allow payments up to and including a channel's total announced usable
578 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
581 pub max_channel_saturation_power_of_half: u8,
583 /// A list of SCIDs which this payment was previously attempted over and which caused the
584 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
586 pub previously_failed_channels: Vec<u64>,
589 impl Writeable for PaymentParameters {
590 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
591 let mut clear_hints = &vec![];
592 let mut blinded_hints = &vec![];
594 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
595 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
597 write_tlv_fields!(writer, {
598 (0, self.payee.node_id(), option),
599 (1, self.max_total_cltv_expiry_delta, required),
600 (2, self.payee.features(), option),
601 (3, self.max_path_count, required),
602 (4, *clear_hints, required_vec),
603 (5, self.max_channel_saturation_power_of_half, required),
604 (6, self.expiry_time, option),
605 (7, self.previously_failed_channels, required_vec),
606 (8, *blinded_hints, optional_vec),
607 (9, self.payee.final_cltv_expiry_delta(), option),
613 impl ReadableArgs<u32> for PaymentParameters {
614 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
615 _init_and_read_len_prefixed_tlv_fields!(reader, {
616 (0, payee_pubkey, option),
617 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
618 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
619 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
620 (4, clear_route_hints, required_vec),
621 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
622 (6, expiry_time, option),
623 (7, previously_failed_channels, optional_vec),
624 (8, blinded_route_hints, optional_vec),
625 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
627 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
628 let payee = if blinded_route_hints.len() != 0 {
629 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
631 route_hints: blinded_route_hints,
632 features: features.and_then(|f: Features| f.bolt12()),
636 route_hints: clear_route_hints,
637 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
638 features: features.and_then(|f| f.bolt11()),
639 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
643 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
644 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
646 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
648 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
654 impl PaymentParameters {
655 /// Creates a payee with the node id of the given `pubkey`.
657 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
659 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
661 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
663 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
664 max_path_count: DEFAULT_MAX_PATH_COUNT,
665 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
666 previously_failed_channels: Vec::new(),
670 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
672 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
675 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
676 /// whether your router will be allowed to find a multi-part route for this payment. If you
677 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
678 /// [`RecipientOnionFields::secret_only`].
680 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
681 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
682 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
683 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
684 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
687 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
688 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
689 /// [`PaymentParameters::expiry_time`].
690 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
691 Self::blinded(invoice.payment_paths().to_vec())
692 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
693 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
696 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
697 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
699 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
701 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
702 max_path_count: DEFAULT_MAX_PATH_COUNT,
703 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
704 previously_failed_channels: Vec::new(),
708 /// Includes the payee's features. Errors if the parameters were not initialized with
709 /// [`PaymentParameters::from_bolt12_invoice`].
711 /// This is not exported to bindings users since bindings don't support move semantics
712 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
714 Payee::Clear { .. } => Err(()),
715 Payee::Blinded { route_hints, .. } =>
716 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
720 /// Includes the payee's features. Errors if the parameters were initialized with
721 /// [`PaymentParameters::from_bolt12_invoice`].
723 /// This is not exported to bindings users since bindings don't support move semantics
724 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
726 Payee::Blinded { .. } => Err(()),
727 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
729 payee: Payee::Clear {
730 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
736 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
737 /// [`PaymentParameters::from_bolt12_invoice`].
739 /// This is not exported to bindings users since bindings don't support move semantics
740 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
742 Payee::Blinded { .. } => Err(()),
743 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
745 payee: Payee::Clear {
746 route_hints, node_id, features, final_cltv_expiry_delta,
752 /// Includes a payment expiration in seconds relative to the UNIX epoch.
754 /// This is not exported to bindings users since bindings don't support move semantics
755 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
756 Self { expiry_time: Some(expiry_time), ..self }
759 /// Includes a limit for the total CLTV expiry delta which is considered during routing
761 /// This is not exported to bindings users since bindings don't support move semantics
762 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
763 Self { max_total_cltv_expiry_delta, ..self }
766 /// Includes a limit for the maximum number of payment paths that may be used.
768 /// This is not exported to bindings users since bindings don't support move semantics
769 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
770 Self { max_path_count, ..self }
773 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
774 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
776 /// This is not exported to bindings users since bindings don't support move semantics
777 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
778 Self { max_channel_saturation_power_of_half, ..self }
782 /// The recipient of a payment, differing based on whether they've hidden their identity with route
784 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
786 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
787 /// will be included in the final [`Route`].
789 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
791 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
792 /// Features supported by the payee.
794 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
796 features: Option<Bolt12InvoiceFeatures>,
798 /// The recipient included these route hints in their BOLT11 invoice.
800 /// The node id of the payee.
802 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
803 route_hints: Vec<RouteHint>,
804 /// Features supported by the payee.
806 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
807 /// does not contain any features.
809 /// [`for_keysend`]: PaymentParameters::for_keysend
810 features: Option<Bolt11InvoiceFeatures>,
811 /// The minimum CLTV delta at the end of the route. This value must not be zero.
812 final_cltv_expiry_delta: u32,
817 fn node_id(&self) -> Option<PublicKey> {
819 Self::Clear { node_id, .. } => Some(*node_id),
823 fn node_features(&self) -> Option<NodeFeatures> {
825 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
826 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
829 fn supports_basic_mpp(&self) -> bool {
831 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
832 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
835 fn features(&self) -> Option<FeaturesRef> {
837 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
838 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
841 fn final_cltv_expiry_delta(&self) -> Option<u32> {
843 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
847 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
849 Self::Blinded { route_hints, .. } => &route_hints[..],
850 Self::Clear { .. } => &[]
854 fn unblinded_route_hints(&self) -> &[RouteHint] {
856 Self::Blinded { .. } => &[],
857 Self::Clear { route_hints, .. } => &route_hints[..]
862 enum FeaturesRef<'a> {
863 Bolt11(&'a Bolt11InvoiceFeatures),
864 Bolt12(&'a Bolt12InvoiceFeatures),
867 Bolt11(Bolt11InvoiceFeatures),
868 Bolt12(Bolt12InvoiceFeatures),
872 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
874 Self::Bolt12(f) => Some(f),
878 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
880 Self::Bolt11(f) => Some(f),
886 impl<'a> Writeable for FeaturesRef<'a> {
887 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
889 Self::Bolt11(f) => Ok(f.write(w)?),
890 Self::Bolt12(f) => Ok(f.write(w)?),
895 impl ReadableArgs<bool> for Features {
896 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
897 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
898 Ok(Self::Bolt12(Readable::read(reader)?))
902 /// A list of hops along a payment path terminating with a channel to the recipient.
903 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
904 pub struct RouteHint(pub Vec<RouteHintHop>);
906 impl Writeable for RouteHint {
907 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
908 (self.0.len() as u64).write(writer)?;
909 for hop in self.0.iter() {
916 impl Readable for RouteHint {
917 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
918 let hop_count: u64 = Readable::read(reader)?;
919 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
920 for _ in 0..hop_count {
921 hops.push(Readable::read(reader)?);
927 /// A channel descriptor for a hop along a payment path.
928 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
929 pub struct RouteHintHop {
930 /// The node_id of the non-target end of the route
931 pub src_node_id: PublicKey,
932 /// The short_channel_id of this channel
933 pub short_channel_id: u64,
934 /// The fees which must be paid to use this channel
935 pub fees: RoutingFees,
936 /// The difference in CLTV values between this node and the next node.
937 pub cltv_expiry_delta: u16,
938 /// The minimum value, in msat, which must be relayed to the next hop.
939 pub htlc_minimum_msat: Option<u64>,
940 /// The maximum value in msat available for routing with a single HTLC.
941 pub htlc_maximum_msat: Option<u64>,
944 impl_writeable_tlv_based!(RouteHintHop, {
945 (0, src_node_id, required),
946 (1, htlc_minimum_msat, option),
947 (2, short_channel_id, required),
948 (3, htlc_maximum_msat, option),
950 (6, cltv_expiry_delta, required),
953 #[derive(Eq, PartialEq)]
954 struct RouteGraphNode {
956 lowest_fee_to_node: u64,
957 total_cltv_delta: u32,
958 // The maximum value a yet-to-be-constructed payment path might flow through this node.
959 // This value is upper-bounded by us by:
960 // - how much is needed for a path being constructed
961 // - how much value can channels following this node (up to the destination) can contribute,
962 // considering their capacity and fees
963 value_contribution_msat: u64,
964 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
965 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
966 path_htlc_minimum_msat: u64,
967 /// All penalties incurred from this hop on the way to the destination, as calculated using
969 path_penalty_msat: u64,
970 /// The number of hops walked up to this node.
971 path_length_to_node: u8,
974 impl cmp::Ord for RouteGraphNode {
975 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
976 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
977 .saturating_add(other.path_penalty_msat);
978 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
979 .saturating_add(self.path_penalty_msat);
980 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
984 impl cmp::PartialOrd for RouteGraphNode {
985 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
986 Some(self.cmp(other))
990 /// A wrapper around the various hop representations.
992 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
993 #[derive(Clone, Debug)]
994 enum CandidateRouteHop<'a> {
995 /// A hop from the payer, where the outbound liquidity is known.
997 details: &'a ChannelDetails,
999 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
1001 info: DirectedChannelInfo<'a>,
1002 short_channel_id: u64,
1004 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
1007 hint: &'a RouteHintHop,
1009 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
1011 hint: &'a (BlindedPayInfo, BlindedPath),
1014 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
1015 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
1016 /// introduction node and the destination. Useful for tracking that we need to include a blinded
1017 /// path at the end of our [`Route`].
1019 hint: &'a (BlindedPayInfo, BlindedPath),
1024 impl<'a> CandidateRouteHop<'a> {
1025 fn short_channel_id(&self) -> Option<u64> {
1027 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
1028 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1029 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
1030 CandidateRouteHop::Blinded { .. } => None,
1031 CandidateRouteHop::OneHopBlinded { .. } => None,
1035 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1036 fn features(&self) -> ChannelFeatures {
1038 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
1039 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1040 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1041 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1042 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1046 fn cltv_expiry_delta(&self) -> u32 {
1048 CandidateRouteHop::FirstHop { .. } => 0,
1049 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1050 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1051 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1052 CandidateRouteHop::OneHopBlinded { .. } => 0,
1056 fn htlc_minimum_msat(&self) -> u64 {
1058 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1059 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1060 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1061 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1062 CandidateRouteHop::OneHopBlinded { .. } => 0,
1066 fn fees(&self) -> RoutingFees {
1068 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1069 base_msat: 0, proportional_millionths: 0,
1071 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1072 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1073 CandidateRouteHop::Blinded { hint, .. } => {
1075 base_msat: hint.0.fee_base_msat,
1076 proportional_millionths: hint.0.fee_proportional_millionths
1079 CandidateRouteHop::OneHopBlinded { .. } =>
1080 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1084 fn effective_capacity(&self) -> EffectiveCapacity {
1086 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1087 liquidity_msat: details.next_outbound_htlc_limit_msat,
1089 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1090 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1091 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1092 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1093 EffectiveCapacity::Infinite,
1094 CandidateRouteHop::Blinded { hint, .. } =>
1095 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1096 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1100 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1102 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1103 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1104 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1107 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1109 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1117 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1118 enum CandidateHopId {
1119 /// Contains (scid, src_node_id < target_node_id)
1121 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1126 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1127 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1129 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1130 EffectiveCapacity::Infinite => u64::max_value(),
1131 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1132 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1133 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1134 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1135 // expected to have been generated from up-to-date capacity information.
1136 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1137 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1138 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1142 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1143 -> bool where I1::Item: PartialEq<I2::Item> {
1145 let a = iter_a.next();
1146 let b = iter_b.next();
1147 if a.is_none() && b.is_none() { return true; }
1148 if a.is_none() || b.is_none() { return false; }
1149 if a.unwrap().ne(&b.unwrap()) { return false; }
1153 /// It's useful to keep track of the hops associated with the fees required to use them,
1154 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1155 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1156 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1158 struct PathBuildingHop<'a> {
1159 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1160 // is a larger refactor and will require careful performance analysis.
1162 candidate: CandidateRouteHop<'a>,
1165 /// All the fees paid *after* this channel on the way to the destination
1166 next_hops_fee_msat: u64,
1167 /// Fee paid for the use of the current channel (see candidate.fees()).
1168 /// The value will be actually deducted from the counterparty balance on the previous link.
1169 hop_use_fee_msat: u64,
1170 /// Used to compare channels when choosing the for routing.
1171 /// Includes paying for the use of a hop and the following hops, as well as
1172 /// an estimated cost of reaching this hop.
1173 /// Might get stale when fees are recomputed. Primarily for internal use.
1174 total_fee_msat: u64,
1175 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1176 /// walk and may be invalid thereafter.
1177 path_htlc_minimum_msat: u64,
1178 /// All penalties incurred from this channel on the way to the destination, as calculated using
1179 /// channel scoring.
1180 path_penalty_msat: u64,
1181 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1182 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1183 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1184 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1185 /// avoid processing them again.
1186 was_processed: bool,
1187 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1188 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1189 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1190 // value_contribution_msat, which requires tracking it here. See comments below where it is
1191 // used for more info.
1192 value_contribution_msat: u64,
1195 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1196 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1197 let mut debug_struct = f.debug_struct("PathBuildingHop");
1199 .field("node_id", &self.node_id)
1200 .field("short_channel_id", &self.candidate.short_channel_id())
1201 .field("total_fee_msat", &self.total_fee_msat)
1202 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1203 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1204 .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
1205 .field("path_penalty_msat", &self.path_penalty_msat)
1206 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1207 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1208 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1209 let debug_struct = debug_struct
1210 .field("value_contribution_msat", &self.value_contribution_msat);
1211 debug_struct.finish()
1215 // Instantiated with a list of hops with correct data in them collected during path finding,
1216 // an instance of this struct should be further modified only via given methods.
1218 struct PaymentPath<'a> {
1219 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1222 impl<'a> PaymentPath<'a> {
1223 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1224 fn get_value_msat(&self) -> u64 {
1225 self.hops.last().unwrap().0.fee_msat
1228 fn get_path_penalty_msat(&self) -> u64 {
1229 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1232 fn get_total_fee_paid_msat(&self) -> u64 {
1233 if self.hops.len() < 1 {
1237 // Can't use next_hops_fee_msat because it gets outdated.
1238 for (i, (hop, _)) in self.hops.iter().enumerate() {
1239 if i != self.hops.len() - 1 {
1240 result += hop.fee_msat;
1246 fn get_cost_msat(&self) -> u64 {
1247 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1250 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1251 // to change fees may result in an inconsistency.
1253 // Sometimes we call this function right after constructing a path which is inconsistent in
1254 // that it the value being transferred has decreased while we were doing path finding, leading
1255 // to the fees being paid not lining up with the actual limits.
1257 // Note that this function is not aware of the available_liquidity limit, and thus does not
1258 // support increasing the value being transferred beyond what was selected during the initial
1260 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1261 let mut total_fee_paid_msat = 0 as u64;
1262 for i in (0..self.hops.len()).rev() {
1263 let last_hop = i == self.hops.len() - 1;
1265 // For non-last-hop, this value will represent the fees paid on the current hop. It
1266 // will consist of the fees for the use of the next hop, and extra fees to match
1267 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1268 let mut cur_hop_fees_msat = 0;
1270 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1273 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1274 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1275 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1276 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1277 // set it too high just to maliciously take more fees by exploiting this
1278 // match htlc_minimum_msat logic.
1279 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1280 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1281 // Note that there is a risk that *previous hops* (those closer to us, as we go
1282 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1284 // This might make us end up with a broken route, although this should be super-rare
1285 // in practice, both because of how healthy channels look like, and how we pick
1286 // channels in add_entry.
1287 // Also, this can't be exploited more heavily than *announce a free path and fail
1289 cur_hop_transferred_amount_msat += extra_fees_msat;
1290 total_fee_paid_msat += extra_fees_msat;
1291 cur_hop_fees_msat += extra_fees_msat;
1295 // Final hop is a special case: it usually has just value_msat (by design), but also
1296 // it still could overpay for the htlc_minimum_msat.
1297 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1299 // Propagate updated fees for the use of the channels to one hop back, where they
1300 // will be actually paid (fee_msat). The last hop is handled above separately.
1301 cur_hop.fee_msat = cur_hop_fees_msat;
1304 // Fee for the use of the current hop which will be deducted on the previous hop.
1305 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1306 // this channel is free for us.
1308 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1309 cur_hop.hop_use_fee_msat = new_fee;
1310 total_fee_paid_msat += new_fee;
1312 // It should not be possible because this function is called only to reduce the
1313 // value. In that case, compute_fee was already called with the same fees for
1314 // larger amount and there was no overflow.
1323 /// Calculate the fees required to route the given amount over a channel with the given fees.
1324 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1325 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1326 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1330 /// Calculate the fees required to route the given amount over a channel with the given fees,
1331 /// saturating to [`u64::max_value`].
1332 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1333 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1334 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1335 .saturating_add(channel_fees.base_msat as u64)
1338 /// The default `features` we assume for a node in a route, when no `features` are known about that
1341 /// Default features are:
1342 /// * variable_length_onion_optional
1343 fn default_node_features() -> NodeFeatures {
1344 let mut features = NodeFeatures::empty();
1345 features.set_variable_length_onion_optional();
1349 struct LoggedPayeePubkey(Option<PublicKey>);
1350 impl fmt::Display for LoggedPayeePubkey {
1351 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1354 "payee node id ".fmt(f)?;
1358 "blinded payee".fmt(f)
1364 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1365 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1366 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1368 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1369 "blinded route hint with introduction node id ".fmt(f)?;
1370 hint.1.introduction_node_id.fmt(f)?;
1371 " and blinding point ".fmt(f)?;
1372 hint.1.blinding_point.fmt(f)
1374 CandidateRouteHop::FirstHop { .. } => {
1375 "first hop with SCID ".fmt(f)?;
1376 self.0.short_channel_id().unwrap().fmt(f)
1378 CandidateRouteHop::PrivateHop { .. } => {
1379 "route hint with SCID ".fmt(f)?;
1380 self.0.short_channel_id().unwrap().fmt(f)
1384 self.0.short_channel_id().unwrap().fmt(f)
1391 fn sort_first_hop_channels(
1392 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1393 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1395 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1396 // most like to use.
1398 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1399 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1402 // Second, because simply always sorting in descending order would always use our largest
1403 // available outbound capacity, needlessly fragmenting our available channel capacities,
1404 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1405 // which have enough, but not too much, capacity for the payment.
1407 // Available outbound balances factor in liquidity already reserved for previously found paths.
1408 channels.sort_unstable_by(|chan_a, chan_b| {
1409 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1410 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1411 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1412 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1413 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1414 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1415 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1416 // Sort in descending order
1417 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1419 // Sort in ascending order
1420 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1425 /// Finds a route from us (payer) to the given target node (payee).
1427 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1428 /// in the given [`RouteParameters::payment_params`].
1429 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1431 /// Private routing paths between a public node and the target may be included in the `payee` field
1432 /// of [`RouteParameters::payment_params`].
1434 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1435 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1436 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1438 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1439 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1440 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1444 /// Panics if first_hops contains channels without `short_channel_id`s;
1445 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1447 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1448 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1449 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1450 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1451 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1452 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1453 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1454 ) -> Result<Route, LightningError>
1455 where L::Target: Logger, GL::Target: Logger {
1456 let graph_lock = network_graph.read_only();
1457 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1458 scorer, score_params, random_seed_bytes)?;
1459 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1463 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1464 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1465 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1466 _random_seed_bytes: &[u8; 32]
1467 ) -> Result<Route, LightningError>
1468 where L::Target: Logger {
1470 let payment_params = &route_params.payment_params;
1471 let final_value_msat = route_params.final_value_msat;
1472 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1473 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1474 // so use a dummy id for this in the blinded case.
1475 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1476 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1477 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1478 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1479 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1481 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1482 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1485 if final_value_msat > MAX_VALUE_MSAT {
1486 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1489 if final_value_msat == 0 {
1490 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1493 match &payment_params.payee {
1494 Payee::Clear { route_hints, node_id, .. } => {
1495 for route in route_hints.iter() {
1496 for hop in &route.0 {
1497 if hop.src_node_id == *node_id {
1498 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1503 Payee::Blinded { route_hints, .. } => {
1504 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1505 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});
1507 for (_, blinded_path) in route_hints.iter() {
1508 if blinded_path.blinded_hops.len() == 0 {
1509 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1510 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1511 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1512 } else if blinded_path.blinded_hops.len() == 1 &&
1513 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1514 && p.introduction_node_id != blinded_path.introduction_node_id)
1516 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1521 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1522 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1523 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});
1526 // The general routing idea is the following:
1527 // 1. Fill first/last hops communicated by the caller.
1528 // 2. Attempt to construct a path from payer to payee for transferring
1529 // any ~sufficient (described later) value.
1530 // If succeed, remember which channels were used and how much liquidity they have available,
1531 // so that future paths don't rely on the same liquidity.
1532 // 3. Proceed to the next step if:
1533 // - we hit the recommended target value;
1534 // - OR if we could not construct a new path. Any next attempt will fail too.
1535 // Otherwise, repeat step 2.
1536 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1537 // (not recommended value).
1538 // 5. If yes, proceed. If not, fail routing.
1539 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1540 // transferred up to the transfer target value.
1541 // 7. Reduce the value of the last path until we are sending only the target value.
1542 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1543 // them so that we're not sending two HTLCs along the same path.
1545 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1546 // distance from the payee
1548 // We are not a faithful Dijkstra's implementation because we can change values which impact
1549 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1550 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1551 // the value we are currently attempting to send over a path, we simply reduce the value being
1552 // sent along the path for any hops after that channel. This may imply that later fees (which
1553 // we've already tabulated) are lower because a smaller value is passing through the channels
1554 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1555 // channels which were selected earlier (and which may still be used for other paths without a
1556 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1559 // One potentially problematic case for this algorithm would be if there are many
1560 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1561 // graph walking), we may never find a path which is not liquidity-limited and has lower
1562 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1563 // Because we only consider paths with at least 5% of the total value being sent, the damage
1564 // from such a case should be limited, however this could be further reduced in the future by
1565 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1566 // limits for the purposes of fee calculation.
1568 // Alternatively, we could store more detailed path information in the heap (targets, below)
1569 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1570 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1571 // and practically (as we would need to store dynamically-allocated path information in heap
1572 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1573 // results of such an algorithm would likely be biased towards lower-value paths.
1575 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1576 // outside of our current search value, running a path search more times to gather candidate
1577 // paths at different values. While this may be acceptable, further path searches may increase
1578 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1579 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1580 // the same time, remaining generic across different payment values.
1582 let network_channels = network_graph.channels();
1583 let network_nodes = network_graph.nodes();
1585 if payment_params.max_path_count == 0 {
1586 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1589 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1590 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1592 let allow_mpp = if payment_params.max_path_count == 1 {
1594 } else if payment_params.payee.supports_basic_mpp() {
1596 } else if let Some(payee) = payee_node_id_opt {
1597 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1598 |info| info.features.supports_basic_mpp()))
1601 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1602 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1603 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1606 // Prepare the data we'll use for payee-to-payer search by
1607 // inserting first hops suggested by the caller as targets.
1608 // Our search will then attempt to reach them while traversing from the payee node.
1609 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1610 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1611 if let Some(hops) = first_hops {
1613 if chan.get_outbound_payment_scid().is_none() {
1614 panic!("first_hops should be filled in with usable channels, not pending ones");
1616 if chan.counterparty.node_id == *our_node_pubkey {
1617 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1620 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1621 .or_insert(Vec::new())
1624 if first_hop_targets.is_empty() {
1625 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1629 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1630 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1631 // adding duplicate entries when we find a better path to a given node.
1632 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1634 // Map from node_id to information about the best current path to that node, including feerate
1636 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1638 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1639 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1640 // htlc_minimum with extra fees while still finding a cheaper path.
1641 let mut hit_minimum_limit;
1643 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1644 // We start with a path_value of the exact amount we want, and if that generates a route we may
1645 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1646 // amount we want in total across paths, selecting the best subset at the end.
1647 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1648 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1649 let mut path_value_msat = final_value_msat;
1651 // Routing Fragmentation Mitigation heuristic:
1653 // Routing fragmentation across many payment paths increases the overall routing
1654 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1655 // Taking too many smaller paths also increases the chance of payment failure.
1656 // Thus to avoid this effect, we require from our collected links to provide
1657 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1658 // This requirement is currently set to be 1/max_path_count of the payment
1659 // value to ensure we only ever return routes that do not violate this limit.
1660 let minimal_value_contribution_msat: u64 = if allow_mpp {
1661 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1666 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1667 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1668 // drop the requirement by setting this to 0.
1669 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1671 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1672 // determine if the channel can be used by additional MPP paths or to inform path finding
1673 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1674 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1676 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1677 HashMap::with_capacity(network_nodes.len());
1679 // Keeping track of how much value we already collected across other paths. Helps to decide
1680 // when we want to stop looking for new paths.
1681 let mut already_collected_value_msat = 0;
1683 for (_, channels) in first_hop_targets.iter_mut() {
1684 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1688 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1689 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1691 // Remember how many candidates we ignored to allow for some logging afterwards.
1692 let mut num_ignored_value_contribution = 0;
1693 let mut num_ignored_path_length_limit = 0;
1694 let mut num_ignored_cltv_delta_limit = 0;
1695 let mut num_ignored_previously_failed = 0;
1696 let mut num_ignored_total_fee_limit = 0;
1698 macro_rules! add_entry {
1699 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1700 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1701 // since that value has to be transferred over this channel.
1702 // Returns whether this channel caused an update to `targets`.
1703 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1704 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1705 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1706 // We "return" whether we updated the path at the end, and how much we can route via
1707 // this channel, via this:
1708 let mut did_add_update_path_to_src_node = None;
1709 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1710 // practice these cases should be caught earlier:
1711 // - for regular channels at channel announcement (TODO)
1712 // - for first and last hops early in get_route
1713 if $src_node_id != $dest_node_id {
1714 let scid_opt = $candidate.short_channel_id();
1715 let effective_capacity = $candidate.effective_capacity();
1716 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1718 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1719 // It may be misleading because we might later choose to reduce the value transferred
1720 // over these channels, and the channel which was insufficient might become sufficient.
1721 // Worst case: we drop a good channel here because it can't cover the high following
1722 // fees caused by one expensive channel, but then this channel could have been used
1723 // if the amount being transferred over this path is lower.
1724 // We do this for now, but this is a subject for removal.
1725 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1726 let used_liquidity_msat = used_liquidities
1727 .get(&$candidate.id($src_node_id < $dest_node_id))
1728 .map_or(0, |used_liquidity_msat| {
1729 available_value_contribution_msat = available_value_contribution_msat
1730 .saturating_sub(*used_liquidity_msat);
1731 *used_liquidity_msat
1734 // Verify the liquidity offered by this channel complies to the minimal contribution.
1735 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1736 // Do not consider candidate hops that would exceed the maximum path length.
1737 let path_length_to_node = $next_hops_path_length + 1;
1738 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1740 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1741 // In order to already account for some of the privacy enhancing random CLTV
1742 // expiry delta offset we add on top later, we subtract a rough estimate
1743 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1744 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1745 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1746 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1747 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1748 .saturating_add($candidate.cltv_expiry_delta());
1749 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1751 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1752 // Includes paying fees for the use of the following channels.
1753 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1754 Some(result) => result,
1755 // Can't overflow due to how the values were computed right above.
1756 None => unreachable!(),
1758 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1759 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1760 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1762 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1763 let may_overpay_to_meet_path_minimum_msat =
1764 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1765 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1766 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1767 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1769 let payment_failed_on_this_channel = scid_opt.map_or(false,
1770 |scid| payment_params.previously_failed_channels.contains(&scid));
1772 let should_log_candidate = match $candidate {
1773 CandidateRouteHop::FirstHop { .. } => true,
1774 CandidateRouteHop::PrivateHop { .. } => true,
1775 CandidateRouteHop::Blinded { .. } => true,
1779 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1780 // bother considering this channel. If retrying with recommended_value_msat may
1781 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1782 // around again with a higher amount.
1783 if !contributes_sufficient_value {
1784 if should_log_candidate {
1785 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1787 num_ignored_value_contribution += 1;
1788 } else if exceeds_max_path_length {
1789 if should_log_candidate {
1790 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1792 num_ignored_path_length_limit += 1;
1793 } else if exceeds_cltv_delta_limit {
1794 if should_log_candidate {
1795 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1797 num_ignored_cltv_delta_limit += 1;
1798 } else if payment_failed_on_this_channel {
1799 if should_log_candidate {
1800 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1802 num_ignored_previously_failed += 1;
1803 } else if may_overpay_to_meet_path_minimum_msat {
1804 hit_minimum_limit = true;
1805 } else if over_path_minimum_msat {
1806 // Note that low contribution here (limited by available_liquidity_msat)
1807 // might violate htlc_minimum_msat on the hops which are next along the
1808 // payment path (upstream to the payee). To avoid that, we recompute
1809 // path fees knowing the final path contribution after constructing it.
1810 let path_htlc_minimum_msat = cmp::max(
1811 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1812 .saturating_add($next_hops_path_htlc_minimum_msat),
1813 $candidate.htlc_minimum_msat());
1814 let hm_entry = dist.entry($src_node_id);
1815 let old_entry = hm_entry.or_insert_with(|| {
1816 // If there was previously no known way to access the source node
1817 // (recall it goes payee-to-payer) of short_channel_id, first add a
1818 // semi-dummy record just to compute the fees to reach the source node.
1819 // This will affect our decision on selecting short_channel_id
1820 // as a way to reach the $dest_node_id.
1822 node_id: $dest_node_id.clone(),
1823 candidate: $candidate.clone(),
1825 next_hops_fee_msat: u64::max_value(),
1826 hop_use_fee_msat: u64::max_value(),
1827 total_fee_msat: u64::max_value(),
1828 path_htlc_minimum_msat,
1829 path_penalty_msat: u64::max_value(),
1830 was_processed: false,
1831 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1832 value_contribution_msat,
1836 #[allow(unused_mut)] // We only use the mut in cfg(test)
1837 let mut should_process = !old_entry.was_processed;
1838 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1840 // In test/fuzzing builds, we do extra checks to make sure the skipping
1841 // of already-seen nodes only happens in cases we expect (see below).
1842 if !should_process { should_process = true; }
1846 let mut hop_use_fee_msat = 0;
1847 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1849 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1850 // will have the same effective-fee
1851 if $src_node_id != our_node_id {
1852 // Note that `u64::max_value` means we'll always fail the
1853 // `old_entry.total_fee_msat > total_fee_msat` check below
1854 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1855 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1858 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
1859 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1860 if total_fee_msat > max_total_routing_fee_msat {
1861 if should_log_candidate {
1862 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
1864 num_ignored_total_fee_limit += 1;
1866 let channel_usage = ChannelUsage {
1867 amount_msat: amount_to_transfer_over_msat,
1868 inflight_htlc_msat: used_liquidity_msat,
1871 let channel_penalty_msat = scid_opt.map_or(0,
1872 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1873 channel_usage, score_params));
1874 let path_penalty_msat = $next_hops_path_penalty_msat
1875 .saturating_add(channel_penalty_msat);
1876 let new_graph_node = RouteGraphNode {
1877 node_id: $src_node_id,
1878 lowest_fee_to_node: total_fee_msat,
1879 total_cltv_delta: hop_total_cltv_delta,
1880 value_contribution_msat,
1881 path_htlc_minimum_msat,
1883 path_length_to_node,
1886 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1887 // if this way is cheaper than the already known
1888 // (considering the cost to "reach" this channel from the route destination,
1889 // the cost of using this channel,
1890 // and the cost of routing to the source node of this channel).
1891 // Also, consider that htlc_minimum_msat_difference, because we might end up
1892 // paying it. Consider the following exploit:
1893 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1894 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1895 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1896 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1898 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1899 // but it may require additional tracking - we don't want to double-count
1900 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1901 // can't use something that may decrease on future hops.
1902 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1903 .saturating_add(old_entry.path_penalty_msat);
1904 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1905 .saturating_add(path_penalty_msat);
1907 if !old_entry.was_processed && new_cost < old_cost {
1908 targets.push(new_graph_node);
1909 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1910 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1911 old_entry.total_fee_msat = total_fee_msat;
1912 old_entry.node_id = $dest_node_id.clone();
1913 old_entry.candidate = $candidate.clone();
1914 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1915 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1916 old_entry.path_penalty_msat = path_penalty_msat;
1917 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1919 old_entry.value_contribution_msat = value_contribution_msat;
1921 did_add_update_path_to_src_node = Some(value_contribution_msat);
1922 } else if old_entry.was_processed && new_cost < old_cost {
1923 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1925 // If we're skipping processing a node which was previously
1926 // processed even though we found another path to it with a
1927 // cheaper fee, check that it was because the second path we
1928 // found (which we are processing now) has a lower value
1929 // contribution due to an HTLC minimum limit.
1931 // e.g. take a graph with two paths from node 1 to node 2, one
1932 // through channel A, and one through channel B. Channel A and
1933 // B are both in the to-process heap, with their scores set by
1934 // a higher htlc_minimum than fee.
1935 // Channel A is processed first, and the channels onwards from
1936 // node 1 are added to the to-process heap. Thereafter, we pop
1937 // Channel B off of the heap, note that it has a much more
1938 // restrictive htlc_maximum_msat, and recalculate the fees for
1939 // all of node 1's channels using the new, reduced, amount.
1941 // This would be bogus - we'd be selecting a higher-fee path
1942 // with a lower htlc_maximum_msat instead of the one we'd
1943 // already decided to use.
1944 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1946 value_contribution_msat + path_penalty_msat <
1947 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1956 did_add_update_path_to_src_node
1960 let default_node_features = default_node_features();
1962 // Find ways (channels with destination) to reach a given node and store them
1963 // in the corresponding data structures (routing graph etc).
1964 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1965 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1966 // This data can later be helpful to optimize routing (pay lower fees).
1967 macro_rules! add_entries_to_cheapest_to_target_node {
1968 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1969 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1970 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1971 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1972 let was_processed = elem.was_processed;
1973 elem.was_processed = true;
1976 // Entries are added to dist in add_entry!() when there is a channel from a node.
1977 // Because there are no channels from payee, it will not have a dist entry at this point.
1978 // If we're processing any other node, it is always be the result of a channel from it.
1979 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1984 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1985 for details in first_channels {
1986 let candidate = CandidateRouteHop::FirstHop { details };
1987 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1988 $next_hops_value_contribution,
1989 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1990 $next_hops_cltv_delta, $next_hops_path_length);
1994 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1997 &default_node_features
2000 if !features.requires_unknown_bits() {
2001 for chan_id in $node.channels.iter() {
2002 let chan = network_channels.get(chan_id).unwrap();
2003 if !chan.features.requires_unknown_bits() {
2004 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2005 if first_hops.is_none() || *source != our_node_id {
2006 if directed_channel.direction().enabled {
2007 let candidate = CandidateRouteHop::PublicHop {
2008 info: directed_channel,
2009 short_channel_id: *chan_id,
2011 add_entry!(candidate, *source, $node_id,
2012 $fee_to_target_msat,
2013 $next_hops_value_contribution,
2014 $next_hops_path_htlc_minimum_msat,
2015 $next_hops_path_penalty_msat,
2016 $next_hops_cltv_delta, $next_hops_path_length);
2027 let mut payment_paths = Vec::<PaymentPath>::new();
2029 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2030 'paths_collection: loop {
2031 // For every new path, start from scratch, except for used_liquidities, which
2032 // helps to avoid reusing previously selected paths in future iterations.
2035 hit_minimum_limit = false;
2037 // If first hop is a private channel and the only way to reach the payee, this is the only
2038 // place where it could be added.
2039 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2040 for details in first_channels {
2041 let candidate = CandidateRouteHop::FirstHop { details };
2042 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
2043 0, 0u64, 0, 0).is_some();
2044 log_trace!(logger, "{} direct route to payee via {}",
2045 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2049 // Add the payee as a target, so that the payee-to-payer
2050 // search algorithm knows what to start with.
2051 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2052 // The payee is not in our network graph, so nothing to add here.
2053 // There is still a chance of reaching them via last_hops though,
2054 // so don't yet fail the payment here.
2055 // If not, targets.pop() will not even let us enter the loop in step 2.
2058 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2063 // If a caller provided us with last hops, add them to routing targets. Since this happens
2064 // earlier than general path finding, they will be somewhat prioritized, although currently
2065 // it matters only if the fees are exactly the same.
2066 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2067 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2068 let have_intro_node_in_graph =
2069 // Only add the hops in this route to our candidate set if either
2070 // we have a direct channel to the first hop or the first hop is
2071 // in the regular network graph.
2072 first_hop_targets.get(&intro_node_id).is_some() ||
2073 network_nodes.get(&intro_node_id).is_some();
2074 if !have_intro_node_in_graph { continue }
2075 let candidate = if hint.1.blinded_hops.len() == 1 {
2076 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2077 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2078 let mut path_contribution_msat = path_value_msat;
2079 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2080 0, path_contribution_msat, 0, 0_u64, 0, 0)
2082 path_contribution_msat = hop_used_msat;
2084 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2085 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2087 for details in first_channels {
2088 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2089 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2093 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2094 path_contribution_msat, candidate.htlc_minimum_msat(), 0_u64,
2095 candidate.cltv_expiry_delta(),
2096 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2100 for route in payment_params.payee.unblinded_route_hints().iter()
2101 .filter(|route| !route.0.is_empty())
2103 let first_hop_in_route = &(route.0)[0];
2104 let have_hop_src_in_graph =
2105 // Only add the hops in this route to our candidate set if either
2106 // we have a direct channel to the first hop or the first hop is
2107 // in the regular network graph.
2108 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2109 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2110 if have_hop_src_in_graph {
2111 // We start building the path from reverse, i.e., from payee
2112 // to the first RouteHintHop in the path.
2113 let hop_iter = route.0.iter().rev();
2114 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2115 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2116 let mut hop_used = true;
2117 let mut aggregate_next_hops_fee_msat: u64 = 0;
2118 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2119 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2120 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2121 let mut aggregate_next_hops_path_length: u8 = 0;
2122 let mut aggregate_path_contribution_msat = path_value_msat;
2124 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2125 let source = NodeId::from_pubkey(&hop.src_node_id);
2126 let target = NodeId::from_pubkey(&prev_hop_id);
2127 let candidate = network_channels
2128 .get(&hop.short_channel_id)
2129 .and_then(|channel| channel.as_directed_to(&target))
2130 .map(|(info, _)| CandidateRouteHop::PublicHop {
2132 short_channel_id: hop.short_channel_id,
2134 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2136 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2137 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2138 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2139 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2141 aggregate_path_contribution_msat = hop_used_msat;
2143 // If this hop was not used then there is no use checking the preceding
2144 // hops in the RouteHint. We can break by just searching for a direct
2145 // channel between last checked hop and first_hop_targets.
2149 let used_liquidity_msat = used_liquidities
2150 .get(&candidate.id(source < target)).copied()
2152 let channel_usage = ChannelUsage {
2153 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2154 inflight_htlc_msat: used_liquidity_msat,
2155 effective_capacity: candidate.effective_capacity(),
2157 let channel_penalty_msat = scorer.channel_penalty_msat(
2158 hop.short_channel_id, &source, &target, channel_usage, score_params
2160 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2161 .saturating_add(channel_penalty_msat);
2163 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2164 .saturating_add(hop.cltv_expiry_delta as u32);
2166 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2169 // Searching for a direct channel between last checked hop and first_hop_targets
2170 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2171 sort_first_hop_channels(first_channels, &used_liquidities,
2172 recommended_value_msat, our_node_pubkey);
2173 for details in first_channels {
2174 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2175 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2176 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2177 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2178 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2186 // In the next values of the iterator, the aggregate fees already reflects
2187 // the sum of value sent from payer (final_value_msat) and routing fees
2188 // for the last node in the RouteHint. We need to just add the fees to
2189 // route through the current node so that the preceding node (next iteration)
2191 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2192 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2193 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2195 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2196 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2197 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2198 .checked_add(hop_htlc_minimum_msat_inc);
2199 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2201 if idx == route.0.len() - 1 {
2202 // The last hop in this iterator is the first hop in
2203 // overall RouteHint.
2204 // If this hop connects to a node with which we have a direct channel,
2205 // ignore the network graph and, if the last hop was added, add our
2206 // direct channel to the candidate set.
2208 // Note that we *must* check if the last hop was added as `add_entry`
2209 // always assumes that the third argument is a node to which we have a
2211 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2212 sort_first_hop_channels(first_channels, &used_liquidities,
2213 recommended_value_msat, our_node_pubkey);
2214 for details in first_channels {
2215 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2216 add_entry!(first_hop_candidate, our_node_id,
2217 NodeId::from_pubkey(&hop.src_node_id),
2218 aggregate_next_hops_fee_msat,
2219 aggregate_path_contribution_msat,
2220 aggregate_next_hops_path_htlc_minimum_msat,
2221 aggregate_next_hops_path_penalty_msat,
2222 aggregate_next_hops_cltv_delta,
2223 aggregate_next_hops_path_length);
2231 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2233 // At this point, targets are filled with the data from first and
2234 // last hops communicated by the caller, and the payment receiver.
2235 let mut found_new_path = false;
2238 // If this loop terminates due the exhaustion of targets, two situations are possible:
2239 // - not enough outgoing liquidity:
2240 // 0 < already_collected_value_msat < final_value_msat
2241 // - enough outgoing liquidity:
2242 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2243 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2244 // paths_collection will be stopped because found_new_path==false.
2245 // This is not necessarily a routing failure.
2246 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, mut value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, path_length_to_node, .. }) = targets.pop() {
2248 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2249 // traversing the graph and arrange the path out of what we found.
2250 if node_id == our_node_id {
2251 let mut new_entry = dist.remove(&our_node_id).unwrap();
2252 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2255 let mut features_set = false;
2256 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2257 for details in first_channels {
2258 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2259 if details.get_outbound_payment_scid().unwrap() == scid {
2260 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2261 features_set = true;
2268 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2269 if let Some(node_info) = node.announcement_info.as_ref() {
2270 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2272 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2275 // We can fill in features for everything except hops which were
2276 // provided via the invoice we're paying. We could guess based on the
2277 // recipient's features but for now we simply avoid guessing at all.
2281 // Means we succesfully traversed from the payer to the payee, now
2282 // save this path for the payment route. Also, update the liquidity
2283 // remaining on the used hops, so that we take them into account
2284 // while looking for more paths.
2285 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2289 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2290 Some(payment_hop) => payment_hop,
2291 // We can't arrive at None because, if we ever add an entry to targets,
2292 // we also fill in the entry in dist (see add_entry!).
2293 None => unreachable!(),
2295 // We "propagate" the fees one hop backward (topologically) here,
2296 // so that fees paid for a HTLC forwarding on the current channel are
2297 // associated with the previous channel (where they will be subtracted).
2298 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2299 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2301 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2302 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2304 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2305 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2307 let mut payment_path = PaymentPath {hops: ordered_hops};
2309 // We could have possibly constructed a slightly inconsistent path: since we reduce
2310 // value being transferred along the way, we could have violated htlc_minimum_msat
2311 // on some channels we already passed (assuming dest->source direction). Here, we
2312 // recompute the fees again, so that if that's the case, we match the currently
2313 // underpaid htlc_minimum_msat with fees.
2314 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2315 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2316 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2318 // Since a path allows to transfer as much value as
2319 // the smallest channel it has ("bottleneck"), we should recompute
2320 // the fees so sender HTLC don't overpay fees when traversing
2321 // larger channels than the bottleneck. This may happen because
2322 // when we were selecting those channels we were not aware how much value
2323 // this path will transfer, and the relative fee for them
2324 // might have been computed considering a larger value.
2325 // Remember that we used these channels so that we don't rely
2326 // on the same liquidity in future paths.
2327 let mut prevented_redundant_path_selection = false;
2328 let prev_hop_iter = core::iter::once(&our_node_id)
2329 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2330 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2331 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2332 let used_liquidity_msat = used_liquidities
2333 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2334 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2335 .or_insert(spent_on_hop_msat);
2336 let hop_capacity = hop.candidate.effective_capacity();
2337 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2338 if *used_liquidity_msat == hop_max_msat {
2339 // If this path used all of this channel's available liquidity, we know
2340 // this path will not be selected again in the next loop iteration.
2341 prevented_redundant_path_selection = true;
2343 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2345 if !prevented_redundant_path_selection {
2346 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2347 // we'll probably end up picking the same path again on the next iteration.
2348 // Decrease the available liquidity of a hop in the middle of the path.
2349 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2350 let exhausted = u64::max_value();
2352 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2353 LoggedCandidateHop(victim_candidate));
2354 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2355 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2358 // Track the total amount all our collected paths allow to send so that we know
2359 // when to stop looking for more paths
2360 already_collected_value_msat += value_contribution_msat;
2362 payment_paths.push(payment_path);
2363 found_new_path = true;
2364 break 'path_construction;
2367 // If we found a path back to the payee, we shouldn't try to process it again. This is
2368 // the equivalent of the `elem.was_processed` check in
2369 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2370 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2372 // Otherwise, since the current target node is not us,
2373 // keep "unrolling" the payment graph from payee to payer by
2374 // finding a way to reach the current target from the payer side.
2375 match network_nodes.get(&node_id) {
2378 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2379 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2380 total_cltv_delta, path_length_to_node);
2386 if !found_new_path && channel_saturation_pow_half != 0 {
2387 channel_saturation_pow_half = 0;
2388 continue 'paths_collection;
2390 // If we don't support MPP, no use trying to gather more value ever.
2391 break 'paths_collection;
2395 // Stop either when the recommended value is reached or if no new path was found in this
2397 // In the latter case, making another path finding attempt won't help,
2398 // because we deterministically terminated the search due to low liquidity.
2399 if !found_new_path && channel_saturation_pow_half != 0 {
2400 channel_saturation_pow_half = 0;
2401 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2402 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2403 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2404 break 'paths_collection;
2405 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2406 // Further, if this was our first walk of the graph, and we weren't limited by an
2407 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2408 // limited by an htlc_minimum_msat value, find another path with a higher value,
2409 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2410 // still keeping a lower total fee than this path.
2411 if !hit_minimum_limit {
2412 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2413 break 'paths_collection;
2415 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2416 path_value_msat = recommended_value_msat;
2420 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2421 num_ignored_cltv_delta_limit + num_ignored_previously_failed + num_ignored_total_fee_limit;
2422 if num_ignored_total > 0 {
2423 log_trace!(logger, "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 maximum total fee limit. Total: {} ignored candidates.", num_ignored_value_contribution, num_ignored_path_length_limit, num_ignored_cltv_delta_limit, num_ignored_previously_failed, num_ignored_total_fee_limit, num_ignored_total);
2427 if payment_paths.len() == 0 {
2428 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2431 if already_collected_value_msat < final_value_msat {
2432 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2436 let mut selected_route = payment_paths;
2438 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2439 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2441 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2442 // the value they contribute towards the payment amount.
2443 // We sort in descending order as we will remove from the front in `retain`, next.
2444 selected_route.sort_unstable_by(|a, b|
2445 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2446 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2449 // We should make sure that at least 1 path left.
2450 let mut paths_left = selected_route.len();
2451 selected_route.retain(|path| {
2452 if paths_left == 1 {
2455 let path_value_msat = path.get_value_msat();
2456 if path_value_msat <= overpaid_value_msat {
2457 overpaid_value_msat -= path_value_msat;
2463 debug_assert!(selected_route.len() > 0);
2465 if overpaid_value_msat != 0 {
2467 // Now, subtract the remaining overpaid value from the most-expensive path.
2468 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2469 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2470 selected_route.sort_unstable_by(|a, b| {
2471 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2472 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2473 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2475 let expensive_payment_path = selected_route.first_mut().unwrap();
2477 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2478 // can't go negative.
2479 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2480 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2484 // Sort by the path itself and combine redundant paths.
2485 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2486 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2488 selected_route.sort_unstable_by_key(|path| {
2489 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2490 debug_assert!(path.hops.len() <= key.len());
2491 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2496 for idx in 0..(selected_route.len() - 1) {
2497 if idx + 1 >= selected_route.len() { break; }
2498 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2499 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2500 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2501 selected_route[idx].update_value_and_recompute_fees(new_value);
2502 selected_route.remove(idx + 1);
2506 let mut paths = Vec::new();
2507 for payment_path in selected_route {
2508 let mut hops = Vec::with_capacity(payment_path.hops.len());
2509 let mut prev_hop_node_id = our_node_id;
2510 for (hop, node_features) in payment_path.hops.iter()
2511 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2513 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2514 // If we sourced the hop from the graph we're sure the target node is announced.
2516 } else if let CandidateRouteHop::FirstHop { details } = hop.candidate {
2517 // If this is a first hop we also know if it's announced.
2520 // If we sourced it any other way, we double-check the network graph to see if
2521 // there are announced channels between the endpoints. If so, the hop might be
2522 // referring to any of the announced channels, as its `short_channel_id` might be
2523 // an alias, in which case we don't take any chances here.
2524 network_graph.node(&hop.node_id).map_or(false, |hop_node|
2525 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2526 .map_or(false, |c| c.as_directed_from(&prev_hop_node_id).is_some()))
2530 hops.push(RouteHop {
2531 pubkey: PublicKey::from_slice(hop.node_id.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &hop.node_id), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2532 node_features: node_features.clone(),
2533 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2534 channel_features: hop.candidate.features(),
2535 fee_msat: hop.fee_msat,
2536 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2537 maybe_announced_channel,
2540 prev_hop_node_id = hop.node_id;
2542 let mut final_cltv_delta = final_cltv_expiry_delta;
2543 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2544 if let Some(blinded_path) = h.candidate.blinded_path() {
2545 final_cltv_delta = h.candidate.cltv_expiry_delta();
2547 hops: blinded_path.blinded_hops.clone(),
2548 blinding_point: blinded_path.blinding_point,
2549 excess_final_cltv_expiry_delta: 0,
2550 final_value_msat: h.fee_msat,
2554 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2555 // applicable for the previous hop.
2556 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2557 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2560 paths.push(Path { hops, blinded_tail });
2562 // Make sure we would never create a route with more paths than we allow.
2563 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2565 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2566 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2567 if paths.iter().map(|p| p.fee_msat()).sum::<u64>() > max_total_routing_fee_msat {
2568 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2569 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2573 if let Some(node_features) = payment_params.payee.node_features() {
2574 for path in paths.iter_mut() {
2575 path.hops.last_mut().unwrap().node_features = node_features.clone();
2579 let route = Route { paths, route_params: Some(route_params.clone()) };
2580 log_info!(logger, "Got route: {}", log_route!(route));
2584 // When an adversarial intermediary node observes a payment, it may be able to infer its
2585 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2586 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2587 // payment path by adding a randomized 'shadow route' offset to the final hop.
2588 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2589 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2591 let network_channels = network_graph.channels();
2592 let network_nodes = network_graph.nodes();
2594 for path in route.paths.iter_mut() {
2595 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2597 // Remember the last three nodes of the random walk and avoid looping back on them.
2598 // Init with the last three nodes from the actual path, if possible.
2599 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2600 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2601 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2603 // Choose the last publicly known node as the starting point for the random walk.
2604 let mut cur_hop: Option<NodeId> = None;
2605 let mut path_nonce = [0u8; 12];
2606 if let Some(starting_hop) = path.hops.iter().rev()
2607 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2608 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2609 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2612 // Init PRNG with the path-dependant nonce, which is static for private paths.
2613 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2614 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2616 // Pick a random path length in [1 .. 3]
2617 prng.process_in_place(&mut random_path_bytes);
2618 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2620 for random_hop in 0..random_walk_length {
2621 // If we don't find a suitable offset in the public network graph, we default to
2622 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2623 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2625 if let Some(cur_node_id) = cur_hop {
2626 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2627 // Randomly choose the next unvisited hop.
2628 prng.process_in_place(&mut random_path_bytes);
2629 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2630 .checked_rem(cur_node.channels.len())
2631 .and_then(|index| cur_node.channels.get(index))
2632 .and_then(|id| network_channels.get(id)) {
2633 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2634 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2635 nodes_to_avoid[random_hop] = *next_id;
2636 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2637 cur_hop = Some(*next_id);
2644 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2645 .checked_add(random_hop_offset)
2646 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2649 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2650 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2651 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2653 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2654 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2655 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2656 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2657 max_path_offset = cmp::max(
2658 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2659 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2660 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2662 // Add 'shadow' CLTV offset to the final hop
2663 if let Some(tail) = path.blinded_tail.as_mut() {
2664 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2665 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2667 if let Some(last_hop) = path.hops.last_mut() {
2668 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2669 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2674 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2675 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2677 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2678 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2679 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2680 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2681 ) -> Result<Route, LightningError>
2682 where L::Target: Logger, GL::Target: Logger {
2683 let graph_lock = network_graph.read_only();
2684 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2685 &graph_lock, logger, random_seed_bytes)?;
2686 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2690 fn build_route_from_hops_internal<L: Deref>(
2691 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2692 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2693 ) -> Result<Route, LightningError> where L::Target: Logger {
2696 our_node_id: NodeId,
2697 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2700 impl ScoreLookUp for HopScorer {
2701 type ScoreParams = ();
2702 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2703 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2705 let mut cur_id = self.our_node_id;
2706 for i in 0..self.hop_ids.len() {
2707 if let Some(next_id) = self.hop_ids[i] {
2708 if cur_id == *source && next_id == *target {
2720 impl<'a> Writeable for HopScorer {
2722 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2727 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2728 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2731 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2732 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2733 for i in 0..hops.len() {
2734 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2737 let scorer = HopScorer { our_node_id, hop_ids };
2739 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2744 use crate::blinded_path::{BlindedHop, BlindedPath};
2745 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2746 use crate::routing::utxo::UtxoResult;
2747 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2748 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2749 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2750 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2751 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2752 use crate::chain::transaction::OutPoint;
2753 use crate::sign::EntropySource;
2754 use crate::ln::ChannelId;
2755 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2756 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2757 use crate::ln::channelmanager;
2758 use crate::offers::invoice::BlindedPayInfo;
2759 use crate::util::config::UserConfig;
2760 use crate::util::test_utils as ln_test_utils;
2761 use crate::util::chacha20::ChaCha20;
2762 use crate::util::ser::{Readable, Writeable};
2764 use crate::util::ser::Writer;
2766 use bitcoin::hashes::Hash;
2767 use bitcoin::network::constants::Network;
2768 use bitcoin::blockdata::constants::genesis_block;
2769 use bitcoin::blockdata::script::Builder;
2770 use bitcoin::blockdata::opcodes;
2771 use bitcoin::blockdata::transaction::TxOut;
2775 use bitcoin::secp256k1::{PublicKey,SecretKey};
2776 use bitcoin::secp256k1::Secp256k1;
2778 use crate::io::Cursor;
2779 use crate::prelude::*;
2780 use crate::sync::Arc;
2782 use core::convert::TryInto;
2784 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2785 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2786 channelmanager::ChannelDetails {
2787 channel_id: ChannelId::new_zero(),
2788 counterparty: channelmanager::ChannelCounterparty {
2791 unspendable_punishment_reserve: 0,
2792 forwarding_info: None,
2793 outbound_htlc_minimum_msat: None,
2794 outbound_htlc_maximum_msat: None,
2796 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2799 outbound_scid_alias: None,
2800 inbound_scid_alias: None,
2801 channel_value_satoshis: 0,
2803 outbound_capacity_msat,
2804 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2805 next_outbound_htlc_minimum_msat: 0,
2806 inbound_capacity_msat: 42,
2807 unspendable_punishment_reserve: None,
2808 confirmations_required: None,
2809 confirmations: None,
2810 force_close_spend_delay: None,
2811 is_outbound: true, is_channel_ready: true,
2812 is_usable: true, is_public: true,
2813 inbound_htlc_minimum_msat: None,
2814 inbound_htlc_maximum_msat: None,
2816 feerate_sat_per_1000_weight: None,
2817 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2822 fn simple_route_test() {
2823 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2824 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2825 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2826 let scorer = ln_test_utils::TestScorer::new();
2827 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2828 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2830 // Simple route to 2 via 1
2832 let route_params = RouteParameters::from_payment_params_and_value(
2833 payment_params.clone(), 0);
2834 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2835 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
2836 &Default::default(), &random_seed_bytes) {
2837 assert_eq!(err, "Cannot send a payment of 0 msat");
2838 } else { panic!(); }
2840 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2841 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2842 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2843 assert_eq!(route.paths[0].hops.len(), 2);
2845 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2846 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2847 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2848 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2849 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2850 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2852 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2853 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2854 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2855 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2856 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2857 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2861 fn invalid_first_hop_test() {
2862 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2863 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2864 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2865 let scorer = ln_test_utils::TestScorer::new();
2866 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2867 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2869 // Simple route to 2 via 1
2871 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2873 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2874 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2875 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
2876 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
2877 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2878 } else { panic!(); }
2880 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2881 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2882 assert_eq!(route.paths[0].hops.len(), 2);
2886 fn htlc_minimum_test() {
2887 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2888 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2889 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2890 let scorer = ln_test_utils::TestScorer::new();
2891 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2892 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2894 // Simple route to 2 via 1
2896 // Disable other paths
2897 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2899 short_channel_id: 12,
2901 flags: 2, // to disable
2902 cltv_expiry_delta: 0,
2903 htlc_minimum_msat: 0,
2904 htlc_maximum_msat: MAX_VALUE_MSAT,
2906 fee_proportional_millionths: 0,
2907 excess_data: Vec::new()
2909 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2911 short_channel_id: 3,
2913 flags: 2, // to disable
2914 cltv_expiry_delta: 0,
2915 htlc_minimum_msat: 0,
2916 htlc_maximum_msat: MAX_VALUE_MSAT,
2918 fee_proportional_millionths: 0,
2919 excess_data: Vec::new()
2921 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2923 short_channel_id: 13,
2925 flags: 2, // to disable
2926 cltv_expiry_delta: 0,
2927 htlc_minimum_msat: 0,
2928 htlc_maximum_msat: MAX_VALUE_MSAT,
2930 fee_proportional_millionths: 0,
2931 excess_data: Vec::new()
2933 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2934 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2935 short_channel_id: 6,
2937 flags: 2, // to disable
2938 cltv_expiry_delta: 0,
2939 htlc_minimum_msat: 0,
2940 htlc_maximum_msat: MAX_VALUE_MSAT,
2942 fee_proportional_millionths: 0,
2943 excess_data: Vec::new()
2945 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2946 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2947 short_channel_id: 7,
2949 flags: 2, // to disable
2950 cltv_expiry_delta: 0,
2951 htlc_minimum_msat: 0,
2952 htlc_maximum_msat: MAX_VALUE_MSAT,
2954 fee_proportional_millionths: 0,
2955 excess_data: Vec::new()
2958 // Check against amount_to_transfer_over_msat.
2959 // Set minimal HTLC of 200_000_000 msat.
2960 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2961 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2962 short_channel_id: 2,
2965 cltv_expiry_delta: 0,
2966 htlc_minimum_msat: 200_000_000,
2967 htlc_maximum_msat: MAX_VALUE_MSAT,
2969 fee_proportional_millionths: 0,
2970 excess_data: Vec::new()
2973 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2975 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2977 short_channel_id: 4,
2980 cltv_expiry_delta: 0,
2981 htlc_minimum_msat: 0,
2982 htlc_maximum_msat: 199_999_999,
2984 fee_proportional_millionths: 0,
2985 excess_data: Vec::new()
2988 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2989 let route_params = RouteParameters::from_payment_params_and_value(
2990 payment_params, 199_999_999);
2991 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2992 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
2993 &Default::default(), &random_seed_bytes) {
2994 assert_eq!(err, "Failed to find a path to the given destination");
2995 } else { panic!(); }
2997 // Lift the restriction on the first hop.
2998 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3000 short_channel_id: 2,
3003 cltv_expiry_delta: 0,
3004 htlc_minimum_msat: 0,
3005 htlc_maximum_msat: MAX_VALUE_MSAT,
3007 fee_proportional_millionths: 0,
3008 excess_data: Vec::new()
3011 // A payment above the minimum should pass
3012 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3013 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3014 assert_eq!(route.paths[0].hops.len(), 2);
3018 fn htlc_minimum_overpay_test() {
3019 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3020 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3021 let config = UserConfig::default();
3022 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3023 let scorer = ln_test_utils::TestScorer::new();
3024 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3025 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3027 // A route to node#2 via two paths.
3028 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3029 // Thus, they can't send 60 without overpaying.
3030 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3032 short_channel_id: 2,
3035 cltv_expiry_delta: 0,
3036 htlc_minimum_msat: 35_000,
3037 htlc_maximum_msat: 40_000,
3039 fee_proportional_millionths: 0,
3040 excess_data: Vec::new()
3042 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3043 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3044 short_channel_id: 12,
3047 cltv_expiry_delta: 0,
3048 htlc_minimum_msat: 35_000,
3049 htlc_maximum_msat: 40_000,
3051 fee_proportional_millionths: 0,
3052 excess_data: Vec::new()
3056 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3058 short_channel_id: 13,
3061 cltv_expiry_delta: 0,
3062 htlc_minimum_msat: 0,
3063 htlc_maximum_msat: MAX_VALUE_MSAT,
3065 fee_proportional_millionths: 0,
3066 excess_data: Vec::new()
3068 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3070 short_channel_id: 4,
3073 cltv_expiry_delta: 0,
3074 htlc_minimum_msat: 0,
3075 htlc_maximum_msat: MAX_VALUE_MSAT,
3077 fee_proportional_millionths: 0,
3078 excess_data: Vec::new()
3081 // Disable other paths
3082 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3084 short_channel_id: 1,
3086 flags: 2, // to disable
3087 cltv_expiry_delta: 0,
3088 htlc_minimum_msat: 0,
3089 htlc_maximum_msat: MAX_VALUE_MSAT,
3091 fee_proportional_millionths: 0,
3092 excess_data: Vec::new()
3095 let route_params = RouteParameters::from_payment_params_and_value(
3096 payment_params.clone(), 60_000);
3097 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3098 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3099 // Overpay fees to hit htlc_minimum_msat.
3100 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3101 // TODO: this could be better balanced to overpay 10k and not 15k.
3102 assert_eq!(overpaid_fees, 15_000);
3104 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3105 // while taking even more fee to match htlc_minimum_msat.
3106 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3107 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3108 short_channel_id: 12,
3111 cltv_expiry_delta: 0,
3112 htlc_minimum_msat: 65_000,
3113 htlc_maximum_msat: 80_000,
3115 fee_proportional_millionths: 0,
3116 excess_data: Vec::new()
3118 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3120 short_channel_id: 2,
3123 cltv_expiry_delta: 0,
3124 htlc_minimum_msat: 0,
3125 htlc_maximum_msat: MAX_VALUE_MSAT,
3127 fee_proportional_millionths: 0,
3128 excess_data: Vec::new()
3130 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3131 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3132 short_channel_id: 4,
3135 cltv_expiry_delta: 0,
3136 htlc_minimum_msat: 0,
3137 htlc_maximum_msat: MAX_VALUE_MSAT,
3139 fee_proportional_millionths: 100_000,
3140 excess_data: Vec::new()
3143 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3144 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3145 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3146 assert_eq!(route.paths.len(), 1);
3147 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3148 let fees = route.paths[0].hops[0].fee_msat;
3149 assert_eq!(fees, 5_000);
3151 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3152 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3153 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3154 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3155 // the other channel.
3156 assert_eq!(route.paths.len(), 1);
3157 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3158 let fees = route.paths[0].hops[0].fee_msat;
3159 assert_eq!(fees, 5_000);
3163 fn disable_channels_test() {
3164 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3165 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3166 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3167 let scorer = ln_test_utils::TestScorer::new();
3168 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3169 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3171 // // Disable channels 4 and 12 by flags=2
3172 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3174 short_channel_id: 4,
3176 flags: 2, // to disable
3177 cltv_expiry_delta: 0,
3178 htlc_minimum_msat: 0,
3179 htlc_maximum_msat: MAX_VALUE_MSAT,
3181 fee_proportional_millionths: 0,
3182 excess_data: Vec::new()
3184 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3186 short_channel_id: 12,
3188 flags: 2, // to disable
3189 cltv_expiry_delta: 0,
3190 htlc_minimum_msat: 0,
3191 htlc_maximum_msat: MAX_VALUE_MSAT,
3193 fee_proportional_millionths: 0,
3194 excess_data: Vec::new()
3197 // If all the channels require some features we don't understand, route should fail
3198 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3199 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3200 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3201 &Default::default(), &random_seed_bytes) {
3202 assert_eq!(err, "Failed to find a path to the given destination");
3203 } else { panic!(); }
3205 // If we specify a channel to node7, that overrides our local channel view and that gets used
3206 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3207 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3208 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3209 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3210 &Default::default(), &random_seed_bytes).unwrap();
3211 assert_eq!(route.paths[0].hops.len(), 2);
3213 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3214 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3215 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3216 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3217 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3218 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3220 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3221 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3222 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3223 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3224 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3225 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3229 fn disable_node_test() {
3230 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3231 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3232 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3233 let scorer = ln_test_utils::TestScorer::new();
3234 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3235 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3237 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3238 let mut unknown_features = NodeFeatures::empty();
3239 unknown_features.set_unknown_feature_required();
3240 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3241 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3242 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3244 // If all nodes require some features we don't understand, route should fail
3245 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3246 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3247 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3248 &Default::default(), &random_seed_bytes) {
3249 assert_eq!(err, "Failed to find a path to the given destination");
3250 } else { panic!(); }
3252 // If we specify a channel to node7, that overrides our local channel view and that gets used
3253 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3254 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3255 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3256 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3257 &Default::default(), &random_seed_bytes).unwrap();
3258 assert_eq!(route.paths[0].hops.len(), 2);
3260 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3261 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3262 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3263 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3264 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3265 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3267 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3268 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3269 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3270 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3271 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3272 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3274 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3275 // naively) assume that the user checked the feature bits on the invoice, which override
3276 // the node_announcement.
3280 fn our_chans_test() {
3281 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3282 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3283 let scorer = ln_test_utils::TestScorer::new();
3284 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3285 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3287 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3288 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3289 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3290 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3291 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3292 assert_eq!(route.paths[0].hops.len(), 3);
3294 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3295 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3296 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3297 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3298 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3299 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3301 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3302 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3303 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3304 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3305 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3306 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3308 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3309 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3310 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3311 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3312 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3313 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3315 // If we specify a channel to node7, that overrides our local channel view and that gets used
3316 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3317 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3318 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3319 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3320 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3321 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3322 &Default::default(), &random_seed_bytes).unwrap();
3323 assert_eq!(route.paths[0].hops.len(), 2);
3325 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3326 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3327 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3328 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3329 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3330 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3332 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3333 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3334 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3335 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3336 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3337 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3340 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3341 let zero_fees = RoutingFees {
3343 proportional_millionths: 0,
3345 vec![RouteHint(vec![RouteHintHop {
3346 src_node_id: nodes[3],
3347 short_channel_id: 8,
3349 cltv_expiry_delta: (8 << 4) | 1,
3350 htlc_minimum_msat: None,
3351 htlc_maximum_msat: None,
3353 ]), RouteHint(vec![RouteHintHop {
3354 src_node_id: nodes[4],
3355 short_channel_id: 9,
3358 proportional_millionths: 0,
3360 cltv_expiry_delta: (9 << 4) | 1,
3361 htlc_minimum_msat: None,
3362 htlc_maximum_msat: None,
3363 }]), RouteHint(vec![RouteHintHop {
3364 src_node_id: nodes[5],
3365 short_channel_id: 10,
3367 cltv_expiry_delta: (10 << 4) | 1,
3368 htlc_minimum_msat: None,
3369 htlc_maximum_msat: None,
3373 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3374 let zero_fees = RoutingFees {
3376 proportional_millionths: 0,
3378 vec![RouteHint(vec![RouteHintHop {
3379 src_node_id: nodes[2],
3380 short_channel_id: 5,
3383 proportional_millionths: 0,
3385 cltv_expiry_delta: (5 << 4) | 1,
3386 htlc_minimum_msat: None,
3387 htlc_maximum_msat: None,
3389 src_node_id: nodes[3],
3390 short_channel_id: 8,
3392 cltv_expiry_delta: (8 << 4) | 1,
3393 htlc_minimum_msat: None,
3394 htlc_maximum_msat: None,
3396 ]), RouteHint(vec![RouteHintHop {
3397 src_node_id: nodes[4],
3398 short_channel_id: 9,
3401 proportional_millionths: 0,
3403 cltv_expiry_delta: (9 << 4) | 1,
3404 htlc_minimum_msat: None,
3405 htlc_maximum_msat: None,
3406 }]), RouteHint(vec![RouteHintHop {
3407 src_node_id: nodes[5],
3408 short_channel_id: 10,
3410 cltv_expiry_delta: (10 << 4) | 1,
3411 htlc_minimum_msat: None,
3412 htlc_maximum_msat: None,
3417 fn partial_route_hint_test() {
3418 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3419 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3420 let scorer = ln_test_utils::TestScorer::new();
3421 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3422 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3424 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3425 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3426 // RouteHint may be partially used by the algo to build the best path.
3428 // First check that last hop can't have its source as the payee.
3429 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3430 src_node_id: nodes[6],
3431 short_channel_id: 8,
3434 proportional_millionths: 0,
3436 cltv_expiry_delta: (8 << 4) | 1,
3437 htlc_minimum_msat: None,
3438 htlc_maximum_msat: None,
3441 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3442 invalid_last_hops.push(invalid_last_hop);
3444 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3445 .with_route_hints(invalid_last_hops).unwrap();
3446 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3447 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3448 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3449 &Default::default(), &random_seed_bytes) {
3450 assert_eq!(err, "Route hint cannot have the payee as the source.");
3451 } else { panic!(); }
3454 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3455 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3456 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3457 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3458 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3459 assert_eq!(route.paths[0].hops.len(), 5);
3461 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3462 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3463 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3464 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3465 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3466 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3468 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3469 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3470 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3471 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3472 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3473 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3475 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3476 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3477 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3478 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3479 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3480 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3482 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3483 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3484 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3485 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3486 // If we have a peer in the node map, we'll use their features here since we don't have
3487 // a way of figuring out their features from the invoice:
3488 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3489 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3491 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3492 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3493 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3494 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3495 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3496 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3499 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3500 let zero_fees = RoutingFees {
3502 proportional_millionths: 0,
3504 vec![RouteHint(vec![RouteHintHop {
3505 src_node_id: nodes[3],
3506 short_channel_id: 8,
3508 cltv_expiry_delta: (8 << 4) | 1,
3509 htlc_minimum_msat: None,
3510 htlc_maximum_msat: None,
3511 }]), RouteHint(vec![
3513 ]), RouteHint(vec![RouteHintHop {
3514 src_node_id: nodes[5],
3515 short_channel_id: 10,
3517 cltv_expiry_delta: (10 << 4) | 1,
3518 htlc_minimum_msat: None,
3519 htlc_maximum_msat: None,
3524 fn ignores_empty_last_hops_test() {
3525 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3526 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3527 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3528 let scorer = ln_test_utils::TestScorer::new();
3529 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3530 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3532 // Test handling of an empty RouteHint passed in Invoice.
3533 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3534 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3535 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3536 assert_eq!(route.paths[0].hops.len(), 5);
3538 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3539 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3540 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3541 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3542 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3543 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3545 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3546 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3547 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3548 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3549 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3550 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3552 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3553 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3554 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3555 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3556 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3557 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3559 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3560 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3561 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3562 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3563 // If we have a peer in the node map, we'll use their features here since we don't have
3564 // a way of figuring out their features from the invoice:
3565 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3566 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3568 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3569 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3570 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3571 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3572 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3573 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3576 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3578 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3579 let zero_fees = RoutingFees {
3581 proportional_millionths: 0,
3583 vec![RouteHint(vec![RouteHintHop {
3584 src_node_id: hint_hops[0],
3585 short_channel_id: 0xff00,
3588 proportional_millionths: 0,
3590 cltv_expiry_delta: (5 << 4) | 1,
3591 htlc_minimum_msat: None,
3592 htlc_maximum_msat: None,
3594 src_node_id: hint_hops[1],
3595 short_channel_id: 0xff01,
3597 cltv_expiry_delta: (8 << 4) | 1,
3598 htlc_minimum_msat: None,
3599 htlc_maximum_msat: None,
3604 fn multi_hint_last_hops_test() {
3605 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3606 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3607 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3608 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3609 let scorer = ln_test_utils::TestScorer::new();
3610 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3611 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3612 // Test through channels 2, 3, 0xff00, 0xff01.
3613 // Test shows that multiple hop hints are considered.
3615 // Disabling channels 6 & 7 by flags=2
3616 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3617 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3618 short_channel_id: 6,
3620 flags: 2, // to disable
3621 cltv_expiry_delta: 0,
3622 htlc_minimum_msat: 0,
3623 htlc_maximum_msat: MAX_VALUE_MSAT,
3625 fee_proportional_millionths: 0,
3626 excess_data: Vec::new()
3628 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3629 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3630 short_channel_id: 7,
3632 flags: 2, // to disable
3633 cltv_expiry_delta: 0,
3634 htlc_minimum_msat: 0,
3635 htlc_maximum_msat: MAX_VALUE_MSAT,
3637 fee_proportional_millionths: 0,
3638 excess_data: Vec::new()
3641 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3642 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3643 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3644 assert_eq!(route.paths[0].hops.len(), 4);
3646 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3647 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3648 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3649 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3650 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3651 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3653 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3654 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3655 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3656 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3657 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3658 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3660 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3661 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3662 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3663 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3664 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3665 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3667 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3668 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3669 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3670 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3671 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3672 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3676 fn private_multi_hint_last_hops_test() {
3677 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3678 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3680 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3681 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3683 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3684 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3685 let scorer = ln_test_utils::TestScorer::new();
3686 // Test through channels 2, 3, 0xff00, 0xff01.
3687 // Test shows that multiple hop hints are considered.
3689 // Disabling channels 6 & 7 by flags=2
3690 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3692 short_channel_id: 6,
3694 flags: 2, // to disable
3695 cltv_expiry_delta: 0,
3696 htlc_minimum_msat: 0,
3697 htlc_maximum_msat: MAX_VALUE_MSAT,
3699 fee_proportional_millionths: 0,
3700 excess_data: Vec::new()
3702 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3704 short_channel_id: 7,
3706 flags: 2, // to disable
3707 cltv_expiry_delta: 0,
3708 htlc_minimum_msat: 0,
3709 htlc_maximum_msat: MAX_VALUE_MSAT,
3711 fee_proportional_millionths: 0,
3712 excess_data: Vec::new()
3715 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3716 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3717 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
3718 assert_eq!(route.paths[0].hops.len(), 4);
3720 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3721 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3722 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3723 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3724 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3725 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3727 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3728 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3729 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3730 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3731 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3732 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3734 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3735 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3736 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3737 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3738 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3739 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3741 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3742 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3743 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3744 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3745 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3746 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3749 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3750 let zero_fees = RoutingFees {
3752 proportional_millionths: 0,
3754 vec![RouteHint(vec![RouteHintHop {
3755 src_node_id: nodes[4],
3756 short_channel_id: 11,
3758 cltv_expiry_delta: (11 << 4) | 1,
3759 htlc_minimum_msat: None,
3760 htlc_maximum_msat: None,
3762 src_node_id: nodes[3],
3763 short_channel_id: 8,
3765 cltv_expiry_delta: (8 << 4) | 1,
3766 htlc_minimum_msat: None,
3767 htlc_maximum_msat: None,
3768 }]), RouteHint(vec![RouteHintHop {
3769 src_node_id: nodes[4],
3770 short_channel_id: 9,
3773 proportional_millionths: 0,
3775 cltv_expiry_delta: (9 << 4) | 1,
3776 htlc_minimum_msat: None,
3777 htlc_maximum_msat: None,
3778 }]), RouteHint(vec![RouteHintHop {
3779 src_node_id: nodes[5],
3780 short_channel_id: 10,
3782 cltv_expiry_delta: (10 << 4) | 1,
3783 htlc_minimum_msat: None,
3784 htlc_maximum_msat: None,
3789 fn last_hops_with_public_channel_test() {
3790 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3791 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3792 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3793 let scorer = ln_test_utils::TestScorer::new();
3794 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3795 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3796 // This test shows that public routes can be present in the invoice
3797 // which would be handled in the same manner.
3799 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3800 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3801 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3802 assert_eq!(route.paths[0].hops.len(), 5);
3804 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3805 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3806 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3807 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3808 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3809 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3811 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3812 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3813 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3814 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3815 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3816 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3818 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3819 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3820 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3821 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3822 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3823 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3825 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3826 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3827 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3828 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3829 // If we have a peer in the node map, we'll use their features here since we don't have
3830 // a way of figuring out their features from the invoice:
3831 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3832 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3834 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3835 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3836 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3837 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3838 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3839 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3843 fn our_chans_last_hop_connect_test() {
3844 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3845 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3846 let scorer = ln_test_utils::TestScorer::new();
3847 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3848 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3850 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3851 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3852 let mut last_hops = last_hops(&nodes);
3853 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3854 .with_route_hints(last_hops.clone()).unwrap();
3855 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3856 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3857 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3858 &Default::default(), &random_seed_bytes).unwrap();
3859 assert_eq!(route.paths[0].hops.len(), 2);
3861 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3862 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3863 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3864 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3865 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3866 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3868 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3869 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3870 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3871 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3872 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3873 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3875 last_hops[0].0[0].fees.base_msat = 1000;
3877 // Revert to via 6 as the fee on 8 goes up
3878 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3879 .with_route_hints(last_hops).unwrap();
3880 let route_params = RouteParameters::from_payment_params_and_value(
3881 payment_params.clone(), 100);
3882 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3883 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3884 assert_eq!(route.paths[0].hops.len(), 4);
3886 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3887 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3888 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3889 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3890 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3891 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3893 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3894 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3895 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3896 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3897 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3898 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3900 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3901 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3902 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3903 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3904 // If we have a peer in the node map, we'll use their features here since we don't have
3905 // a way of figuring out their features from the invoice:
3906 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3907 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3909 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3910 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3911 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3912 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3913 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3914 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3916 // ...but still use 8 for larger payments as 6 has a variable feerate
3917 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
3918 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3919 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3920 assert_eq!(route.paths[0].hops.len(), 5);
3922 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3923 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3924 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3925 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3926 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3927 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3929 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3930 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3931 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3932 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3933 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3934 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3936 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3937 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3938 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3939 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3940 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3941 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3943 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3944 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3945 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3946 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3947 // If we have a peer in the node map, we'll use their features here since we don't have
3948 // a way of figuring out their features from the invoice:
3949 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3950 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3952 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3953 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3954 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3955 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3956 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3957 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3960 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> {
3961 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3962 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3963 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3965 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3966 let last_hops = RouteHint(vec![RouteHintHop {
3967 src_node_id: middle_node_id,
3968 short_channel_id: 8,
3971 proportional_millionths: last_hop_fee_prop,
3973 cltv_expiry_delta: (8 << 4) | 1,
3974 htlc_minimum_msat: None,
3975 htlc_maximum_msat: last_hop_htlc_max,
3977 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3978 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3979 let scorer = ln_test_utils::TestScorer::new();
3980 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3981 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3982 let logger = ln_test_utils::TestLogger::new();
3983 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3984 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
3985 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
3986 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
3987 &random_seed_bytes);
3992 fn unannounced_path_test() {
3993 // We should be able to send a payment to a destination without any help of a routing graph
3994 // if we have a channel with a common counterparty that appears in the first and last hop
3996 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3998 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3999 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4000 assert_eq!(route.paths[0].hops.len(), 2);
4002 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4003 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4004 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4005 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4006 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4007 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4009 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4010 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4011 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4012 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4013 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4014 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4018 fn overflow_unannounced_path_test_liquidity_underflow() {
4019 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4020 // the last-hop had a fee which overflowed a u64, we'd panic.
4021 // This was due to us adding the first-hop from us unconditionally, causing us to think
4022 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4023 // In this test, we previously hit a subtraction underflow due to having less available
4024 // liquidity at the last hop than 0.
4025 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());
4029 fn overflow_unannounced_path_test_feerate_overflow() {
4030 // This tests for the same case as above, except instead of hitting a subtraction
4031 // underflow, we hit a case where the fee charged at a hop overflowed.
4032 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());
4036 fn available_amount_while_routing_test() {
4037 // Tests whether we choose the correct available channel amount while routing.
4039 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4040 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4041 let scorer = ln_test_utils::TestScorer::new();
4042 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4043 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4044 let config = UserConfig::default();
4045 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4047 // We will use a simple single-path route from
4048 // our node to node2 via node0: channels {1, 3}.
4050 // First disable all other paths.
4051 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4052 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4053 short_channel_id: 2,
4056 cltv_expiry_delta: 0,
4057 htlc_minimum_msat: 0,
4058 htlc_maximum_msat: 100_000,
4060 fee_proportional_millionths: 0,
4061 excess_data: Vec::new()
4063 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4065 short_channel_id: 12,
4068 cltv_expiry_delta: 0,
4069 htlc_minimum_msat: 0,
4070 htlc_maximum_msat: 100_000,
4072 fee_proportional_millionths: 0,
4073 excess_data: Vec::new()
4076 // Make the first channel (#1) very permissive,
4077 // and we will be testing all limits on the second channel.
4078 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080 short_channel_id: 1,
4083 cltv_expiry_delta: 0,
4084 htlc_minimum_msat: 0,
4085 htlc_maximum_msat: 1_000_000_000,
4087 fee_proportional_millionths: 0,
4088 excess_data: Vec::new()
4091 // First, let's see if routing works if we have absolutely no idea about the available amount.
4092 // In this case, it should be set to 250_000 sats.
4093 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4094 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4095 short_channel_id: 3,
4098 cltv_expiry_delta: 0,
4099 htlc_minimum_msat: 0,
4100 htlc_maximum_msat: 250_000_000,
4102 fee_proportional_millionths: 0,
4103 excess_data: Vec::new()
4107 // Attempt to route more than available results in a failure.
4108 let route_params = RouteParameters::from_payment_params_and_value(
4109 payment_params.clone(), 250_000_001);
4110 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4111 &our_id, &route_params, &network_graph.read_only(), None,
4112 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4113 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4114 } else { panic!(); }
4118 // Now, attempt to route an exact amount we have should be fine.
4119 let route_params = RouteParameters::from_payment_params_and_value(
4120 payment_params.clone(), 250_000_000);
4121 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4122 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4123 assert_eq!(route.paths.len(), 1);
4124 let path = route.paths.last().unwrap();
4125 assert_eq!(path.hops.len(), 2);
4126 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4127 assert_eq!(path.final_value_msat(), 250_000_000);
4130 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4131 // Disable channel #1 and use another first hop.
4132 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4133 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4134 short_channel_id: 1,
4137 cltv_expiry_delta: 0,
4138 htlc_minimum_msat: 0,
4139 htlc_maximum_msat: 1_000_000_000,
4141 fee_proportional_millionths: 0,
4142 excess_data: Vec::new()
4145 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4146 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4149 // Attempt to route more than available results in a failure.
4150 let route_params = RouteParameters::from_payment_params_and_value(
4151 payment_params.clone(), 200_000_001);
4152 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4153 &our_id, &route_params, &network_graph.read_only(),
4154 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4155 &Default::default(), &random_seed_bytes) {
4156 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4157 } else { panic!(); }
4161 // Now, attempt to route an exact amount we have should be fine.
4162 let route_params = RouteParameters::from_payment_params_and_value(
4163 payment_params.clone(), 200_000_000);
4164 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4165 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4166 &Default::default(), &random_seed_bytes).unwrap();
4167 assert_eq!(route.paths.len(), 1);
4168 let path = route.paths.last().unwrap();
4169 assert_eq!(path.hops.len(), 2);
4170 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4171 assert_eq!(path.final_value_msat(), 200_000_000);
4174 // Enable channel #1 back.
4175 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4177 short_channel_id: 1,
4180 cltv_expiry_delta: 0,
4181 htlc_minimum_msat: 0,
4182 htlc_maximum_msat: 1_000_000_000,
4184 fee_proportional_millionths: 0,
4185 excess_data: Vec::new()
4189 // Now let's see if routing works if we know only htlc_maximum_msat.
4190 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4192 short_channel_id: 3,
4195 cltv_expiry_delta: 0,
4196 htlc_minimum_msat: 0,
4197 htlc_maximum_msat: 15_000,
4199 fee_proportional_millionths: 0,
4200 excess_data: Vec::new()
4204 // Attempt to route more than available results in a failure.
4205 let route_params = RouteParameters::from_payment_params_and_value(
4206 payment_params.clone(), 15_001);
4207 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4208 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4209 &scorer, &Default::default(), &random_seed_bytes) {
4210 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4211 } else { panic!(); }
4215 // Now, attempt to route an exact amount we have should be fine.
4216 let route_params = RouteParameters::from_payment_params_and_value(
4217 payment_params.clone(), 15_000);
4218 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4219 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4220 assert_eq!(route.paths.len(), 1);
4221 let path = route.paths.last().unwrap();
4222 assert_eq!(path.hops.len(), 2);
4223 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4224 assert_eq!(path.final_value_msat(), 15_000);
4227 // Now let's see if routing works if we know only capacity from the UTXO.
4229 // We can't change UTXO capacity on the fly, so we'll disable
4230 // the existing channel and add another one with the capacity we need.
4231 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4232 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4233 short_channel_id: 3,
4236 cltv_expiry_delta: 0,
4237 htlc_minimum_msat: 0,
4238 htlc_maximum_msat: MAX_VALUE_MSAT,
4240 fee_proportional_millionths: 0,
4241 excess_data: Vec::new()
4244 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4245 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4246 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4247 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4248 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4250 *chain_monitor.utxo_ret.lock().unwrap() =
4251 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4252 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4254 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4255 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4257 short_channel_id: 333,
4260 cltv_expiry_delta: (3 << 4) | 1,
4261 htlc_minimum_msat: 0,
4262 htlc_maximum_msat: 15_000,
4264 fee_proportional_millionths: 0,
4265 excess_data: Vec::new()
4267 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4268 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4269 short_channel_id: 333,
4272 cltv_expiry_delta: (3 << 4) | 2,
4273 htlc_minimum_msat: 0,
4274 htlc_maximum_msat: 15_000,
4276 fee_proportional_millionths: 0,
4277 excess_data: Vec::new()
4281 // Attempt to route more than available results in a failure.
4282 let route_params = RouteParameters::from_payment_params_and_value(
4283 payment_params.clone(), 15_001);
4284 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4285 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4286 &scorer, &Default::default(), &random_seed_bytes) {
4287 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4288 } else { panic!(); }
4292 // Now, attempt to route an exact amount we have should be fine.
4293 let route_params = RouteParameters::from_payment_params_and_value(
4294 payment_params.clone(), 15_000);
4295 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4296 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4297 assert_eq!(route.paths.len(), 1);
4298 let path = route.paths.last().unwrap();
4299 assert_eq!(path.hops.len(), 2);
4300 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4301 assert_eq!(path.final_value_msat(), 15_000);
4304 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4305 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4306 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4307 short_channel_id: 333,
4310 cltv_expiry_delta: 0,
4311 htlc_minimum_msat: 0,
4312 htlc_maximum_msat: 10_000,
4314 fee_proportional_millionths: 0,
4315 excess_data: Vec::new()
4319 // Attempt to route more than available results in a failure.
4320 let route_params = RouteParameters::from_payment_params_and_value(
4321 payment_params.clone(), 10_001);
4322 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4323 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4324 &scorer, &Default::default(), &random_seed_bytes) {
4325 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4326 } else { panic!(); }
4330 // Now, attempt to route an exact amount we have should be fine.
4331 let route_params = RouteParameters::from_payment_params_and_value(
4332 payment_params.clone(), 10_000);
4333 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4334 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4335 assert_eq!(route.paths.len(), 1);
4336 let path = route.paths.last().unwrap();
4337 assert_eq!(path.hops.len(), 2);
4338 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4339 assert_eq!(path.final_value_msat(), 10_000);
4344 fn available_liquidity_last_hop_test() {
4345 // Check that available liquidity properly limits the path even when only
4346 // one of the latter hops is limited.
4347 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4348 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4349 let scorer = ln_test_utils::TestScorer::new();
4350 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4351 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4352 let config = UserConfig::default();
4353 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4355 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4356 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4357 // Total capacity: 50 sats.
4359 // Disable other potential paths.
4360 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4362 short_channel_id: 2,
4365 cltv_expiry_delta: 0,
4366 htlc_minimum_msat: 0,
4367 htlc_maximum_msat: 100_000,
4369 fee_proportional_millionths: 0,
4370 excess_data: Vec::new()
4372 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4373 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4374 short_channel_id: 7,
4377 cltv_expiry_delta: 0,
4378 htlc_minimum_msat: 0,
4379 htlc_maximum_msat: 100_000,
4381 fee_proportional_millionths: 0,
4382 excess_data: Vec::new()
4387 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4389 short_channel_id: 12,
4392 cltv_expiry_delta: 0,
4393 htlc_minimum_msat: 0,
4394 htlc_maximum_msat: 100_000,
4396 fee_proportional_millionths: 0,
4397 excess_data: Vec::new()
4399 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4400 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4401 short_channel_id: 13,
4404 cltv_expiry_delta: 0,
4405 htlc_minimum_msat: 0,
4406 htlc_maximum_msat: 100_000,
4408 fee_proportional_millionths: 0,
4409 excess_data: Vec::new()
4412 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4413 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4414 short_channel_id: 6,
4417 cltv_expiry_delta: 0,
4418 htlc_minimum_msat: 0,
4419 htlc_maximum_msat: 50_000,
4421 fee_proportional_millionths: 0,
4422 excess_data: Vec::new()
4424 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4425 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4426 short_channel_id: 11,
4429 cltv_expiry_delta: 0,
4430 htlc_minimum_msat: 0,
4431 htlc_maximum_msat: 100_000,
4433 fee_proportional_millionths: 0,
4434 excess_data: Vec::new()
4437 // Attempt to route more than available results in a failure.
4438 let route_params = RouteParameters::from_payment_params_and_value(
4439 payment_params.clone(), 60_000);
4440 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4441 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4442 &scorer, &Default::default(), &random_seed_bytes) {
4443 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4444 } else { panic!(); }
4448 // Now, attempt to route 49 sats (just a bit below the capacity).
4449 let route_params = RouteParameters::from_payment_params_and_value(
4450 payment_params.clone(), 49_000);
4451 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4452 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4453 assert_eq!(route.paths.len(), 1);
4454 let mut total_amount_paid_msat = 0;
4455 for path in &route.paths {
4456 assert_eq!(path.hops.len(), 4);
4457 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4458 total_amount_paid_msat += path.final_value_msat();
4460 assert_eq!(total_amount_paid_msat, 49_000);
4464 // Attempt to route an exact amount is also fine
4465 let route_params = RouteParameters::from_payment_params_and_value(
4466 payment_params, 50_000);
4467 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4468 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4469 assert_eq!(route.paths.len(), 1);
4470 let mut total_amount_paid_msat = 0;
4471 for path in &route.paths {
4472 assert_eq!(path.hops.len(), 4);
4473 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4474 total_amount_paid_msat += path.final_value_msat();
4476 assert_eq!(total_amount_paid_msat, 50_000);
4481 fn ignore_fee_first_hop_test() {
4482 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4483 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4484 let scorer = ln_test_utils::TestScorer::new();
4485 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4486 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4487 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4489 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4490 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4492 short_channel_id: 1,
4495 cltv_expiry_delta: 0,
4496 htlc_minimum_msat: 0,
4497 htlc_maximum_msat: 100_000,
4498 fee_base_msat: 1_000_000,
4499 fee_proportional_millionths: 0,
4500 excess_data: Vec::new()
4502 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4503 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4504 short_channel_id: 3,
4507 cltv_expiry_delta: 0,
4508 htlc_minimum_msat: 0,
4509 htlc_maximum_msat: 50_000,
4511 fee_proportional_millionths: 0,
4512 excess_data: Vec::new()
4516 let route_params = RouteParameters::from_payment_params_and_value(
4517 payment_params, 50_000);
4518 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4519 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4520 assert_eq!(route.paths.len(), 1);
4521 let mut total_amount_paid_msat = 0;
4522 for path in &route.paths {
4523 assert_eq!(path.hops.len(), 2);
4524 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4525 total_amount_paid_msat += path.final_value_msat();
4527 assert_eq!(total_amount_paid_msat, 50_000);
4532 fn simple_mpp_route_test() {
4533 let (secp_ctx, _, _, _, _) = build_graph();
4534 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4535 let config = UserConfig::default();
4536 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4537 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4538 do_simple_mpp_route_test(clear_payment_params);
4540 // MPP to a 1-hop blinded path for nodes[2]
4541 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4542 let blinded_path = BlindedPath {
4543 introduction_node_id: nodes[2],
4544 blinding_point: ln_test_utils::pubkey(42),
4545 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4547 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4549 fee_proportional_millionths: 0,
4550 htlc_minimum_msat: 0,
4551 htlc_maximum_msat: 0,
4552 cltv_expiry_delta: 0,
4553 features: BlindedHopFeatures::empty(),
4555 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4556 .with_bolt12_features(bolt12_features.clone()).unwrap();
4557 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4559 // MPP to 3 2-hop blinded paths
4560 let mut blinded_path_node_0 = blinded_path.clone();
4561 blinded_path_node_0.introduction_node_id = nodes[0];
4562 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4563 let mut node_0_payinfo = blinded_payinfo.clone();
4564 node_0_payinfo.htlc_maximum_msat = 50_000;
4566 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4567 blinded_path_node_7.introduction_node_id = nodes[7];
4568 let mut node_7_payinfo = blinded_payinfo.clone();
4569 node_7_payinfo.htlc_maximum_msat = 60_000;
4571 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4572 blinded_path_node_1.introduction_node_id = nodes[1];
4573 let mut node_1_payinfo = blinded_payinfo.clone();
4574 node_1_payinfo.htlc_maximum_msat = 180_000;
4576 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4578 (node_0_payinfo, blinded_path_node_0),
4579 (node_7_payinfo, blinded_path_node_7),
4580 (node_1_payinfo, blinded_path_node_1)
4582 .with_bolt12_features(bolt12_features).unwrap();
4583 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4587 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4588 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4589 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4590 let scorer = ln_test_utils::TestScorer::new();
4591 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4592 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4594 // We need a route consisting of 3 paths:
4595 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4596 // To achieve this, the amount being transferred should be around
4597 // the total capacity of these 3 paths.
4599 // First, we set limits on these (previously unlimited) channels.
4600 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4602 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4603 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4604 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4605 short_channel_id: 1,
4608 cltv_expiry_delta: 0,
4609 htlc_minimum_msat: 0,
4610 htlc_maximum_msat: 100_000,
4612 fee_proportional_millionths: 0,
4613 excess_data: Vec::new()
4615 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4616 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4617 short_channel_id: 3,
4620 cltv_expiry_delta: 0,
4621 htlc_minimum_msat: 0,
4622 htlc_maximum_msat: 50_000,
4624 fee_proportional_millionths: 0,
4625 excess_data: Vec::new()
4628 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4629 // (total limit 60).
4630 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4631 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4632 short_channel_id: 12,
4635 cltv_expiry_delta: 0,
4636 htlc_minimum_msat: 0,
4637 htlc_maximum_msat: 60_000,
4639 fee_proportional_millionths: 0,
4640 excess_data: Vec::new()
4642 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4643 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4644 short_channel_id: 13,
4647 cltv_expiry_delta: 0,
4648 htlc_minimum_msat: 0,
4649 htlc_maximum_msat: 60_000,
4651 fee_proportional_millionths: 0,
4652 excess_data: Vec::new()
4655 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4656 // (total capacity 180 sats).
4657 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4659 short_channel_id: 2,
4662 cltv_expiry_delta: 0,
4663 htlc_minimum_msat: 0,
4664 htlc_maximum_msat: 200_000,
4666 fee_proportional_millionths: 0,
4667 excess_data: Vec::new()
4669 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4671 short_channel_id: 4,
4674 cltv_expiry_delta: 0,
4675 htlc_minimum_msat: 0,
4676 htlc_maximum_msat: 180_000,
4678 fee_proportional_millionths: 0,
4679 excess_data: Vec::new()
4683 // Attempt to route more than available results in a failure.
4684 let route_params = RouteParameters::from_payment_params_and_value(
4685 payment_params.clone(), 300_000);
4686 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4687 &our_id, &route_params, &network_graph.read_only(), None,
4688 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4689 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4690 } else { panic!(); }
4694 // Attempt to route while setting max_path_count to 0 results in a failure.
4695 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4696 let route_params = RouteParameters::from_payment_params_and_value(
4697 zero_payment_params, 100);
4698 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4699 &our_id, &route_params, &network_graph.read_only(), None,
4700 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4701 assert_eq!(err, "Can't find a route with no paths allowed.");
4702 } else { panic!(); }
4706 // Attempt to route while setting max_path_count to 3 results in a failure.
4707 // This is the case because the minimal_value_contribution_msat would require each path
4708 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4709 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4710 let route_params = RouteParameters::from_payment_params_and_value(
4711 fail_payment_params, 250_000);
4712 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4713 &our_id, &route_params, &network_graph.read_only(), None,
4714 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4715 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4716 } else { panic!(); }
4720 // Now, attempt to route 250 sats (just a bit below the capacity).
4721 // Our algorithm should provide us with these 3 paths.
4722 let route_params = RouteParameters::from_payment_params_and_value(
4723 payment_params.clone(), 250_000);
4724 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4725 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4726 assert_eq!(route.paths.len(), 3);
4727 let mut total_amount_paid_msat = 0;
4728 for path in &route.paths {
4729 if let Some(bt) = &path.blinded_tail {
4730 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4732 assert_eq!(path.hops.len(), 2);
4733 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4735 total_amount_paid_msat += path.final_value_msat();
4737 assert_eq!(total_amount_paid_msat, 250_000);
4741 // Attempt to route an exact amount is also fine
4742 let route_params = RouteParameters::from_payment_params_and_value(
4743 payment_params.clone(), 290_000);
4744 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4745 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4746 assert_eq!(route.paths.len(), 3);
4747 let mut total_amount_paid_msat = 0;
4748 for path in &route.paths {
4749 if payment_params.payee.blinded_route_hints().len() != 0 {
4750 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4751 if let Some(bt) = &path.blinded_tail {
4752 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4753 if bt.hops.len() > 1 {
4754 assert_eq!(path.hops.last().unwrap().pubkey,
4755 payment_params.payee.blinded_route_hints().iter()
4756 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4757 .map(|(_, p)| p.introduction_node_id).unwrap());
4759 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4762 assert_eq!(path.hops.len(), 2);
4763 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4765 total_amount_paid_msat += path.final_value_msat();
4767 assert_eq!(total_amount_paid_msat, 290_000);
4772 fn long_mpp_route_test() {
4773 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4774 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4775 let scorer = ln_test_utils::TestScorer::new();
4776 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4777 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4778 let config = UserConfig::default();
4779 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4780 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4782 // We need a route consisting of 3 paths:
4783 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4784 // Note that these paths overlap (channels 5, 12, 13).
4785 // We will route 300 sats.
4786 // Each path will have 100 sats capacity, those channels which
4787 // are used twice will have 200 sats capacity.
4789 // Disable other potential paths.
4790 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4792 short_channel_id: 2,
4795 cltv_expiry_delta: 0,
4796 htlc_minimum_msat: 0,
4797 htlc_maximum_msat: 100_000,
4799 fee_proportional_millionths: 0,
4800 excess_data: Vec::new()
4802 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4804 short_channel_id: 7,
4807 cltv_expiry_delta: 0,
4808 htlc_minimum_msat: 0,
4809 htlc_maximum_msat: 100_000,
4811 fee_proportional_millionths: 0,
4812 excess_data: Vec::new()
4815 // Path via {node0, node2} is channels {1, 3, 5}.
4816 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4818 short_channel_id: 1,
4821 cltv_expiry_delta: 0,
4822 htlc_minimum_msat: 0,
4823 htlc_maximum_msat: 100_000,
4825 fee_proportional_millionths: 0,
4826 excess_data: Vec::new()
4828 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4829 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4830 short_channel_id: 3,
4833 cltv_expiry_delta: 0,
4834 htlc_minimum_msat: 0,
4835 htlc_maximum_msat: 100_000,
4837 fee_proportional_millionths: 0,
4838 excess_data: Vec::new()
4841 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4842 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4843 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4844 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4845 short_channel_id: 5,
4848 cltv_expiry_delta: 0,
4849 htlc_minimum_msat: 0,
4850 htlc_maximum_msat: 200_000,
4852 fee_proportional_millionths: 0,
4853 excess_data: Vec::new()
4856 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4857 // Add 100 sats to the capacities of {12, 13}, because these channels
4858 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4859 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4861 short_channel_id: 12,
4864 cltv_expiry_delta: 0,
4865 htlc_minimum_msat: 0,
4866 htlc_maximum_msat: 200_000,
4868 fee_proportional_millionths: 0,
4869 excess_data: Vec::new()
4871 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4873 short_channel_id: 13,
4876 cltv_expiry_delta: 0,
4877 htlc_minimum_msat: 0,
4878 htlc_maximum_msat: 200_000,
4880 fee_proportional_millionths: 0,
4881 excess_data: Vec::new()
4884 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4885 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4886 short_channel_id: 6,
4889 cltv_expiry_delta: 0,
4890 htlc_minimum_msat: 0,
4891 htlc_maximum_msat: 100_000,
4893 fee_proportional_millionths: 0,
4894 excess_data: Vec::new()
4896 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4897 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4898 short_channel_id: 11,
4901 cltv_expiry_delta: 0,
4902 htlc_minimum_msat: 0,
4903 htlc_maximum_msat: 100_000,
4905 fee_proportional_millionths: 0,
4906 excess_data: Vec::new()
4909 // Path via {node7, node2} is channels {12, 13, 5}.
4910 // We already limited them to 200 sats (they are used twice for 100 sats).
4911 // Nothing to do here.
4914 // Attempt to route more than available results in a failure.
4915 let route_params = RouteParameters::from_payment_params_and_value(
4916 payment_params.clone(), 350_000);
4917 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4918 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4919 &scorer, &Default::default(), &random_seed_bytes) {
4920 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4921 } else { panic!(); }
4925 // Now, attempt to route 300 sats (exact amount we can route).
4926 // Our algorithm should provide us with these 3 paths, 100 sats each.
4927 let route_params = RouteParameters::from_payment_params_and_value(
4928 payment_params, 300_000);
4929 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4930 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4931 assert_eq!(route.paths.len(), 3);
4933 let mut total_amount_paid_msat = 0;
4934 for path in &route.paths {
4935 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4936 total_amount_paid_msat += path.final_value_msat();
4938 assert_eq!(total_amount_paid_msat, 300_000);
4944 fn mpp_cheaper_route_test() {
4945 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4946 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4947 let scorer = ln_test_utils::TestScorer::new();
4948 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4949 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4950 let config = UserConfig::default();
4951 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4953 // This test checks that if we have two cheaper paths and one more expensive path,
4954 // so that liquidity-wise any 2 of 3 combination is sufficient,
4955 // two cheaper paths will be taken.
4956 // These paths have equal available liquidity.
4958 // We need a combination of 3 paths:
4959 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4960 // Note that these paths overlap (channels 5, 12, 13).
4961 // Each path will have 100 sats capacity, those channels which
4962 // are used twice will have 200 sats capacity.
4964 // Disable other potential paths.
4965 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4967 short_channel_id: 2,
4970 cltv_expiry_delta: 0,
4971 htlc_minimum_msat: 0,
4972 htlc_maximum_msat: 100_000,
4974 fee_proportional_millionths: 0,
4975 excess_data: Vec::new()
4977 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4979 short_channel_id: 7,
4982 cltv_expiry_delta: 0,
4983 htlc_minimum_msat: 0,
4984 htlc_maximum_msat: 100_000,
4986 fee_proportional_millionths: 0,
4987 excess_data: Vec::new()
4990 // Path via {node0, node2} is channels {1, 3, 5}.
4991 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4992 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4993 short_channel_id: 1,
4996 cltv_expiry_delta: 0,
4997 htlc_minimum_msat: 0,
4998 htlc_maximum_msat: 100_000,
5000 fee_proportional_millionths: 0,
5001 excess_data: Vec::new()
5003 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5005 short_channel_id: 3,
5008 cltv_expiry_delta: 0,
5009 htlc_minimum_msat: 0,
5010 htlc_maximum_msat: 100_000,
5012 fee_proportional_millionths: 0,
5013 excess_data: Vec::new()
5016 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5017 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5018 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5020 short_channel_id: 5,
5023 cltv_expiry_delta: 0,
5024 htlc_minimum_msat: 0,
5025 htlc_maximum_msat: 200_000,
5027 fee_proportional_millionths: 0,
5028 excess_data: Vec::new()
5031 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5032 // Add 100 sats to the capacities of {12, 13}, because these channels
5033 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5034 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5036 short_channel_id: 12,
5039 cltv_expiry_delta: 0,
5040 htlc_minimum_msat: 0,
5041 htlc_maximum_msat: 200_000,
5043 fee_proportional_millionths: 0,
5044 excess_data: Vec::new()
5046 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5048 short_channel_id: 13,
5051 cltv_expiry_delta: 0,
5052 htlc_minimum_msat: 0,
5053 htlc_maximum_msat: 200_000,
5055 fee_proportional_millionths: 0,
5056 excess_data: Vec::new()
5059 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5061 short_channel_id: 6,
5064 cltv_expiry_delta: 0,
5065 htlc_minimum_msat: 0,
5066 htlc_maximum_msat: 100_000,
5067 fee_base_msat: 1_000,
5068 fee_proportional_millionths: 0,
5069 excess_data: Vec::new()
5071 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5073 short_channel_id: 11,
5076 cltv_expiry_delta: 0,
5077 htlc_minimum_msat: 0,
5078 htlc_maximum_msat: 100_000,
5080 fee_proportional_millionths: 0,
5081 excess_data: Vec::new()
5084 // Path via {node7, node2} is channels {12, 13, 5}.
5085 // We already limited them to 200 sats (they are used twice for 100 sats).
5086 // Nothing to do here.
5089 // Now, attempt to route 180 sats.
5090 // Our algorithm should provide us with these 2 paths.
5091 let route_params = RouteParameters::from_payment_params_and_value(
5092 payment_params, 180_000);
5093 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5094 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5095 assert_eq!(route.paths.len(), 2);
5097 let mut total_value_transferred_msat = 0;
5098 let mut total_paid_msat = 0;
5099 for path in &route.paths {
5100 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5101 total_value_transferred_msat += path.final_value_msat();
5102 for hop in &path.hops {
5103 total_paid_msat += hop.fee_msat;
5106 // If we paid fee, this would be higher.
5107 assert_eq!(total_value_transferred_msat, 180_000);
5108 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5109 assert_eq!(total_fees_paid, 0);
5114 fn fees_on_mpp_route_test() {
5115 // This test makes sure that MPP algorithm properly takes into account
5116 // fees charged on the channels, by making the fees impactful:
5117 // if the fee is not properly accounted for, the behavior is different.
5118 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5119 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5120 let scorer = ln_test_utils::TestScorer::new();
5121 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5122 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5123 let config = UserConfig::default();
5124 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5126 // We need a route consisting of 2 paths:
5127 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5128 // We will route 200 sats, Each path will have 100 sats capacity.
5130 // This test is not particularly stable: e.g.,
5131 // there's a way to route via {node0, node2, node4}.
5132 // It works while pathfinding is deterministic, but can be broken otherwise.
5133 // It's fine to ignore this concern for now.
5135 // Disable other potential paths.
5136 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5137 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5138 short_channel_id: 2,
5141 cltv_expiry_delta: 0,
5142 htlc_minimum_msat: 0,
5143 htlc_maximum_msat: 100_000,
5145 fee_proportional_millionths: 0,
5146 excess_data: Vec::new()
5149 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5150 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5151 short_channel_id: 7,
5154 cltv_expiry_delta: 0,
5155 htlc_minimum_msat: 0,
5156 htlc_maximum_msat: 100_000,
5158 fee_proportional_millionths: 0,
5159 excess_data: Vec::new()
5162 // Path via {node0, node2} is channels {1, 3, 5}.
5163 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5165 short_channel_id: 1,
5168 cltv_expiry_delta: 0,
5169 htlc_minimum_msat: 0,
5170 htlc_maximum_msat: 100_000,
5172 fee_proportional_millionths: 0,
5173 excess_data: Vec::new()
5175 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5177 short_channel_id: 3,
5180 cltv_expiry_delta: 0,
5181 htlc_minimum_msat: 0,
5182 htlc_maximum_msat: 100_000,
5184 fee_proportional_millionths: 0,
5185 excess_data: Vec::new()
5188 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5189 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5190 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5191 short_channel_id: 5,
5194 cltv_expiry_delta: 0,
5195 htlc_minimum_msat: 0,
5196 htlc_maximum_msat: 100_000,
5198 fee_proportional_millionths: 0,
5199 excess_data: Vec::new()
5202 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5203 // All channels should be 100 sats capacity. But for the fee experiment,
5204 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5205 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5206 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5207 // so no matter how large are other channels,
5208 // the whole path will be limited by 100 sats with just these 2 conditions:
5209 // - channel 12 capacity is 250 sats
5210 // - fee for channel 6 is 150 sats
5211 // Let's test this by enforcing these 2 conditions and removing other limits.
5212 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5213 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5214 short_channel_id: 12,
5217 cltv_expiry_delta: 0,
5218 htlc_minimum_msat: 0,
5219 htlc_maximum_msat: 250_000,
5221 fee_proportional_millionths: 0,
5222 excess_data: Vec::new()
5224 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5226 short_channel_id: 13,
5229 cltv_expiry_delta: 0,
5230 htlc_minimum_msat: 0,
5231 htlc_maximum_msat: MAX_VALUE_MSAT,
5233 fee_proportional_millionths: 0,
5234 excess_data: Vec::new()
5237 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5239 short_channel_id: 6,
5242 cltv_expiry_delta: 0,
5243 htlc_minimum_msat: 0,
5244 htlc_maximum_msat: MAX_VALUE_MSAT,
5245 fee_base_msat: 150_000,
5246 fee_proportional_millionths: 0,
5247 excess_data: Vec::new()
5249 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5251 short_channel_id: 11,
5254 cltv_expiry_delta: 0,
5255 htlc_minimum_msat: 0,
5256 htlc_maximum_msat: MAX_VALUE_MSAT,
5258 fee_proportional_millionths: 0,
5259 excess_data: Vec::new()
5263 // Attempt to route more than available results in a failure.
5264 let route_params = RouteParameters::from_payment_params_and_value(
5265 payment_params.clone(), 210_000);
5266 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5267 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5268 &scorer, &Default::default(), &random_seed_bytes) {
5269 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5270 } else { panic!(); }
5274 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5275 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5276 max_total_routing_fee_msat: Some(149_999) };
5277 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5278 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5279 &scorer, &(), &random_seed_bytes) {
5280 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5281 } else { panic!(); }
5285 // Now, attempt to route 200 sats (exact amount we can route).
5286 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5287 max_total_routing_fee_msat: Some(150_000) };
5288 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5289 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5290 assert_eq!(route.paths.len(), 2);
5292 let mut total_amount_paid_msat = 0;
5293 for path in &route.paths {
5294 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5295 total_amount_paid_msat += path.final_value_msat();
5297 assert_eq!(total_amount_paid_msat, 200_000);
5298 assert_eq!(route.get_total_fees(), 150_000);
5303 fn mpp_with_last_hops() {
5304 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5305 // via a single last-hop route hint, we'd fail to route if we first collected routes
5306 // totaling close but not quite enough to fund the full payment.
5308 // This was because we considered last-hop hints to have exactly the sought payment amount
5309 // instead of the amount we were trying to collect, needlessly limiting our path searching
5310 // at the very first hop.
5312 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5313 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5314 // to only have the remaining to-collect amount in available liquidity.
5316 // This bug appeared in production in some specific channel configurations.
5317 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5318 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5319 let scorer = ln_test_utils::TestScorer::new();
5320 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5321 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5322 let config = UserConfig::default();
5323 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5324 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5325 src_node_id: nodes[2],
5326 short_channel_id: 42,
5327 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5328 cltv_expiry_delta: 42,
5329 htlc_minimum_msat: None,
5330 htlc_maximum_msat: None,
5331 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5333 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5334 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5335 // would first use the no-fee route and then fail to find a path along the second route as
5336 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5337 // under 5% of our payment amount.
5338 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5339 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5340 short_channel_id: 1,
5343 cltv_expiry_delta: (5 << 4) | 5,
5344 htlc_minimum_msat: 0,
5345 htlc_maximum_msat: 99_000,
5346 fee_base_msat: u32::max_value(),
5347 fee_proportional_millionths: u32::max_value(),
5348 excess_data: Vec::new()
5350 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5352 short_channel_id: 2,
5355 cltv_expiry_delta: (5 << 4) | 3,
5356 htlc_minimum_msat: 0,
5357 htlc_maximum_msat: 99_000,
5358 fee_base_msat: u32::max_value(),
5359 fee_proportional_millionths: u32::max_value(),
5360 excess_data: Vec::new()
5362 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5364 short_channel_id: 4,
5367 cltv_expiry_delta: (4 << 4) | 1,
5368 htlc_minimum_msat: 0,
5369 htlc_maximum_msat: MAX_VALUE_MSAT,
5371 fee_proportional_millionths: 0,
5372 excess_data: Vec::new()
5374 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5376 short_channel_id: 13,
5378 flags: 0|2, // Channel disabled
5379 cltv_expiry_delta: (13 << 4) | 1,
5380 htlc_minimum_msat: 0,
5381 htlc_maximum_msat: MAX_VALUE_MSAT,
5383 fee_proportional_millionths: 2000000,
5384 excess_data: Vec::new()
5387 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5389 let route_params = RouteParameters::from_payment_params_and_value(
5390 payment_params, 100_000);
5391 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5392 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5393 assert_eq!(route.paths.len(), 2);
5394 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5395 // Paths are manually ordered ordered by SCID, so:
5396 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5397 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5398 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5399 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5400 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5401 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5402 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5403 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5404 assert_eq!(route.get_total_fees(), 1);
5405 assert_eq!(route.get_total_amount(), 100_000);
5409 fn drop_lowest_channel_mpp_route_test() {
5410 // This test checks that low-capacity channel is dropped when after
5411 // path finding we realize that we found more capacity than we need.
5412 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5413 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5414 let scorer = ln_test_utils::TestScorer::new();
5415 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5416 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5417 let config = UserConfig::default();
5418 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5419 .with_max_channel_saturation_power_of_half(0);
5421 // We need a route consisting of 3 paths:
5422 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5424 // The first and the second paths should be sufficient, but the third should be
5425 // cheaper, so that we select it but drop later.
5427 // First, we set limits on these (previously unlimited) channels.
5428 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5430 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5431 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5432 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5433 short_channel_id: 1,
5436 cltv_expiry_delta: 0,
5437 htlc_minimum_msat: 0,
5438 htlc_maximum_msat: 100_000,
5440 fee_proportional_millionths: 0,
5441 excess_data: Vec::new()
5443 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5444 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5445 short_channel_id: 3,
5448 cltv_expiry_delta: 0,
5449 htlc_minimum_msat: 0,
5450 htlc_maximum_msat: 50_000,
5452 fee_proportional_millionths: 0,
5453 excess_data: Vec::new()
5456 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5457 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5458 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5459 short_channel_id: 12,
5462 cltv_expiry_delta: 0,
5463 htlc_minimum_msat: 0,
5464 htlc_maximum_msat: 60_000,
5466 fee_proportional_millionths: 0,
5467 excess_data: Vec::new()
5469 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5470 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5471 short_channel_id: 13,
5474 cltv_expiry_delta: 0,
5475 htlc_minimum_msat: 0,
5476 htlc_maximum_msat: 60_000,
5478 fee_proportional_millionths: 0,
5479 excess_data: Vec::new()
5482 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5483 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5485 short_channel_id: 2,
5488 cltv_expiry_delta: 0,
5489 htlc_minimum_msat: 0,
5490 htlc_maximum_msat: 20_000,
5492 fee_proportional_millionths: 0,
5493 excess_data: Vec::new()
5495 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5497 short_channel_id: 4,
5500 cltv_expiry_delta: 0,
5501 htlc_minimum_msat: 0,
5502 htlc_maximum_msat: 20_000,
5504 fee_proportional_millionths: 0,
5505 excess_data: Vec::new()
5509 // Attempt to route more than available results in a failure.
5510 let route_params = RouteParameters::from_payment_params_and_value(
5511 payment_params.clone(), 150_000);
5512 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5513 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5514 &scorer, &Default::default(), &random_seed_bytes) {
5515 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5516 } else { panic!(); }
5520 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5521 // Our algorithm should provide us with these 3 paths.
5522 let route_params = RouteParameters::from_payment_params_and_value(
5523 payment_params.clone(), 125_000);
5524 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5525 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5526 assert_eq!(route.paths.len(), 3);
5527 let mut total_amount_paid_msat = 0;
5528 for path in &route.paths {
5529 assert_eq!(path.hops.len(), 2);
5530 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5531 total_amount_paid_msat += path.final_value_msat();
5533 assert_eq!(total_amount_paid_msat, 125_000);
5537 // Attempt to route without the last small cheap channel
5538 let route_params = RouteParameters::from_payment_params_and_value(
5539 payment_params, 90_000);
5540 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5541 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5542 assert_eq!(route.paths.len(), 2);
5543 let mut total_amount_paid_msat = 0;
5544 for path in &route.paths {
5545 assert_eq!(path.hops.len(), 2);
5546 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5547 total_amount_paid_msat += path.final_value_msat();
5549 assert_eq!(total_amount_paid_msat, 90_000);
5554 fn min_criteria_consistency() {
5555 // Test that we don't use an inconsistent metric between updating and walking nodes during
5556 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5557 // was updated with a different criterion from the heap sorting, resulting in loops in
5558 // calculated paths. We test for that specific case here.
5560 // We construct a network that looks like this:
5562 // node2 -1(3)2- node3
5566 // node1 -1(5)2- node4 -1(1)2- node6
5572 // We create a loop on the side of our real path - our destination is node 6, with a
5573 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5574 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5575 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5576 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5577 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5578 // "previous hop" being set to node 3, creating a loop in the path.
5579 let secp_ctx = Secp256k1::new();
5580 let logger = Arc::new(ln_test_utils::TestLogger::new());
5581 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5582 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5583 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5584 let scorer = ln_test_utils::TestScorer::new();
5585 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5586 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5587 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5589 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5590 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5592 short_channel_id: 6,
5595 cltv_expiry_delta: (6 << 4) | 0,
5596 htlc_minimum_msat: 0,
5597 htlc_maximum_msat: MAX_VALUE_MSAT,
5599 fee_proportional_millionths: 0,
5600 excess_data: Vec::new()
5602 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5604 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5605 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5606 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5607 short_channel_id: 5,
5610 cltv_expiry_delta: (5 << 4) | 0,
5611 htlc_minimum_msat: 0,
5612 htlc_maximum_msat: MAX_VALUE_MSAT,
5614 fee_proportional_millionths: 0,
5615 excess_data: Vec::new()
5617 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5619 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5620 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5621 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5622 short_channel_id: 4,
5625 cltv_expiry_delta: (4 << 4) | 0,
5626 htlc_minimum_msat: 0,
5627 htlc_maximum_msat: MAX_VALUE_MSAT,
5629 fee_proportional_millionths: 0,
5630 excess_data: Vec::new()
5632 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5634 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5635 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5637 short_channel_id: 3,
5640 cltv_expiry_delta: (3 << 4) | 0,
5641 htlc_minimum_msat: 0,
5642 htlc_maximum_msat: MAX_VALUE_MSAT,
5644 fee_proportional_millionths: 0,
5645 excess_data: Vec::new()
5647 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5649 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5650 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5652 short_channel_id: 2,
5655 cltv_expiry_delta: (2 << 4) | 0,
5656 htlc_minimum_msat: 0,
5657 htlc_maximum_msat: MAX_VALUE_MSAT,
5659 fee_proportional_millionths: 0,
5660 excess_data: Vec::new()
5663 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5664 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5665 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5666 short_channel_id: 1,
5669 cltv_expiry_delta: (1 << 4) | 0,
5670 htlc_minimum_msat: 100,
5671 htlc_maximum_msat: MAX_VALUE_MSAT,
5673 fee_proportional_millionths: 0,
5674 excess_data: Vec::new()
5676 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5679 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5680 let route_params = RouteParameters::from_payment_params_and_value(
5681 payment_params, 10_000);
5682 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5683 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5684 assert_eq!(route.paths.len(), 1);
5685 assert_eq!(route.paths[0].hops.len(), 3);
5687 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5688 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5689 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5690 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5691 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5692 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5694 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5695 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5696 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5697 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5698 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5699 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5701 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5702 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5703 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5704 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5705 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5706 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5712 fn exact_fee_liquidity_limit() {
5713 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5714 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5715 // we calculated fees on a higher value, resulting in us ignoring such paths.
5716 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5717 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5718 let scorer = ln_test_utils::TestScorer::new();
5719 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5720 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5721 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5723 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5725 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5727 short_channel_id: 2,
5730 cltv_expiry_delta: 0,
5731 htlc_minimum_msat: 0,
5732 htlc_maximum_msat: 85_000,
5734 fee_proportional_millionths: 0,
5735 excess_data: Vec::new()
5738 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5740 short_channel_id: 12,
5743 cltv_expiry_delta: (4 << 4) | 1,
5744 htlc_minimum_msat: 0,
5745 htlc_maximum_msat: 270_000,
5747 fee_proportional_millionths: 1000000,
5748 excess_data: Vec::new()
5752 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5753 // 200% fee charged channel 13 in the 1-to-2 direction.
5754 let route_params = RouteParameters::from_payment_params_and_value(
5755 payment_params, 90_000);
5756 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5757 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5758 assert_eq!(route.paths.len(), 1);
5759 assert_eq!(route.paths[0].hops.len(), 2);
5761 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5762 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5763 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5764 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5765 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5766 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5768 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5769 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5770 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5771 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5772 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5773 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5778 fn htlc_max_reduction_below_min() {
5779 // Test that if, while walking the graph, we reduce the value being sent to meet an
5780 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5781 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5782 // resulting in us thinking there is no possible path, even if other paths exist.
5783 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5784 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5785 let scorer = ln_test_utils::TestScorer::new();
5786 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5787 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5788 let config = UserConfig::default();
5789 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5791 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5792 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5793 // then try to send 90_000.
5794 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5796 short_channel_id: 2,
5799 cltv_expiry_delta: 0,
5800 htlc_minimum_msat: 0,
5801 htlc_maximum_msat: 80_000,
5803 fee_proportional_millionths: 0,
5804 excess_data: Vec::new()
5806 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5808 short_channel_id: 4,
5811 cltv_expiry_delta: (4 << 4) | 1,
5812 htlc_minimum_msat: 90_000,
5813 htlc_maximum_msat: MAX_VALUE_MSAT,
5815 fee_proportional_millionths: 0,
5816 excess_data: Vec::new()
5820 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5821 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5822 // expensive) channels 12-13 path.
5823 let route_params = RouteParameters::from_payment_params_and_value(
5824 payment_params, 90_000);
5825 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5826 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5827 assert_eq!(route.paths.len(), 1);
5828 assert_eq!(route.paths[0].hops.len(), 2);
5830 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5831 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5832 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5833 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5834 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5835 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5837 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5838 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5839 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5840 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5841 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5842 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5847 fn multiple_direct_first_hops() {
5848 // Previously we'd only ever considered one first hop path per counterparty.
5849 // However, as we don't restrict users to one channel per peer, we really need to support
5850 // looking at all first hop paths.
5851 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5852 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5853 // route over multiple channels with the same first hop.
5854 let secp_ctx = Secp256k1::new();
5855 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5856 let logger = Arc::new(ln_test_utils::TestLogger::new());
5857 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5858 let scorer = ln_test_utils::TestScorer::new();
5859 let config = UserConfig::default();
5860 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5861 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5862 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5865 let route_params = RouteParameters::from_payment_params_and_value(
5866 payment_params.clone(), 100_000);
5867 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5868 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5869 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5870 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5871 assert_eq!(route.paths.len(), 1);
5872 assert_eq!(route.paths[0].hops.len(), 1);
5874 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5875 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5876 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5879 let route_params = RouteParameters::from_payment_params_and_value(
5880 payment_params.clone(), 100_000);
5881 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5882 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5883 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5884 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5885 assert_eq!(route.paths.len(), 2);
5886 assert_eq!(route.paths[0].hops.len(), 1);
5887 assert_eq!(route.paths[1].hops.len(), 1);
5889 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5890 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5892 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5893 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5895 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5896 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5900 // If we have a bunch of outbound channels to the same node, where most are not
5901 // sufficient to pay the full payment, but one is, we should default to just using the
5902 // one single channel that has sufficient balance, avoiding MPP.
5904 // If we have several options above the 3xpayment value threshold, we should pick the
5905 // smallest of them, avoiding further fragmenting our available outbound balance to
5907 let route_params = RouteParameters::from_payment_params_and_value(
5908 payment_params, 100_000);
5909 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5910 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5911 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5912 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5913 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5914 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5915 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5916 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5917 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5918 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5919 assert_eq!(route.paths.len(), 1);
5920 assert_eq!(route.paths[0].hops.len(), 1);
5922 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5923 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5924 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5929 fn prefers_shorter_route_with_higher_fees() {
5930 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5931 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5932 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5934 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5935 let scorer = ln_test_utils::TestScorer::new();
5936 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5937 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5938 let route_params = RouteParameters::from_payment_params_and_value(
5939 payment_params.clone(), 100);
5940 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5941 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5942 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5944 assert_eq!(route.get_total_fees(), 100);
5945 assert_eq!(route.get_total_amount(), 100);
5946 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5948 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5949 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5950 let scorer = FixedPenaltyScorer::with_penalty(100);
5951 let route_params = RouteParameters::from_payment_params_and_value(
5952 payment_params, 100);
5953 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5954 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5955 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5957 assert_eq!(route.get_total_fees(), 300);
5958 assert_eq!(route.get_total_amount(), 100);
5959 assert_eq!(path, vec![2, 4, 7, 10]);
5962 struct BadChannelScorer {
5963 short_channel_id: u64,
5967 impl Writeable for BadChannelScorer {
5968 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5970 impl ScoreLookUp for BadChannelScorer {
5971 type ScoreParams = ();
5972 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5973 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5977 struct BadNodeScorer {
5982 impl Writeable for BadNodeScorer {
5983 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5986 impl ScoreLookUp for BadNodeScorer {
5987 type ScoreParams = ();
5988 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5989 if *target == self.node_id { u64::max_value() } else { 0 }
5994 fn avoids_routing_through_bad_channels_and_nodes() {
5995 let (secp_ctx, network, _, _, logger) = build_graph();
5996 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5997 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5998 let network_graph = network.read_only();
6000 // A path to nodes[6] exists when no penalties are applied to any channel.
6001 let scorer = ln_test_utils::TestScorer::new();
6002 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6003 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6004 let route_params = RouteParameters::from_payment_params_and_value(
6005 payment_params, 100);
6006 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6007 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6008 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6010 assert_eq!(route.get_total_fees(), 100);
6011 assert_eq!(route.get_total_amount(), 100);
6012 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6014 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6015 let scorer = BadChannelScorer { short_channel_id: 6 };
6016 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6017 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6018 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6020 assert_eq!(route.get_total_fees(), 300);
6021 assert_eq!(route.get_total_amount(), 100);
6022 assert_eq!(path, vec![2, 4, 7, 10]);
6024 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6025 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6026 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6027 &scorer, &Default::default(), &random_seed_bytes) {
6028 Err(LightningError { err, .. } ) => {
6029 assert_eq!(err, "Failed to find a path to the given destination");
6031 Ok(_) => panic!("Expected error"),
6036 fn total_fees_single_path() {
6038 paths: vec![Path { hops: vec![
6040 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6041 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6042 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6045 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6046 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6047 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6050 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6051 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6052 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6054 ], blinded_tail: None }],
6058 assert_eq!(route.get_total_fees(), 250);
6059 assert_eq!(route.get_total_amount(), 225);
6063 fn total_fees_multi_path() {
6065 paths: vec![Path { hops: vec![
6067 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6068 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6069 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6072 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6073 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6074 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6076 ], blinded_tail: None }, Path { hops: vec![
6078 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6079 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6080 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6083 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6084 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6085 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6087 ], blinded_tail: None }],
6091 assert_eq!(route.get_total_fees(), 200);
6092 assert_eq!(route.get_total_amount(), 300);
6096 fn total_empty_route_no_panic() {
6097 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6098 // would both panic if the route was completely empty. We test to ensure they return 0
6099 // here, even though its somewhat nonsensical as a route.
6100 let route = Route { paths: Vec::new(), route_params: None };
6102 assert_eq!(route.get_total_fees(), 0);
6103 assert_eq!(route.get_total_amount(), 0);
6107 fn limits_total_cltv_delta() {
6108 let (secp_ctx, network, _, _, logger) = build_graph();
6109 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6110 let network_graph = network.read_only();
6112 let scorer = ln_test_utils::TestScorer::new();
6114 // Make sure that generally there is at least one route available
6115 let feasible_max_total_cltv_delta = 1008;
6116 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6117 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6118 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6119 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6120 let route_params = RouteParameters::from_payment_params_and_value(
6121 feasible_payment_params, 100);
6122 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6123 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6124 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6125 assert_ne!(path.len(), 0);
6127 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6128 let fail_max_total_cltv_delta = 23;
6129 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6130 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6131 let route_params = RouteParameters::from_payment_params_and_value(
6132 fail_payment_params, 100);
6133 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6134 &Default::default(), &random_seed_bytes)
6136 Err(LightningError { err, .. } ) => {
6137 assert_eq!(err, "Failed to find a path to the given destination");
6139 Ok(_) => panic!("Expected error"),
6144 fn avoids_recently_failed_paths() {
6145 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6146 // randomly inserting channels into it until we can't find a route anymore.
6147 let (secp_ctx, network, _, _, logger) = build_graph();
6148 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6149 let network_graph = network.read_only();
6151 let scorer = ln_test_utils::TestScorer::new();
6152 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6153 .with_max_path_count(1);
6154 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6155 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6157 // We should be able to find a route initially, and then after we fail a few random
6158 // channels eventually we won't be able to any longer.
6159 let route_params = RouteParameters::from_payment_params_and_value(
6160 payment_params.clone(), 100);
6161 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6162 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6164 let route_params = RouteParameters::from_payment_params_and_value(
6165 payment_params.clone(), 100);
6166 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6167 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6169 for chan in route.paths[0].hops.iter() {
6170 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6172 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6173 % route.paths[0].hops.len();
6174 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6180 fn limits_path_length() {
6181 let (secp_ctx, network, _, _, logger) = build_line_graph();
6182 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6183 let network_graph = network.read_only();
6185 let scorer = ln_test_utils::TestScorer::new();
6186 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6187 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6189 // First check we can actually create a long route on this graph.
6190 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6191 let route_params = RouteParameters::from_payment_params_and_value(
6192 feasible_payment_params, 100);
6193 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6194 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6195 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6196 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6198 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6199 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6200 let route_params = RouteParameters::from_payment_params_and_value(
6201 fail_payment_params, 100);
6202 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6203 &Default::default(), &random_seed_bytes)
6205 Err(LightningError { err, .. } ) => {
6206 assert_eq!(err, "Failed to find a path to the given destination");
6208 Ok(_) => panic!("Expected error"),
6213 fn adds_and_limits_cltv_offset() {
6214 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6215 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6217 let scorer = ln_test_utils::TestScorer::new();
6219 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6220 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6221 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6222 let route_params = RouteParameters::from_payment_params_and_value(
6223 payment_params.clone(), 100);
6224 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6225 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6226 assert_eq!(route.paths.len(), 1);
6228 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6230 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6231 let mut route_default = route.clone();
6232 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6233 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6234 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6235 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6236 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6238 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6239 let mut route_limited = route.clone();
6240 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6241 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6242 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6243 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6244 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6248 fn adds_plausible_cltv_offset() {
6249 let (secp_ctx, network, _, _, logger) = build_graph();
6250 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6251 let network_graph = network.read_only();
6252 let network_nodes = network_graph.nodes();
6253 let network_channels = network_graph.channels();
6254 let scorer = ln_test_utils::TestScorer::new();
6255 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6256 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6257 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6259 let route_params = RouteParameters::from_payment_params_and_value(
6260 payment_params.clone(), 100);
6261 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6262 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6263 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6265 let mut path_plausibility = vec![];
6267 for p in route.paths {
6268 // 1. Select random observation point
6269 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6270 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6272 prng.process_in_place(&mut random_bytes);
6273 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6274 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6276 // 2. Calculate what CLTV expiry delta we would observe there
6277 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6279 // 3. Starting from the observation point, find candidate paths
6280 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6281 candidates.push_back((observation_point, vec![]));
6283 let mut found_plausible_candidate = false;
6285 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6286 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6287 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6288 found_plausible_candidate = true;
6289 break 'candidate_loop;
6293 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6294 for channel_id in &cur_node.channels {
6295 if let Some(channel_info) = network_channels.get(&channel_id) {
6296 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6297 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6298 if cur_path_cltv_deltas.iter().sum::<u32>()
6299 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6300 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6301 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6302 candidates.push_back((*next_id, new_path_cltv_deltas));
6310 path_plausibility.push(found_plausible_candidate);
6312 assert!(path_plausibility.iter().all(|x| *x));
6316 fn builds_correct_path_from_hops() {
6317 let (secp_ctx, network, _, _, logger) = build_graph();
6318 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6319 let network_graph = network.read_only();
6321 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6322 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6324 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6325 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6326 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6327 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6328 Arc::clone(&logger), &random_seed_bytes).unwrap();
6329 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6330 assert_eq!(hops.len(), route.paths[0].hops.len());
6331 for (idx, hop_pubkey) in hops.iter().enumerate() {
6332 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6337 fn avoids_saturating_channels() {
6338 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6339 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6340 let decay_params = ProbabilisticScoringDecayParameters::default();
6341 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6343 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6344 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6345 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6347 short_channel_id: 4,
6350 cltv_expiry_delta: (4 << 4) | 1,
6351 htlc_minimum_msat: 0,
6352 htlc_maximum_msat: 250_000_000,
6354 fee_proportional_millionths: 0,
6355 excess_data: Vec::new()
6357 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6359 short_channel_id: 13,
6362 cltv_expiry_delta: (13 << 4) | 1,
6363 htlc_minimum_msat: 0,
6364 htlc_maximum_msat: 250_000_000,
6366 fee_proportional_millionths: 0,
6367 excess_data: Vec::new()
6370 let config = UserConfig::default();
6371 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6372 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6373 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6374 // 100,000 sats is less than the available liquidity on each channel, set above.
6375 let route_params = RouteParameters::from_payment_params_and_value(
6376 payment_params, 100_000_000);
6377 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6378 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6379 assert_eq!(route.paths.len(), 2);
6380 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6381 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6384 #[cfg(not(feature = "no-std"))]
6385 pub(super) fn random_init_seed() -> u64 {
6386 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6387 use core::hash::{BuildHasher, Hasher};
6388 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6389 println!("Using seed of {}", seed);
6394 #[cfg(not(feature = "no-std"))]
6395 fn generate_routes() {
6396 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6398 let logger = ln_test_utils::TestLogger::new();
6399 let graph = match super::bench_utils::read_network_graph(&logger) {
6407 let params = ProbabilisticScoringFeeParameters::default();
6408 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6409 let features = super::Bolt11InvoiceFeatures::empty();
6411 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6415 #[cfg(not(feature = "no-std"))]
6416 fn generate_routes_mpp() {
6417 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6419 let logger = ln_test_utils::TestLogger::new();
6420 let graph = match super::bench_utils::read_network_graph(&logger) {
6428 let params = ProbabilisticScoringFeeParameters::default();
6429 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6430 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6432 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6436 #[cfg(not(feature = "no-std"))]
6437 fn generate_large_mpp_routes() {
6438 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6440 let logger = ln_test_utils::TestLogger::new();
6441 let graph = match super::bench_utils::read_network_graph(&logger) {
6449 let params = ProbabilisticScoringFeeParameters::default();
6450 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6451 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6453 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6457 fn honors_manual_penalties() {
6458 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6459 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6461 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6462 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6464 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6465 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6467 // First check set manual penalties are returned by the scorer.
6468 let usage = ChannelUsage {
6470 inflight_htlc_msat: 0,
6471 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6473 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6474 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6475 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6477 // Then check we can get a normal route
6478 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6479 let route_params = RouteParameters::from_payment_params_and_value(
6480 payment_params, 100);
6481 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6482 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6483 assert!(route.is_ok());
6485 // Then check that we can't get a route if we ban an intermediate node.
6486 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6487 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6488 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6489 assert!(route.is_err());
6491 // Finally make sure we can route again, when we remove the ban.
6492 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6493 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6494 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6495 assert!(route.is_ok());
6499 fn abide_by_route_hint_max_htlc() {
6500 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6501 // params in the final route.
6502 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6503 let netgraph = network_graph.read_only();
6504 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6505 let scorer = ln_test_utils::TestScorer::new();
6506 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6507 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6508 let config = UserConfig::default();
6510 let max_htlc_msat = 50_000;
6511 let route_hint_1 = RouteHint(vec![RouteHintHop {
6512 src_node_id: nodes[2],
6513 short_channel_id: 42,
6516 proportional_millionths: 0,
6518 cltv_expiry_delta: 10,
6519 htlc_minimum_msat: None,
6520 htlc_maximum_msat: Some(max_htlc_msat),
6522 let dest_node_id = ln_test_utils::pubkey(42);
6523 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6524 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6525 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6527 // Make sure we'll error if our route hints don't have enough liquidity according to their
6528 // htlc_maximum_msat.
6529 let route_params = RouteParameters::from_payment_params_and_value(
6530 payment_params, max_htlc_msat + 1);
6531 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6532 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6535 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6536 } else { panic!(); }
6538 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6539 let mut route_hint_2 = route_hint_1.clone();
6540 route_hint_2.0[0].short_channel_id = 43;
6541 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6542 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6543 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6544 let route_params = RouteParameters::from_payment_params_and_value(
6545 payment_params, max_htlc_msat + 1);
6546 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6547 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6548 assert_eq!(route.paths.len(), 2);
6549 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6550 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6554 fn direct_channel_to_hints_with_max_htlc() {
6555 // Check that if we have a first hop channel peer that's connected to multiple provided route
6556 // hints, that we properly split the payment between the route hints if needed.
6557 let logger = Arc::new(ln_test_utils::TestLogger::new());
6558 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6559 let scorer = ln_test_utils::TestScorer::new();
6560 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6561 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6562 let config = UserConfig::default();
6564 let our_node_id = ln_test_utils::pubkey(42);
6565 let intermed_node_id = ln_test_utils::pubkey(43);
6566 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6568 let amt_msat = 900_000;
6569 let max_htlc_msat = 500_000;
6570 let route_hint_1 = RouteHint(vec![RouteHintHop {
6571 src_node_id: intermed_node_id,
6572 short_channel_id: 44,
6575 proportional_millionths: 0,
6577 cltv_expiry_delta: 10,
6578 htlc_minimum_msat: None,
6579 htlc_maximum_msat: Some(max_htlc_msat),
6581 src_node_id: intermed_node_id,
6582 short_channel_id: 45,
6585 proportional_millionths: 0,
6587 cltv_expiry_delta: 10,
6588 htlc_minimum_msat: None,
6589 // Check that later route hint max htlcs don't override earlier ones
6590 htlc_maximum_msat: Some(max_htlc_msat - 50),
6592 let mut route_hint_2 = route_hint_1.clone();
6593 route_hint_2.0[0].short_channel_id = 46;
6594 route_hint_2.0[1].short_channel_id = 47;
6595 let dest_node_id = ln_test_utils::pubkey(44);
6596 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6597 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6598 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6600 let route_params = RouteParameters::from_payment_params_and_value(
6601 payment_params, amt_msat);
6602 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6603 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6604 &Default::default(), &random_seed_bytes).unwrap();
6605 assert_eq!(route.paths.len(), 2);
6606 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6607 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6608 assert_eq!(route.get_total_amount(), amt_msat);
6610 // Re-run but with two first hop channels connected to the same route hint peers that must be
6612 let first_hops = vec![
6613 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6614 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6616 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6617 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6618 &Default::default(), &random_seed_bytes).unwrap();
6619 assert_eq!(route.paths.len(), 2);
6620 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6621 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6622 assert_eq!(route.get_total_amount(), amt_msat);
6624 // Make sure this works for blinded route hints.
6625 let blinded_path = BlindedPath {
6626 introduction_node_id: intermed_node_id,
6627 blinding_point: ln_test_utils::pubkey(42),
6629 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6630 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6633 let blinded_payinfo = BlindedPayInfo {
6635 fee_proportional_millionths: 0,
6636 htlc_minimum_msat: 1,
6637 htlc_maximum_msat: max_htlc_msat,
6638 cltv_expiry_delta: 10,
6639 features: BlindedHopFeatures::empty(),
6641 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6642 let payment_params = PaymentParameters::blinded(vec![
6643 (blinded_payinfo.clone(), blinded_path.clone()),
6644 (blinded_payinfo.clone(), blinded_path.clone())])
6645 .with_bolt12_features(bolt12_features).unwrap();
6646 let route_params = RouteParameters::from_payment_params_and_value(
6647 payment_params, amt_msat);
6648 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6649 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6650 &Default::default(), &random_seed_bytes).unwrap();
6651 assert_eq!(route.paths.len(), 2);
6652 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6653 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6654 assert_eq!(route.get_total_amount(), amt_msat);
6658 fn blinded_route_ser() {
6659 let blinded_path_1 = BlindedPath {
6660 introduction_node_id: ln_test_utils::pubkey(42),
6661 blinding_point: ln_test_utils::pubkey(43),
6663 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6664 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6667 let blinded_path_2 = BlindedPath {
6668 introduction_node_id: ln_test_utils::pubkey(46),
6669 blinding_point: ln_test_utils::pubkey(47),
6671 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6672 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6675 // (De)serialize a Route with 1 blinded path out of two total paths.
6676 let mut route = Route { paths: vec![Path {
6677 hops: vec![RouteHop {
6678 pubkey: ln_test_utils::pubkey(50),
6679 node_features: NodeFeatures::empty(),
6680 short_channel_id: 42,
6681 channel_features: ChannelFeatures::empty(),
6683 cltv_expiry_delta: 0,
6684 maybe_announced_channel: true,
6686 blinded_tail: Some(BlindedTail {
6687 hops: blinded_path_1.blinded_hops,
6688 blinding_point: blinded_path_1.blinding_point,
6689 excess_final_cltv_expiry_delta: 40,
6690 final_value_msat: 100,
6692 hops: vec![RouteHop {
6693 pubkey: ln_test_utils::pubkey(51),
6694 node_features: NodeFeatures::empty(),
6695 short_channel_id: 43,
6696 channel_features: ChannelFeatures::empty(),
6698 cltv_expiry_delta: 0,
6699 maybe_announced_channel: true,
6700 }], blinded_tail: None }],
6703 let encoded_route = route.encode();
6704 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6705 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6706 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6708 // (De)serialize a Route with two paths, each containing a blinded tail.
6709 route.paths[1].blinded_tail = Some(BlindedTail {
6710 hops: blinded_path_2.blinded_hops,
6711 blinding_point: blinded_path_2.blinding_point,
6712 excess_final_cltv_expiry_delta: 41,
6713 final_value_msat: 101,
6715 let encoded_route = route.encode();
6716 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6717 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6718 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6722 fn blinded_path_inflight_processing() {
6723 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6724 // account for the blinded tail's final amount_msat.
6725 let mut inflight_htlcs = InFlightHtlcs::new();
6726 let blinded_path = BlindedPath {
6727 introduction_node_id: ln_test_utils::pubkey(43),
6728 blinding_point: ln_test_utils::pubkey(48),
6729 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6732 hops: vec![RouteHop {
6733 pubkey: ln_test_utils::pubkey(42),
6734 node_features: NodeFeatures::empty(),
6735 short_channel_id: 42,
6736 channel_features: ChannelFeatures::empty(),
6738 cltv_expiry_delta: 0,
6739 maybe_announced_channel: false,
6742 pubkey: blinded_path.introduction_node_id,
6743 node_features: NodeFeatures::empty(),
6744 short_channel_id: 43,
6745 channel_features: ChannelFeatures::empty(),
6747 cltv_expiry_delta: 0,
6748 maybe_announced_channel: false,
6750 blinded_tail: Some(BlindedTail {
6751 hops: blinded_path.blinded_hops,
6752 blinding_point: blinded_path.blinding_point,
6753 excess_final_cltv_expiry_delta: 0,
6754 final_value_msat: 200,
6757 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6758 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6759 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6763 fn blinded_path_cltv_shadow_offset() {
6764 // Make sure we add a shadow offset when sending to blinded paths.
6765 let blinded_path = BlindedPath {
6766 introduction_node_id: ln_test_utils::pubkey(43),
6767 blinding_point: ln_test_utils::pubkey(44),
6769 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6770 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6773 let mut route = Route { paths: vec![Path {
6774 hops: vec![RouteHop {
6775 pubkey: ln_test_utils::pubkey(42),
6776 node_features: NodeFeatures::empty(),
6777 short_channel_id: 42,
6778 channel_features: ChannelFeatures::empty(),
6780 cltv_expiry_delta: 0,
6781 maybe_announced_channel: false,
6784 pubkey: blinded_path.introduction_node_id,
6785 node_features: NodeFeatures::empty(),
6786 short_channel_id: 43,
6787 channel_features: ChannelFeatures::empty(),
6789 cltv_expiry_delta: 0,
6790 maybe_announced_channel: false,
6793 blinded_tail: Some(BlindedTail {
6794 hops: blinded_path.blinded_hops,
6795 blinding_point: blinded_path.blinding_point,
6796 excess_final_cltv_expiry_delta: 0,
6797 final_value_msat: 200,
6799 }], route_params: None};
6801 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6802 let (_, network_graph, _, _, _) = build_line_graph();
6803 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6804 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6805 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6809 fn simple_blinded_route_hints() {
6810 do_simple_blinded_route_hints(1);
6811 do_simple_blinded_route_hints(2);
6812 do_simple_blinded_route_hints(3);
6815 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6816 // Check that we can generate a route to a blinded path with the expected hops.
6817 let (secp_ctx, network, _, _, logger) = build_graph();
6818 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6819 let network_graph = network.read_only();
6821 let scorer = ln_test_utils::TestScorer::new();
6822 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6823 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6825 let mut blinded_path = BlindedPath {
6826 introduction_node_id: nodes[2],
6827 blinding_point: ln_test_utils::pubkey(42),
6828 blinded_hops: Vec::with_capacity(num_blinded_hops),
6830 for i in 0..num_blinded_hops {
6831 blinded_path.blinded_hops.push(
6832 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6835 let blinded_payinfo = BlindedPayInfo {
6837 fee_proportional_millionths: 500,
6838 htlc_minimum_msat: 1000,
6839 htlc_maximum_msat: 100_000_000,
6840 cltv_expiry_delta: 15,
6841 features: BlindedHopFeatures::empty(),
6844 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6845 let route_params = RouteParameters::from_payment_params_and_value(
6846 payment_params, 1001);
6847 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6848 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6849 assert_eq!(route.paths.len(), 1);
6850 assert_eq!(route.paths[0].hops.len(), 2);
6852 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6853 assert_eq!(tail.hops, blinded_path.blinded_hops);
6854 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6855 assert_eq!(tail.final_value_msat, 1001);
6857 let final_hop = route.paths[0].hops.last().unwrap();
6858 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6859 if tail.hops.len() > 1 {
6860 assert_eq!(final_hop.fee_msat,
6861 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6862 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6864 assert_eq!(final_hop.fee_msat, 0);
6865 assert_eq!(final_hop.cltv_expiry_delta, 0);
6870 fn blinded_path_routing_errors() {
6871 // Check that we can generate a route to a blinded path with the expected hops.
6872 let (secp_ctx, network, _, _, logger) = build_graph();
6873 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6874 let network_graph = network.read_only();
6876 let scorer = ln_test_utils::TestScorer::new();
6877 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6878 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6880 let mut invalid_blinded_path = BlindedPath {
6881 introduction_node_id: nodes[2],
6882 blinding_point: ln_test_utils::pubkey(42),
6884 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6887 let blinded_payinfo = BlindedPayInfo {
6889 fee_proportional_millionths: 500,
6890 htlc_minimum_msat: 1000,
6891 htlc_maximum_msat: 100_000_000,
6892 cltv_expiry_delta: 15,
6893 features: BlindedHopFeatures::empty(),
6896 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6897 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6898 let payment_params = PaymentParameters::blinded(vec![
6899 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6900 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6901 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6902 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6903 &scorer, &Default::default(), &random_seed_bytes)
6905 Err(LightningError { err, .. }) => {
6906 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6908 _ => panic!("Expected error")
6911 invalid_blinded_path.introduction_node_id = our_id;
6912 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6913 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6914 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6915 &Default::default(), &random_seed_bytes)
6917 Err(LightningError { err, .. }) => {
6918 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6920 _ => panic!("Expected error")
6923 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6924 invalid_blinded_path.blinded_hops.clear();
6925 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6926 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6927 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6928 &Default::default(), &random_seed_bytes)
6930 Err(LightningError { err, .. }) => {
6931 assert_eq!(err, "0-hop blinded path provided");
6933 _ => panic!("Expected error")
6938 fn matching_intro_node_paths_provided() {
6939 // Check that if multiple blinded paths with the same intro node are provided in payment
6940 // parameters, we'll return the correct paths in the resulting MPP route.
6941 let (secp_ctx, network, _, _, logger) = build_graph();
6942 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6943 let network_graph = network.read_only();
6945 let scorer = ln_test_utils::TestScorer::new();
6946 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6947 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6948 let config = UserConfig::default();
6950 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6951 let blinded_path_1 = BlindedPath {
6952 introduction_node_id: nodes[2],
6953 blinding_point: ln_test_utils::pubkey(42),
6955 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6956 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6959 let blinded_payinfo_1 = BlindedPayInfo {
6961 fee_proportional_millionths: 0,
6962 htlc_minimum_msat: 0,
6963 htlc_maximum_msat: 30_000,
6964 cltv_expiry_delta: 0,
6965 features: BlindedHopFeatures::empty(),
6968 let mut blinded_path_2 = blinded_path_1.clone();
6969 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6970 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6971 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6973 let blinded_hints = vec![
6974 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6975 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6977 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6978 .with_bolt12_features(bolt12_features.clone()).unwrap();
6980 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
6981 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6982 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6983 assert_eq!(route.paths.len(), 2);
6984 let mut total_amount_paid_msat = 0;
6985 for path in route.paths.into_iter() {
6986 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6987 if let Some(bt) = &path.blinded_tail {
6988 assert_eq!(bt.blinding_point,
6989 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6990 .map(|(_, bp)| bp.blinding_point).unwrap());
6991 } else { panic!(); }
6992 total_amount_paid_msat += path.final_value_msat();
6994 assert_eq!(total_amount_paid_msat, 100_000);
6998 fn direct_to_intro_node() {
6999 // This previously caused a debug panic in the router when asserting
7000 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7001 // direct channels we failed to account for the fee charged for use of the blinded path.
7004 // node0 -1(1)2 - node1
7005 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7006 // doesn't account for the blinded path fee.
7008 let secp_ctx = Secp256k1::new();
7009 let logger = Arc::new(ln_test_utils::TestLogger::new());
7010 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7011 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7012 let scorer = ln_test_utils::TestScorer::new();
7013 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7014 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7016 let amt_msat = 10_000_000;
7017 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7018 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7019 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7020 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7022 short_channel_id: 1,
7025 cltv_expiry_delta: 42,
7026 htlc_minimum_msat: 1_000,
7027 htlc_maximum_msat: 10_000_000,
7029 fee_proportional_millionths: 0,
7030 excess_data: Vec::new()
7032 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7034 short_channel_id: 1,
7037 cltv_expiry_delta: 42,
7038 htlc_minimum_msat: 1_000,
7039 htlc_maximum_msat: 10_000_000,
7041 fee_proportional_millionths: 0,
7042 excess_data: Vec::new()
7044 let first_hops = vec![
7045 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7047 let blinded_path = BlindedPath {
7048 introduction_node_id: nodes[1],
7049 blinding_point: ln_test_utils::pubkey(42),
7051 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7052 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7055 let blinded_payinfo = BlindedPayInfo {
7056 fee_base_msat: 1000,
7057 fee_proportional_millionths: 0,
7058 htlc_minimum_msat: 1000,
7059 htlc_maximum_msat: MAX_VALUE_MSAT,
7060 cltv_expiry_delta: 0,
7061 features: BlindedHopFeatures::empty(),
7063 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7065 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7067 let netgraph = network_graph.read_only();
7068 let route_params = RouteParameters::from_payment_params_and_value(
7069 payment_params.clone(), amt_msat);
7070 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7071 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7072 &Default::default(), &random_seed_bytes) {
7073 assert_eq!(err, "Failed to find a path to the given destination");
7074 } else { panic!("Expected error") }
7076 // Sending an exact amount accounting for the blinded path fee works.
7077 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7078 let route_params = RouteParameters::from_payment_params_and_value(
7079 payment_params, amt_minus_blinded_path_fee);
7080 let route = get_route(&nodes[0], &route_params, &netgraph,
7081 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7082 &Default::default(), &random_seed_bytes).unwrap();
7083 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7084 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7088 fn direct_to_matching_intro_nodes() {
7089 // This previously caused us to enter `unreachable` code in the following situation:
7090 // 1. We add a route candidate for intro_node contributing a high amount
7091 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7092 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7093 // amount, and update our route candidate for intro_node for the lower amount
7094 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7095 // lower contribution amount, but fail (this was previously caused by failure to account for
7096 // blinded path fees when adding first_hop<>intro_node candidates)
7097 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7098 // candidate still thinks its path is contributing the original higher amount. This caused us
7099 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7101 let secp_ctx = Secp256k1::new();
7102 let logger = Arc::new(ln_test_utils::TestLogger::new());
7103 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7104 let scorer = ln_test_utils::TestScorer::new();
7105 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7106 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7107 let config = UserConfig::default();
7109 // Values are taken from the fuzz input that uncovered this panic.
7110 let amt_msat = 21_7020_5185_1403_2640;
7111 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7112 let first_hops = vec![
7113 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7114 18446744073709551615)];
7116 let blinded_path = BlindedPath {
7117 introduction_node_id: nodes[1],
7118 blinding_point: ln_test_utils::pubkey(42),
7120 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7121 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7124 let blinded_payinfo = BlindedPayInfo {
7125 fee_base_msat: 5046_2720,
7126 fee_proportional_millionths: 0,
7127 htlc_minimum_msat: 4503_5996_2737_0496,
7128 htlc_maximum_msat: 45_0359_9627_3704_9600,
7129 cltv_expiry_delta: 0,
7130 features: BlindedHopFeatures::empty(),
7132 let mut blinded_hints = vec![
7133 (blinded_payinfo.clone(), blinded_path.clone()),
7134 (blinded_payinfo.clone(), blinded_path.clone()),
7136 blinded_hints[1].0.fee_base_msat = 419_4304;
7137 blinded_hints[1].0.fee_proportional_millionths = 257;
7138 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7139 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7140 blinded_hints[1].0.cltv_expiry_delta = 0;
7142 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7143 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7144 .with_bolt12_features(bolt12_features.clone()).unwrap();
7146 let netgraph = network_graph.read_only();
7147 let route_params = RouteParameters::from_payment_params_and_value(
7148 payment_params, amt_msat);
7149 let route = get_route(&nodes[0], &route_params, &netgraph,
7150 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7151 &Default::default(), &random_seed_bytes).unwrap();
7152 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7153 assert_eq!(route.get_total_amount(), amt_msat);
7157 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
7158 pub(crate) mod bench_utils {
7162 use bitcoin::hashes::Hash;
7163 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7165 use crate::chain::transaction::OutPoint;
7166 use crate::routing::scoring::ScoreUpdate;
7167 use crate::sign::{EntropySource, KeysManager};
7168 use crate::ln::ChannelId;
7169 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
7170 use crate::ln::features::Bolt11InvoiceFeatures;
7171 use crate::routing::gossip::NetworkGraph;
7172 use crate::util::config::UserConfig;
7173 use crate::util::ser::ReadableArgs;
7174 use crate::util::test_utils::TestLogger;
7176 /// Tries to open a network graph file, or panics with a URL to fetch it.
7177 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
7178 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
7179 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
7180 .or_else(|_| { // Fall back to guessing based on the binary location
7181 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
7182 let mut path = std::env::current_exe().unwrap();
7183 path.pop(); // lightning-...
7185 path.pop(); // debug
7186 path.pop(); // target
7187 path.push("lightning");
7188 path.push("net_graph-2023-01-18.bin");
7191 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
7192 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
7193 let mut path = std::env::current_exe().unwrap();
7194 path.pop(); // bench...
7196 path.pop(); // debug
7197 path.pop(); // target
7198 path.pop(); // bench
7199 path.push("lightning");
7200 path.push("net_graph-2023-01-18.bin");
7203 .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");
7204 #[cfg(require_route_graph_test)]
7205 return Ok(res.unwrap());
7206 #[cfg(not(require_route_graph_test))]
7210 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
7211 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
7214 pub(crate) fn payer_pubkey() -> PublicKey {
7215 let secp_ctx = Secp256k1::new();
7216 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
7220 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
7222 channel_id: ChannelId::new_zero(),
7223 counterparty: ChannelCounterparty {
7224 features: channelmanager::provided_init_features(&UserConfig::default()),
7226 unspendable_punishment_reserve: 0,
7227 forwarding_info: None,
7228 outbound_htlc_minimum_msat: None,
7229 outbound_htlc_maximum_msat: None,
7231 funding_txo: Some(OutPoint {
7232 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
7235 short_channel_id: Some(1),
7236 inbound_scid_alias: None,
7237 outbound_scid_alias: None,
7238 channel_value_satoshis: 10_000_000_000,
7240 outbound_capacity_msat: 10_000_000_000,
7241 next_outbound_htlc_minimum_msat: 0,
7242 next_outbound_htlc_limit_msat: 10_000_000_000,
7243 inbound_capacity_msat: 0,
7244 unspendable_punishment_reserve: None,
7245 confirmations_required: None,
7246 confirmations: None,
7247 force_close_spend_delay: None,
7249 is_channel_ready: true,
7252 inbound_htlc_minimum_msat: None,
7253 inbound_htlc_maximum_msat: None,
7255 feerate_sat_per_1000_weight: None,
7256 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
7260 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
7261 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
7262 starting_amount: u64, route_count: usize,
7263 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
7264 let payer = payer_pubkey();
7265 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7266 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7268 let nodes = graph.read_only().nodes().clone();
7269 let mut route_endpoints = Vec::new();
7270 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
7271 // with some routes we picked being un-routable.
7272 for _ in 0..route_count * 3 / 2 {
7274 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7275 let src = PublicKey::from_slice(nodes.unordered_keys()
7276 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7277 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7278 let dst = PublicKey::from_slice(nodes.unordered_keys()
7279 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7280 let params = PaymentParameters::from_node_id(dst, 42)
7281 .with_bolt11_features(features.clone()).unwrap();
7282 let first_hop = first_hop(src);
7283 let amt_msat = starting_amount + seed % 1_000_000;
7284 let route_params = RouteParameters::from_payment_params_and_value(
7285 params.clone(), amt_msat);
7287 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
7288 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
7290 // ...and seed the scorer with success and failure data...
7291 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7292 let mut score_amt = seed % 1_000_000_000;
7294 // Generate fail/success paths for a wider range of potential amounts with
7295 // MPP enabled to give us a chance to apply penalties for more potential
7297 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7298 let params = PaymentParameters::from_node_id(dst, 42)
7299 .with_bolt11_features(mpp_features).unwrap();
7300 let route_params = RouteParameters::from_payment_params_and_value(
7301 params.clone(), score_amt);
7302 let route_res = get_route(&payer, &route_params, &graph.read_only(),
7303 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
7304 &random_seed_bytes);
7305 if let Ok(route) = route_res {
7306 for path in route.paths {
7307 if seed & 0x80 == 0 {
7308 scorer.payment_path_successful(&path);
7310 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7311 scorer.payment_path_failed(&path, short_channel_id);
7313 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7317 // If we couldn't find a path with a higer amount, reduce and try again.
7321 route_endpoints.push((first_hop, params, amt_msat));
7327 // Because we've changed channel scores, it's possible we'll take different routes to the
7328 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7329 // requires a too-high CLTV delta.
7330 route_endpoints.retain(|(first_hop, params, amt_msat)| {
7331 let route_params = RouteParameters::from_payment_params_and_value(
7332 params.clone(), *amt_msat);
7333 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7334 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7336 route_endpoints.truncate(route_count);
7337 assert_eq!(route_endpoints.len(), route_count);
7345 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7346 use crate::sign::{EntropySource, KeysManager};
7347 use crate::ln::channelmanager;
7348 use crate::ln::features::Bolt11InvoiceFeatures;
7349 use crate::routing::gossip::NetworkGraph;
7350 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7351 use crate::util::config::UserConfig;
7352 use crate::util::logger::{Logger, Record};
7353 use crate::util::test_utils::TestLogger;
7355 use criterion::Criterion;
7357 struct DummyLogger {}
7358 impl Logger for DummyLogger {
7359 fn log(&self, _record: &Record) {}
7362 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7363 let logger = TestLogger::new();
7364 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7365 let scorer = FixedPenaltyScorer::with_penalty(0);
7366 generate_routes(bench, &network_graph, scorer, &Default::default(),
7367 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
7370 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7371 let logger = TestLogger::new();
7372 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7373 let scorer = FixedPenaltyScorer::with_penalty(0);
7374 generate_routes(bench, &network_graph, scorer, &Default::default(),
7375 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7376 "generate_mpp_routes_with_zero_penalty_scorer");
7379 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7380 let logger = TestLogger::new();
7381 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7382 let params = ProbabilisticScoringFeeParameters::default();
7383 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7384 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7385 "generate_routes_with_probabilistic_scorer");
7388 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7389 let logger = TestLogger::new();
7390 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7391 let params = ProbabilisticScoringFeeParameters::default();
7392 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7393 generate_routes(bench, &network_graph, scorer, ¶ms,
7394 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7395 "generate_mpp_routes_with_probabilistic_scorer");
7398 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7399 let logger = TestLogger::new();
7400 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7401 let params = ProbabilisticScoringFeeParameters::default();
7402 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7403 generate_routes(bench, &network_graph, scorer, ¶ms,
7404 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7405 "generate_large_mpp_routes_with_probabilistic_scorer");
7408 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7409 let logger = TestLogger::new();
7410 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7411 let mut params = ProbabilisticScoringFeeParameters::default();
7412 params.linear_success_probability = false;
7413 let scorer = ProbabilisticScorer::new(
7414 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7415 generate_routes(bench, &network_graph, scorer, ¶ms,
7416 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7417 "generate_routes_with_nonlinear_probabilistic_scorer");
7420 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7421 let logger = TestLogger::new();
7422 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7423 let mut params = ProbabilisticScoringFeeParameters::default();
7424 params.linear_success_probability = false;
7425 let scorer = ProbabilisticScorer::new(
7426 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7427 generate_routes(bench, &network_graph, scorer, ¶ms,
7428 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7429 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
7432 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7433 let logger = TestLogger::new();
7434 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7435 let mut params = ProbabilisticScoringFeeParameters::default();
7436 params.linear_success_probability = false;
7437 let scorer = ProbabilisticScorer::new(
7438 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7439 generate_routes(bench, &network_graph, scorer, ¶ms,
7440 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7441 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
7444 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7445 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7446 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7447 bench_name: &'static str,
7449 let payer = bench_utils::payer_pubkey();
7450 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7451 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7453 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7454 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7456 // ...then benchmark finding paths between the nodes we learned.
7458 bench.bench_function(bench_name, |b| b.iter(|| {
7459 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7460 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
7461 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7462 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());