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, Debug, 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 impl fmt::Display for Route {
384 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
385 log_route!(self).fmt(f)
389 const SERIALIZATION_VERSION: u8 = 1;
390 const MIN_SERIALIZATION_VERSION: u8 = 1;
392 impl Writeable for Route {
393 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
394 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
395 (self.paths.len() as u64).write(writer)?;
396 let mut blinded_tails = Vec::new();
397 for path in self.paths.iter() {
398 (path.hops.len() as u8).write(writer)?;
399 for (idx, hop) in path.hops.iter().enumerate() {
401 if let Some(blinded_tail) = &path.blinded_tail {
402 if blinded_tails.is_empty() {
403 blinded_tails = Vec::with_capacity(path.hops.len());
405 blinded_tails.push(None);
408 blinded_tails.push(Some(blinded_tail));
409 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
412 write_tlv_fields!(writer, {
413 // For compatibility with LDK versions prior to 0.0.117, we take the individual
414 // RouteParameters' fields and reconstruct them on read.
415 (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
416 (2, blinded_tails, optional_vec),
417 (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
418 (5, self.route_params.as_ref().map(|p| p.max_total_routing_fee_msat), option),
424 impl Readable for Route {
425 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
426 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
427 let path_count: u64 = Readable::read(reader)?;
428 if path_count == 0 { return Err(DecodeError::InvalidValue); }
429 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
430 let mut min_final_cltv_expiry_delta = u32::max_value();
431 for _ in 0..path_count {
432 let hop_count: u8 = Readable::read(reader)?;
433 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
434 for _ in 0..hop_count {
435 hops.push(Readable::read(reader)?);
437 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
438 min_final_cltv_expiry_delta =
439 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
440 paths.push(Path { hops, blinded_tail: None });
442 _init_and_read_len_prefixed_tlv_fields!(reader, {
443 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
444 (2, blinded_tails, optional_vec),
445 (3, final_value_msat, option),
446 (5, max_total_routing_fee_msat, option)
448 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
449 if blinded_tails.len() != 0 {
450 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
451 for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
452 path.blinded_tail = blinded_tail_opt;
456 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
457 let route_params = match (payment_params, final_value_msat) {
458 (Some(payment_params), Some(final_value_msat)) => {
459 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
464 Ok(Route { paths, route_params })
468 /// Parameters needed to find a [`Route`].
470 /// Passed to [`find_route`] and [`build_route_from_hops`].
471 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
472 pub struct RouteParameters {
473 /// The parameters of the failed payment path.
474 pub payment_params: PaymentParameters,
476 /// The amount in msats sent on the failed payment path.
477 pub final_value_msat: u64,
479 /// The maximum total fees, in millisatoshi, that may accrue during route finding.
481 /// This limit also applies to the total fees that may arise while retrying failed payment
484 /// Note that values below a few sats may result in some paths being spuriously ignored.
485 pub max_total_routing_fee_msat: Option<u64>,
488 impl RouteParameters {
489 /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
491 /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
492 pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
493 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
497 impl Writeable for RouteParameters {
498 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
499 write_tlv_fields!(writer, {
500 (0, self.payment_params, required),
501 (1, self.max_total_routing_fee_msat, option),
502 (2, self.final_value_msat, required),
503 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
504 // `RouteParameters` directly. For compatibility, we write it here.
505 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
511 impl Readable for RouteParameters {
512 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
513 _init_and_read_len_prefixed_tlv_fields!(reader, {
514 (0, payment_params, (required: ReadableArgs, 0)),
515 (1, max_total_routing_fee_msat, option),
516 (2, final_value_msat, required),
517 (4, final_cltv_delta, option),
519 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
520 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
521 if final_cltv_expiry_delta == &0 {
522 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
527 final_value_msat: final_value_msat.0.unwrap(),
528 max_total_routing_fee_msat,
533 /// Maximum total CTLV difference we allow for a full payment path.
534 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
536 /// Maximum number of paths we allow an (MPP) payment to have.
537 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
538 // limits, but for now more than 10 paths likely carries too much one-path failure.
539 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
541 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
543 // The median hop CLTV expiry delta currently seen in the network.
544 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
546 // During routing, we only consider paths shorter than our maximum length estimate.
547 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
548 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
549 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
551 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
552 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
553 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
554 // (payment_secret and total_msat) = 93 bytes for the final hop.
555 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
556 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
557 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
559 /// Information used to route a payment.
560 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
561 pub struct PaymentParameters {
562 /// Information about the payee, such as their features and route hints for their channels.
565 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
566 pub expiry_time: Option<u64>,
568 /// The maximum total CLTV delta we accept for the route.
569 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
570 pub max_total_cltv_expiry_delta: u32,
572 /// The maximum number of paths that may be used by (MPP) payments.
573 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
574 pub max_path_count: u8,
576 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
577 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
578 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
579 /// increasing failure probability for those paths.
581 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
582 /// restriction have been found. While paths which meet this criteria will be searched for, it
583 /// is ultimately up to the scorer to select them over other paths.
585 /// A value of 0 will allow payments up to and including a channel's total announced usable
586 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
589 pub max_channel_saturation_power_of_half: u8,
591 /// A list of SCIDs which this payment was previously attempted over and which caused the
592 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
594 pub previously_failed_channels: Vec<u64>,
597 impl Writeable for PaymentParameters {
598 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
599 let mut clear_hints = &vec![];
600 let mut blinded_hints = &vec![];
602 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
603 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
605 write_tlv_fields!(writer, {
606 (0, self.payee.node_id(), option),
607 (1, self.max_total_cltv_expiry_delta, required),
608 (2, self.payee.features(), option),
609 (3, self.max_path_count, required),
610 (4, *clear_hints, required_vec),
611 (5, self.max_channel_saturation_power_of_half, required),
612 (6, self.expiry_time, option),
613 (7, self.previously_failed_channels, required_vec),
614 (8, *blinded_hints, optional_vec),
615 (9, self.payee.final_cltv_expiry_delta(), option),
621 impl ReadableArgs<u32> for PaymentParameters {
622 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
623 _init_and_read_len_prefixed_tlv_fields!(reader, {
624 (0, payee_pubkey, option),
625 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
626 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
627 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
628 (4, clear_route_hints, required_vec),
629 (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
630 (6, expiry_time, option),
631 (7, previously_failed_channels, optional_vec),
632 (8, blinded_route_hints, optional_vec),
633 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
635 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
636 let payee = if blinded_route_hints.len() != 0 {
637 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
639 route_hints: blinded_route_hints,
640 features: features.and_then(|f: Features| f.bolt12()),
644 route_hints: clear_route_hints,
645 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
646 features: features.and_then(|f| f.bolt11()),
647 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
651 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
652 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
654 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
656 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
662 impl PaymentParameters {
663 /// Creates a payee with the node id of the given `pubkey`.
665 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
667 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
669 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
671 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
672 max_path_count: DEFAULT_MAX_PATH_COUNT,
673 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
674 previously_failed_channels: Vec::new(),
678 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
680 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
683 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
684 /// whether your router will be allowed to find a multi-part route for this payment. If you
685 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
686 /// [`RecipientOnionFields::secret_only`].
688 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
689 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
690 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
691 .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
692 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
695 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
696 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
697 /// [`PaymentParameters::expiry_time`].
698 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
699 Self::blinded(invoice.payment_paths().to_vec())
700 .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
701 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
704 /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
705 pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
707 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
709 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
710 max_path_count: DEFAULT_MAX_PATH_COUNT,
711 max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
712 previously_failed_channels: Vec::new(),
716 /// Includes the payee's features. Errors if the parameters were not initialized with
717 /// [`PaymentParameters::from_bolt12_invoice`].
719 /// This is not exported to bindings users since bindings don't support move semantics
720 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
722 Payee::Clear { .. } => Err(()),
723 Payee::Blinded { route_hints, .. } =>
724 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
728 /// Includes the payee's features. Errors if the parameters were initialized with
729 /// [`PaymentParameters::from_bolt12_invoice`].
731 /// This is not exported to bindings users since bindings don't support move semantics
732 pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
734 Payee::Blinded { .. } => Err(()),
735 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
737 payee: Payee::Clear {
738 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
744 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
745 /// [`PaymentParameters::from_bolt12_invoice`].
747 /// This is not exported to bindings users since bindings don't support move semantics
748 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
750 Payee::Blinded { .. } => Err(()),
751 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
753 payee: Payee::Clear {
754 route_hints, node_id, features, final_cltv_expiry_delta,
760 /// Includes a payment expiration in seconds relative to the UNIX epoch.
762 /// This is not exported to bindings users since bindings don't support move semantics
763 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
764 Self { expiry_time: Some(expiry_time), ..self }
767 /// Includes a limit for the total CLTV expiry delta which is considered during routing
769 /// This is not exported to bindings users since bindings don't support move semantics
770 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
771 Self { max_total_cltv_expiry_delta, ..self }
774 /// Includes a limit for the maximum number of payment paths that may be used.
776 /// This is not exported to bindings users since bindings don't support move semantics
777 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
778 Self { max_path_count, ..self }
781 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
782 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
784 /// This is not exported to bindings users since bindings don't support move semantics
785 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
786 Self { max_channel_saturation_power_of_half, ..self }
790 /// The recipient of a payment, differing based on whether they've hidden their identity with route
792 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
794 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
795 /// will be included in the final [`Route`].
797 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
799 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
800 /// Features supported by the payee.
802 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
804 features: Option<Bolt12InvoiceFeatures>,
806 /// The recipient included these route hints in their BOLT11 invoice.
808 /// The node id of the payee.
810 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
811 route_hints: Vec<RouteHint>,
812 /// Features supported by the payee.
814 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
815 /// does not contain any features.
817 /// [`for_keysend`]: PaymentParameters::for_keysend
818 features: Option<Bolt11InvoiceFeatures>,
819 /// The minimum CLTV delta at the end of the route. This value must not be zero.
820 final_cltv_expiry_delta: u32,
825 fn node_id(&self) -> Option<PublicKey> {
827 Self::Clear { node_id, .. } => Some(*node_id),
831 fn node_features(&self) -> Option<NodeFeatures> {
833 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
834 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
837 fn supports_basic_mpp(&self) -> bool {
839 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
840 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
843 fn features(&self) -> Option<FeaturesRef> {
845 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
846 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
849 fn final_cltv_expiry_delta(&self) -> Option<u32> {
851 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
855 fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
857 Self::Blinded { route_hints, .. } => &route_hints[..],
858 Self::Clear { .. } => &[]
862 fn unblinded_route_hints(&self) -> &[RouteHint] {
864 Self::Blinded { .. } => &[],
865 Self::Clear { route_hints, .. } => &route_hints[..]
870 enum FeaturesRef<'a> {
871 Bolt11(&'a Bolt11InvoiceFeatures),
872 Bolt12(&'a Bolt12InvoiceFeatures),
875 Bolt11(Bolt11InvoiceFeatures),
876 Bolt12(Bolt12InvoiceFeatures),
880 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
882 Self::Bolt12(f) => Some(f),
886 fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
888 Self::Bolt11(f) => Some(f),
894 impl<'a> Writeable for FeaturesRef<'a> {
895 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
897 Self::Bolt11(f) => Ok(f.write(w)?),
898 Self::Bolt12(f) => Ok(f.write(w)?),
903 impl ReadableArgs<bool> for Features {
904 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
905 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
906 Ok(Self::Bolt12(Readable::read(reader)?))
910 /// A list of hops along a payment path terminating with a channel to the recipient.
911 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
912 pub struct RouteHint(pub Vec<RouteHintHop>);
914 impl Writeable for RouteHint {
915 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
916 (self.0.len() as u64).write(writer)?;
917 for hop in self.0.iter() {
924 impl Readable for RouteHint {
925 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
926 let hop_count: u64 = Readable::read(reader)?;
927 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
928 for _ in 0..hop_count {
929 hops.push(Readable::read(reader)?);
935 /// A channel descriptor for a hop along a payment path.
936 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
937 pub struct RouteHintHop {
938 /// The node_id of the non-target end of the route
939 pub src_node_id: PublicKey,
940 /// The short_channel_id of this channel
941 pub short_channel_id: u64,
942 /// The fees which must be paid to use this channel
943 pub fees: RoutingFees,
944 /// The difference in CLTV values between this node and the next node.
945 pub cltv_expiry_delta: u16,
946 /// The minimum value, in msat, which must be relayed to the next hop.
947 pub htlc_minimum_msat: Option<u64>,
948 /// The maximum value in msat available for routing with a single HTLC.
949 pub htlc_maximum_msat: Option<u64>,
952 impl_writeable_tlv_based!(RouteHintHop, {
953 (0, src_node_id, required),
954 (1, htlc_minimum_msat, option),
955 (2, short_channel_id, required),
956 (3, htlc_maximum_msat, option),
958 (6, cltv_expiry_delta, required),
961 #[derive(Eq, PartialEq)]
962 struct RouteGraphNode {
964 lowest_fee_to_node: u64,
965 total_cltv_delta: u32,
966 // The maximum value a yet-to-be-constructed payment path might flow through this node.
967 // This value is upper-bounded by us by:
968 // - how much is needed for a path being constructed
969 // - how much value can channels following this node (up to the destination) can contribute,
970 // considering their capacity and fees
971 value_contribution_msat: u64,
972 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
973 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
974 path_htlc_minimum_msat: u64,
975 /// All penalties incurred from this hop on the way to the destination, as calculated using
977 path_penalty_msat: u64,
978 /// The number of hops walked up to this node.
979 path_length_to_node: u8,
982 impl cmp::Ord for RouteGraphNode {
983 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
984 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
985 .saturating_add(other.path_penalty_msat);
986 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
987 .saturating_add(self.path_penalty_msat);
988 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
992 impl cmp::PartialOrd for RouteGraphNode {
993 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
994 Some(self.cmp(other))
998 /// A wrapper around the various hop representations.
1000 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
1001 #[derive(Clone, Debug)]
1002 enum CandidateRouteHop<'a> {
1003 /// A hop from the payer, where the outbound liquidity is known.
1005 details: &'a ChannelDetails,
1007 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
1009 info: DirectedChannelInfo<'a>,
1010 short_channel_id: u64,
1012 /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
1015 hint: &'a RouteHintHop,
1017 /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
1019 hint: &'a (BlindedPayInfo, BlindedPath),
1022 /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
1023 /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
1024 /// introduction node and the destination. Useful for tracking that we need to include a blinded
1025 /// path at the end of our [`Route`].
1027 hint: &'a (BlindedPayInfo, BlindedPath),
1032 impl<'a> CandidateRouteHop<'a> {
1033 fn short_channel_id(&self) -> Option<u64> {
1035 CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
1036 CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
1037 CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
1038 CandidateRouteHop::Blinded { .. } => None,
1039 CandidateRouteHop::OneHopBlinded { .. } => None,
1043 // NOTE: This may alloc memory so avoid calling it in a hot code path.
1044 fn features(&self) -> ChannelFeatures {
1046 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
1047 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
1048 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
1049 CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
1050 CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
1054 fn cltv_expiry_delta(&self) -> u32 {
1056 CandidateRouteHop::FirstHop { .. } => 0,
1057 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
1058 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
1059 CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
1060 CandidateRouteHop::OneHopBlinded { .. } => 0,
1064 fn htlc_minimum_msat(&self) -> u64 {
1066 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
1067 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
1068 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
1069 CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1070 CandidateRouteHop::OneHopBlinded { .. } => 0,
1074 fn fees(&self) -> RoutingFees {
1076 CandidateRouteHop::FirstHop { .. } => RoutingFees {
1077 base_msat: 0, proportional_millionths: 0,
1079 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1080 CandidateRouteHop::PrivateHop { hint } => hint.fees,
1081 CandidateRouteHop::Blinded { hint, .. } => {
1083 base_msat: hint.0.fee_base_msat,
1084 proportional_millionths: hint.0.fee_proportional_millionths
1087 CandidateRouteHop::OneHopBlinded { .. } =>
1088 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1092 fn effective_capacity(&self) -> EffectiveCapacity {
1094 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1095 liquidity_msat: details.next_outbound_htlc_limit_msat,
1097 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1098 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1099 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1100 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1101 EffectiveCapacity::Infinite,
1102 CandidateRouteHop::Blinded { hint, .. } =>
1103 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1104 CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1108 fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1110 CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1111 CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1112 _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1115 fn blinded_path(&self) -> Option<&'a BlindedPath> {
1117 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1125 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1126 enum CandidateHopId {
1127 /// Contains (scid, src_node_id < target_node_id)
1129 /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1134 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1135 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1137 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1138 EffectiveCapacity::Infinite => u64::max_value(),
1139 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1140 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1141 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1142 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1143 // expected to have been generated from up-to-date capacity information.
1144 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1145 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1146 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1150 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1151 -> bool where I1::Item: PartialEq<I2::Item> {
1153 let a = iter_a.next();
1154 let b = iter_b.next();
1155 if a.is_none() && b.is_none() { return true; }
1156 if a.is_none() || b.is_none() { return false; }
1157 if a.unwrap().ne(&b.unwrap()) { return false; }
1161 /// It's useful to keep track of the hops associated with the fees required to use them,
1162 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1163 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1164 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1166 struct PathBuildingHop<'a> {
1167 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1168 // is a larger refactor and will require careful performance analysis.
1170 candidate: CandidateRouteHop<'a>,
1173 /// All the fees paid *after* this channel on the way to the destination
1174 next_hops_fee_msat: u64,
1175 /// Fee paid for the use of the current channel (see candidate.fees()).
1176 /// The value will be actually deducted from the counterparty balance on the previous link.
1177 hop_use_fee_msat: u64,
1178 /// Used to compare channels when choosing the for routing.
1179 /// Includes paying for the use of a hop and the following hops, as well as
1180 /// an estimated cost of reaching this hop.
1181 /// Might get stale when fees are recomputed. Primarily for internal use.
1182 total_fee_msat: u64,
1183 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1184 /// walk and may be invalid thereafter.
1185 path_htlc_minimum_msat: u64,
1186 /// All penalties incurred from this channel on the way to the destination, as calculated using
1187 /// channel scoring.
1188 path_penalty_msat: u64,
1189 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1190 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1191 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1192 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1193 /// avoid processing them again.
1194 was_processed: bool,
1195 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1196 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1197 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1198 // value_contribution_msat, which requires tracking it here. See comments below where it is
1199 // used for more info.
1200 value_contribution_msat: u64,
1203 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1204 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1205 let mut debug_struct = f.debug_struct("PathBuildingHop");
1207 .field("node_id", &self.node_id)
1208 .field("short_channel_id", &self.candidate.short_channel_id())
1209 .field("total_fee_msat", &self.total_fee_msat)
1210 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1211 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1212 .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)))
1213 .field("path_penalty_msat", &self.path_penalty_msat)
1214 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1215 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1216 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1217 let debug_struct = debug_struct
1218 .field("value_contribution_msat", &self.value_contribution_msat);
1219 debug_struct.finish()
1223 // Instantiated with a list of hops with correct data in them collected during path finding,
1224 // an instance of this struct should be further modified only via given methods.
1226 struct PaymentPath<'a> {
1227 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1230 impl<'a> PaymentPath<'a> {
1231 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1232 fn get_value_msat(&self) -> u64 {
1233 self.hops.last().unwrap().0.fee_msat
1236 fn get_path_penalty_msat(&self) -> u64 {
1237 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1240 fn get_total_fee_paid_msat(&self) -> u64 {
1241 if self.hops.len() < 1 {
1245 // Can't use next_hops_fee_msat because it gets outdated.
1246 for (i, (hop, _)) in self.hops.iter().enumerate() {
1247 if i != self.hops.len() - 1 {
1248 result += hop.fee_msat;
1254 fn get_cost_msat(&self) -> u64 {
1255 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1258 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1259 // to change fees may result in an inconsistency.
1261 // Sometimes we call this function right after constructing a path which is inconsistent in
1262 // that it the value being transferred has decreased while we were doing path finding, leading
1263 // to the fees being paid not lining up with the actual limits.
1265 // Note that this function is not aware of the available_liquidity limit, and thus does not
1266 // support increasing the value being transferred beyond what was selected during the initial
1268 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1269 let mut total_fee_paid_msat = 0 as u64;
1270 for i in (0..self.hops.len()).rev() {
1271 let last_hop = i == self.hops.len() - 1;
1273 // For non-last-hop, this value will represent the fees paid on the current hop. It
1274 // will consist of the fees for the use of the next hop, and extra fees to match
1275 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1276 let mut cur_hop_fees_msat = 0;
1278 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1281 let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1282 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1283 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1284 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1285 // set it too high just to maliciously take more fees by exploiting this
1286 // match htlc_minimum_msat logic.
1287 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1288 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1289 // Note that there is a risk that *previous hops* (those closer to us, as we go
1290 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1292 // This might make us end up with a broken route, although this should be super-rare
1293 // in practice, both because of how healthy channels look like, and how we pick
1294 // channels in add_entry.
1295 // Also, this can't be exploited more heavily than *announce a free path and fail
1297 cur_hop_transferred_amount_msat += extra_fees_msat;
1298 total_fee_paid_msat += extra_fees_msat;
1299 cur_hop_fees_msat += extra_fees_msat;
1303 // Final hop is a special case: it usually has just value_msat (by design), but also
1304 // it still could overpay for the htlc_minimum_msat.
1305 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1307 // Propagate updated fees for the use of the channels to one hop back, where they
1308 // will be actually paid (fee_msat). The last hop is handled above separately.
1309 cur_hop.fee_msat = cur_hop_fees_msat;
1312 // Fee for the use of the current hop which will be deducted on the previous hop.
1313 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1314 // this channel is free for us.
1316 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1317 cur_hop.hop_use_fee_msat = new_fee;
1318 total_fee_paid_msat += new_fee;
1320 // It should not be possible because this function is called only to reduce the
1321 // value. In that case, compute_fee was already called with the same fees for
1322 // larger amount and there was no overflow.
1331 /// Calculate the fees required to route the given amount over a channel with the given fees.
1332 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1333 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1334 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1338 /// Calculate the fees required to route the given amount over a channel with the given fees,
1339 /// saturating to [`u64::max_value`].
1340 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1341 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1342 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1343 .saturating_add(channel_fees.base_msat as u64)
1346 /// The default `features` we assume for a node in a route, when no `features` are known about that
1349 /// Default features are:
1350 /// * variable_length_onion_optional
1351 fn default_node_features() -> NodeFeatures {
1352 let mut features = NodeFeatures::empty();
1353 features.set_variable_length_onion_optional();
1357 struct LoggedPayeePubkey(Option<PublicKey>);
1358 impl fmt::Display for LoggedPayeePubkey {
1359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1362 "payee node id ".fmt(f)?;
1366 "blinded payee".fmt(f)
1372 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1373 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1374 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1376 CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1377 "blinded route hint with introduction node id ".fmt(f)?;
1378 hint.1.introduction_node_id.fmt(f)?;
1379 " and blinding point ".fmt(f)?;
1380 hint.1.blinding_point.fmt(f)
1382 CandidateRouteHop::FirstHop { .. } => {
1383 "first hop with SCID ".fmt(f)?;
1384 self.0.short_channel_id().unwrap().fmt(f)
1386 CandidateRouteHop::PrivateHop { .. } => {
1387 "route hint with SCID ".fmt(f)?;
1388 self.0.short_channel_id().unwrap().fmt(f)
1392 self.0.short_channel_id().unwrap().fmt(f)
1399 fn sort_first_hop_channels(
1400 channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1401 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1403 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1404 // most like to use.
1406 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1407 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1410 // Second, because simply always sorting in descending order would always use our largest
1411 // available outbound capacity, needlessly fragmenting our available channel capacities,
1412 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1413 // which have enough, but not too much, capacity for the payment.
1415 // Available outbound balances factor in liquidity already reserved for previously found paths.
1416 channels.sort_unstable_by(|chan_a, chan_b| {
1417 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1418 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1419 our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1420 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1421 .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1422 our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1423 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1424 // Sort in descending order
1425 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1427 // Sort in ascending order
1428 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1433 /// Finds a route from us (payer) to the given target node (payee).
1435 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1436 /// in the given [`RouteParameters::payment_params`].
1437 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1439 /// Private routing paths between a public node and the target may be included in the `payee` field
1440 /// of [`RouteParameters::payment_params`].
1442 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1443 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1444 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1446 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1447 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1448 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1452 /// Panics if first_hops contains channels without `short_channel_id`s;
1453 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1455 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1456 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1457 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1458 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1459 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1460 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1461 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1462 ) -> Result<Route, LightningError>
1463 where L::Target: Logger, GL::Target: Logger {
1464 let graph_lock = network_graph.read_only();
1465 let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1466 scorer, score_params, random_seed_bytes)?;
1467 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1471 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1472 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1473 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1474 _random_seed_bytes: &[u8; 32]
1475 ) -> Result<Route, LightningError>
1476 where L::Target: Logger {
1478 let payment_params = &route_params.payment_params;
1479 let final_value_msat = route_params.final_value_msat;
1480 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1481 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1482 // so use a dummy id for this in the blinded case.
1483 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1484 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1485 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1486 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1487 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1489 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1490 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1493 if final_value_msat > MAX_VALUE_MSAT {
1494 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1497 if final_value_msat == 0 {
1498 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1501 match &payment_params.payee {
1502 Payee::Clear { route_hints, node_id, .. } => {
1503 for route in route_hints.iter() {
1504 for hop in &route.0 {
1505 if hop.src_node_id == *node_id {
1506 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1511 Payee::Blinded { route_hints, .. } => {
1512 if route_hints.iter().all(|(_, path)| &path.introduction_node_id == our_node_pubkey) {
1513 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});
1515 for (_, blinded_path) in route_hints.iter() {
1516 if blinded_path.blinded_hops.len() == 0 {
1517 return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1518 } else if &blinded_path.introduction_node_id == our_node_pubkey {
1519 log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1520 } else if blinded_path.blinded_hops.len() == 1 &&
1521 route_hints.iter().any( |(_, p)| p.blinded_hops.len() == 1
1522 && p.introduction_node_id != blinded_path.introduction_node_id)
1524 return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1529 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1530 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1531 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});
1534 // The general routing idea is the following:
1535 // 1. Fill first/last hops communicated by the caller.
1536 // 2. Attempt to construct a path from payer to payee for transferring
1537 // any ~sufficient (described later) value.
1538 // If succeed, remember which channels were used and how much liquidity they have available,
1539 // so that future paths don't rely on the same liquidity.
1540 // 3. Proceed to the next step if:
1541 // - we hit the recommended target value;
1542 // - OR if we could not construct a new path. Any next attempt will fail too.
1543 // Otherwise, repeat step 2.
1544 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1545 // (not recommended value).
1546 // 5. If yes, proceed. If not, fail routing.
1547 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1548 // transferred up to the transfer target value.
1549 // 7. Reduce the value of the last path until we are sending only the target value.
1550 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1551 // them so that we're not sending two HTLCs along the same path.
1553 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1554 // distance from the payee
1556 // We are not a faithful Dijkstra's implementation because we can change values which impact
1557 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1558 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1559 // the value we are currently attempting to send over a path, we simply reduce the value being
1560 // sent along the path for any hops after that channel. This may imply that later fees (which
1561 // we've already tabulated) are lower because a smaller value is passing through the channels
1562 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1563 // channels which were selected earlier (and which may still be used for other paths without a
1564 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1567 // One potentially problematic case for this algorithm would be if there are many
1568 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1569 // graph walking), we may never find a path which is not liquidity-limited and has lower
1570 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1571 // Because we only consider paths with at least 5% of the total value being sent, the damage
1572 // from such a case should be limited, however this could be further reduced in the future by
1573 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1574 // limits for the purposes of fee calculation.
1576 // Alternatively, we could store more detailed path information in the heap (targets, below)
1577 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1578 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1579 // and practically (as we would need to store dynamically-allocated path information in heap
1580 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1581 // results of such an algorithm would likely be biased towards lower-value paths.
1583 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1584 // outside of our current search value, running a path search more times to gather candidate
1585 // paths at different values. While this may be acceptable, further path searches may increase
1586 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1587 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1588 // the same time, remaining generic across different payment values.
1590 let network_channels = network_graph.channels();
1591 let network_nodes = network_graph.nodes();
1593 if payment_params.max_path_count == 0 {
1594 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1597 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1598 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1600 let allow_mpp = if payment_params.max_path_count == 1 {
1602 } else if payment_params.payee.supports_basic_mpp() {
1604 } else if let Some(payee) = payee_node_id_opt {
1605 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1606 |info| info.features.supports_basic_mpp()))
1609 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1610 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1611 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1614 // Prepare the data we'll use for payee-to-payer search by
1615 // inserting first hops suggested by the caller as targets.
1616 // Our search will then attempt to reach them while traversing from the payee node.
1617 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1618 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1619 if let Some(hops) = first_hops {
1621 if chan.get_outbound_payment_scid().is_none() {
1622 panic!("first_hops should be filled in with usable channels, not pending ones");
1624 if chan.counterparty.node_id == *our_node_pubkey {
1625 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1628 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1629 .or_insert(Vec::new())
1632 if first_hop_targets.is_empty() {
1633 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1637 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1638 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1639 // adding duplicate entries when we find a better path to a given node.
1640 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1642 // Map from node_id to information about the best current path to that node, including feerate
1644 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1646 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1647 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1648 // htlc_minimum with extra fees while still finding a cheaper path.
1649 let mut hit_minimum_limit;
1651 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1652 // We start with a path_value of the exact amount we want, and if that generates a route we may
1653 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1654 // amount we want in total across paths, selecting the best subset at the end.
1655 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1656 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1657 let mut path_value_msat = final_value_msat;
1659 // Routing Fragmentation Mitigation heuristic:
1661 // Routing fragmentation across many payment paths increases the overall routing
1662 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1663 // Taking too many smaller paths also increases the chance of payment failure.
1664 // Thus to avoid this effect, we require from our collected links to provide
1665 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1666 // This requirement is currently set to be 1/max_path_count of the payment
1667 // value to ensure we only ever return routes that do not violate this limit.
1668 let minimal_value_contribution_msat: u64 = if allow_mpp {
1669 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1674 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1675 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1676 // drop the requirement by setting this to 0.
1677 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1679 // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1680 // determine if the channel can be used by additional MPP paths or to inform path finding
1681 // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1682 // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1684 let mut used_liquidities: HashMap<CandidateHopId, u64> =
1685 HashMap::with_capacity(network_nodes.len());
1687 // Keeping track of how much value we already collected across other paths. Helps to decide
1688 // when we want to stop looking for new paths.
1689 let mut already_collected_value_msat = 0;
1691 for (_, channels) in first_hop_targets.iter_mut() {
1692 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1696 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1697 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1699 // Remember how many candidates we ignored to allow for some logging afterwards.
1700 let mut num_ignored_value_contribution = 0;
1701 let mut num_ignored_path_length_limit = 0;
1702 let mut num_ignored_cltv_delta_limit = 0;
1703 let mut num_ignored_previously_failed = 0;
1704 let mut num_ignored_total_fee_limit = 0;
1706 macro_rules! add_entry {
1707 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1708 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1709 // since that value has to be transferred over this channel.
1710 // Returns whether this channel caused an update to `targets`.
1711 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1712 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1713 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1714 // We "return" whether we updated the path at the end, and how much we can route via
1715 // this channel, via this:
1716 let mut did_add_update_path_to_src_node = None;
1717 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1718 // practice these cases should be caught earlier:
1719 // - for regular channels at channel announcement (TODO)
1720 // - for first and last hops early in get_route
1721 if $src_node_id != $dest_node_id {
1722 let scid_opt = $candidate.short_channel_id();
1723 let effective_capacity = $candidate.effective_capacity();
1724 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1726 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1727 // It may be misleading because we might later choose to reduce the value transferred
1728 // over these channels, and the channel which was insufficient might become sufficient.
1729 // Worst case: we drop a good channel here because it can't cover the high following
1730 // fees caused by one expensive channel, but then this channel could have been used
1731 // if the amount being transferred over this path is lower.
1732 // We do this for now, but this is a subject for removal.
1733 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1734 let used_liquidity_msat = used_liquidities
1735 .get(&$candidate.id($src_node_id < $dest_node_id))
1736 .map_or(0, |used_liquidity_msat| {
1737 available_value_contribution_msat = available_value_contribution_msat
1738 .saturating_sub(*used_liquidity_msat);
1739 *used_liquidity_msat
1742 // Verify the liquidity offered by this channel complies to the minimal contribution.
1743 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1744 // Do not consider candidate hops that would exceed the maximum path length.
1745 let path_length_to_node = $next_hops_path_length + 1;
1746 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1748 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1749 // In order to already account for some of the privacy enhancing random CLTV
1750 // expiry delta offset we add on top later, we subtract a rough estimate
1751 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1752 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1753 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1754 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1755 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1756 .saturating_add($candidate.cltv_expiry_delta());
1757 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1759 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1760 // Includes paying fees for the use of the following channels.
1761 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1762 Some(result) => result,
1763 // Can't overflow due to how the values were computed right above.
1764 None => unreachable!(),
1766 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1767 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1768 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1770 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1771 let may_overpay_to_meet_path_minimum_msat =
1772 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1773 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1774 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1775 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1777 let payment_failed_on_this_channel = scid_opt.map_or(false,
1778 |scid| payment_params.previously_failed_channels.contains(&scid));
1780 let should_log_candidate = match $candidate {
1781 CandidateRouteHop::FirstHop { .. } => true,
1782 CandidateRouteHop::PrivateHop { .. } => true,
1783 CandidateRouteHop::Blinded { .. } => true,
1787 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1788 // bother considering this channel. If retrying with recommended_value_msat may
1789 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1790 // around again with a higher amount.
1791 if !contributes_sufficient_value {
1792 if should_log_candidate {
1793 log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1795 num_ignored_value_contribution += 1;
1796 } else if exceeds_max_path_length {
1797 if should_log_candidate {
1798 log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1800 num_ignored_path_length_limit += 1;
1801 } else if exceeds_cltv_delta_limit {
1802 if should_log_candidate {
1803 log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1805 num_ignored_cltv_delta_limit += 1;
1806 } else if payment_failed_on_this_channel {
1807 if should_log_candidate {
1808 log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1810 num_ignored_previously_failed += 1;
1811 } else if may_overpay_to_meet_path_minimum_msat {
1812 hit_minimum_limit = true;
1813 } else if over_path_minimum_msat {
1814 // Note that low contribution here (limited by available_liquidity_msat)
1815 // might violate htlc_minimum_msat on the hops which are next along the
1816 // payment path (upstream to the payee). To avoid that, we recompute
1817 // path fees knowing the final path contribution after constructing it.
1818 let path_htlc_minimum_msat = cmp::max(
1819 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1820 .saturating_add($next_hops_path_htlc_minimum_msat),
1821 $candidate.htlc_minimum_msat());
1822 let hm_entry = dist.entry($src_node_id);
1823 let old_entry = hm_entry.or_insert_with(|| {
1824 // If there was previously no known way to access the source node
1825 // (recall it goes payee-to-payer) of short_channel_id, first add a
1826 // semi-dummy record just to compute the fees to reach the source node.
1827 // This will affect our decision on selecting short_channel_id
1828 // as a way to reach the $dest_node_id.
1830 node_id: $dest_node_id.clone(),
1831 candidate: $candidate.clone(),
1833 next_hops_fee_msat: u64::max_value(),
1834 hop_use_fee_msat: u64::max_value(),
1835 total_fee_msat: u64::max_value(),
1836 path_htlc_minimum_msat,
1837 path_penalty_msat: u64::max_value(),
1838 was_processed: false,
1839 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1840 value_contribution_msat,
1844 #[allow(unused_mut)] // We only use the mut in cfg(test)
1845 let mut should_process = !old_entry.was_processed;
1846 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1848 // In test/fuzzing builds, we do extra checks to make sure the skipping
1849 // of already-seen nodes only happens in cases we expect (see below).
1850 if !should_process { should_process = true; }
1854 let mut hop_use_fee_msat = 0;
1855 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1857 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1858 // will have the same effective-fee
1859 if $src_node_id != our_node_id {
1860 // Note that `u64::max_value` means we'll always fail the
1861 // `old_entry.total_fee_msat > total_fee_msat` check below
1862 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1863 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1866 // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
1867 let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1868 if total_fee_msat > max_total_routing_fee_msat {
1869 if should_log_candidate {
1870 log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
1872 num_ignored_total_fee_limit += 1;
1874 let channel_usage = ChannelUsage {
1875 amount_msat: amount_to_transfer_over_msat,
1876 inflight_htlc_msat: used_liquidity_msat,
1879 let channel_penalty_msat = scid_opt.map_or(0,
1880 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1881 channel_usage, score_params));
1882 let path_penalty_msat = $next_hops_path_penalty_msat
1883 .saturating_add(channel_penalty_msat);
1884 let new_graph_node = RouteGraphNode {
1885 node_id: $src_node_id,
1886 lowest_fee_to_node: total_fee_msat,
1887 total_cltv_delta: hop_total_cltv_delta,
1888 value_contribution_msat,
1889 path_htlc_minimum_msat,
1891 path_length_to_node,
1894 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1895 // if this way is cheaper than the already known
1896 // (considering the cost to "reach" this channel from the route destination,
1897 // the cost of using this channel,
1898 // and the cost of routing to the source node of this channel).
1899 // Also, consider that htlc_minimum_msat_difference, because we might end up
1900 // paying it. Consider the following exploit:
1901 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1902 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1903 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1904 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1906 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1907 // but it may require additional tracking - we don't want to double-count
1908 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1909 // can't use something that may decrease on future hops.
1910 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1911 .saturating_add(old_entry.path_penalty_msat);
1912 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1913 .saturating_add(path_penalty_msat);
1915 if !old_entry.was_processed && new_cost < old_cost {
1916 targets.push(new_graph_node);
1917 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1918 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1919 old_entry.total_fee_msat = total_fee_msat;
1920 old_entry.node_id = $dest_node_id.clone();
1921 old_entry.candidate = $candidate.clone();
1922 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1923 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1924 old_entry.path_penalty_msat = path_penalty_msat;
1925 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1927 old_entry.value_contribution_msat = value_contribution_msat;
1929 did_add_update_path_to_src_node = Some(value_contribution_msat);
1930 } else if old_entry.was_processed && new_cost < old_cost {
1931 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1933 // If we're skipping processing a node which was previously
1934 // processed even though we found another path to it with a
1935 // cheaper fee, check that it was because the second path we
1936 // found (which we are processing now) has a lower value
1937 // contribution due to an HTLC minimum limit.
1939 // e.g. take a graph with two paths from node 1 to node 2, one
1940 // through channel A, and one through channel B. Channel A and
1941 // B are both in the to-process heap, with their scores set by
1942 // a higher htlc_minimum than fee.
1943 // Channel A is processed first, and the channels onwards from
1944 // node 1 are added to the to-process heap. Thereafter, we pop
1945 // Channel B off of the heap, note that it has a much more
1946 // restrictive htlc_maximum_msat, and recalculate the fees for
1947 // all of node 1's channels using the new, reduced, amount.
1949 // This would be bogus - we'd be selecting a higher-fee path
1950 // with a lower htlc_maximum_msat instead of the one we'd
1951 // already decided to use.
1952 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1954 value_contribution_msat + path_penalty_msat <
1955 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1964 did_add_update_path_to_src_node
1968 let default_node_features = default_node_features();
1970 // Find ways (channels with destination) to reach a given node and store them
1971 // in the corresponding data structures (routing graph etc).
1972 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1973 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1974 // This data can later be helpful to optimize routing (pay lower fees).
1975 macro_rules! add_entries_to_cheapest_to_target_node {
1976 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1977 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1978 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1979 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1980 let was_processed = elem.was_processed;
1981 elem.was_processed = true;
1984 // Entries are added to dist in add_entry!() when there is a channel from a node.
1985 // Because there are no channels from payee, it will not have a dist entry at this point.
1986 // If we're processing any other node, it is always be the result of a channel from it.
1987 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1992 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1993 for details in first_channels {
1994 let candidate = CandidateRouteHop::FirstHop { details };
1995 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1996 $next_hops_value_contribution,
1997 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1998 $next_hops_cltv_delta, $next_hops_path_length);
2002 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2005 &default_node_features
2008 if !features.requires_unknown_bits() {
2009 for chan_id in $node.channels.iter() {
2010 let chan = network_channels.get(chan_id).unwrap();
2011 if !chan.features.requires_unknown_bits() {
2012 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2013 if first_hops.is_none() || *source != our_node_id {
2014 if directed_channel.direction().enabled {
2015 let candidate = CandidateRouteHop::PublicHop {
2016 info: directed_channel,
2017 short_channel_id: *chan_id,
2019 add_entry!(candidate, *source, $node_id,
2020 $fee_to_target_msat,
2021 $next_hops_value_contribution,
2022 $next_hops_path_htlc_minimum_msat,
2023 $next_hops_path_penalty_msat,
2024 $next_hops_cltv_delta, $next_hops_path_length);
2035 let mut payment_paths = Vec::<PaymentPath>::new();
2037 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2038 'paths_collection: loop {
2039 // For every new path, start from scratch, except for used_liquidities, which
2040 // helps to avoid reusing previously selected paths in future iterations.
2043 hit_minimum_limit = false;
2045 // If first hop is a private channel and the only way to reach the payee, this is the only
2046 // place where it could be added.
2047 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2048 for details in first_channels {
2049 let candidate = CandidateRouteHop::FirstHop { details };
2050 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
2051 0, 0u64, 0, 0).is_some();
2052 log_trace!(logger, "{} direct route to payee via {}",
2053 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2057 // Add the payee as a target, so that the payee-to-payer
2058 // search algorithm knows what to start with.
2059 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2060 // The payee is not in our network graph, so nothing to add here.
2061 // There is still a chance of reaching them via last_hops though,
2062 // so don't yet fail the payment here.
2063 // If not, targets.pop() will not even let us enter the loop in step 2.
2066 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2071 // If a caller provided us with last hops, add them to routing targets. Since this happens
2072 // earlier than general path finding, they will be somewhat prioritized, although currently
2073 // it matters only if the fees are exactly the same.
2074 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2075 let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2076 let have_intro_node_in_graph =
2077 // Only add the hops in this route to our candidate set if either
2078 // we have a direct channel to the first hop or the first hop is
2079 // in the regular network graph.
2080 first_hop_targets.get(&intro_node_id).is_some() ||
2081 network_nodes.get(&intro_node_id).is_some();
2082 if !have_intro_node_in_graph { continue }
2083 let candidate = if hint.1.blinded_hops.len() == 1 {
2084 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2085 } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2086 let mut path_contribution_msat = path_value_msat;
2087 if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2088 0, path_contribution_msat, 0, 0_u64, 0, 0)
2090 path_contribution_msat = hop_used_msat;
2092 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2093 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2095 for details in first_channels {
2096 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2097 let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2101 add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2102 path_contribution_msat, candidate.htlc_minimum_msat(), 0_u64,
2103 candidate.cltv_expiry_delta(),
2104 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2108 for route in payment_params.payee.unblinded_route_hints().iter()
2109 .filter(|route| !route.0.is_empty())
2111 let first_hop_in_route = &(route.0)[0];
2112 let have_hop_src_in_graph =
2113 // Only add the hops in this route to our candidate set if either
2114 // we have a direct channel to the first hop or the first hop is
2115 // in the regular network graph.
2116 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
2117 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
2118 if have_hop_src_in_graph {
2119 // We start building the path from reverse, i.e., from payee
2120 // to the first RouteHintHop in the path.
2121 let hop_iter = route.0.iter().rev();
2122 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2123 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2124 let mut hop_used = true;
2125 let mut aggregate_next_hops_fee_msat: u64 = 0;
2126 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2127 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2128 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2129 let mut aggregate_next_hops_path_length: u8 = 0;
2130 let mut aggregate_path_contribution_msat = path_value_msat;
2132 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2133 let source = NodeId::from_pubkey(&hop.src_node_id);
2134 let target = NodeId::from_pubkey(&prev_hop_id);
2135 let candidate = network_channels
2136 .get(&hop.short_channel_id)
2137 .and_then(|channel| channel.as_directed_to(&target))
2138 .map(|(info, _)| CandidateRouteHop::PublicHop {
2140 short_channel_id: hop.short_channel_id,
2142 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2144 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2145 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2146 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2147 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2149 aggregate_path_contribution_msat = hop_used_msat;
2151 // If this hop was not used then there is no use checking the preceding
2152 // hops in the RouteHint. We can break by just searching for a direct
2153 // channel between last checked hop and first_hop_targets.
2157 let used_liquidity_msat = used_liquidities
2158 .get(&candidate.id(source < target)).copied()
2160 let channel_usage = ChannelUsage {
2161 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2162 inflight_htlc_msat: used_liquidity_msat,
2163 effective_capacity: candidate.effective_capacity(),
2165 let channel_penalty_msat = scorer.channel_penalty_msat(
2166 hop.short_channel_id, &source, &target, channel_usage, score_params
2168 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2169 .saturating_add(channel_penalty_msat);
2171 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2172 .saturating_add(hop.cltv_expiry_delta as u32);
2174 aggregate_next_hops_path_length = aggregate_next_hops_path_length
2177 // Searching for a direct channel between last checked hop and first_hop_targets
2178 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2179 sort_first_hop_channels(first_channels, &used_liquidities,
2180 recommended_value_msat, our_node_pubkey);
2181 for details in first_channels {
2182 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2183 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2184 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2185 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2186 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2194 // In the next values of the iterator, the aggregate fees already reflects
2195 // the sum of value sent from payer (final_value_msat) and routing fees
2196 // for the last node in the RouteHint. We need to just add the fees to
2197 // route through the current node so that the preceding node (next iteration)
2199 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2200 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2201 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2203 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2204 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2205 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2206 .checked_add(hop_htlc_minimum_msat_inc);
2207 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2209 if idx == route.0.len() - 1 {
2210 // The last hop in this iterator is the first hop in
2211 // overall RouteHint.
2212 // If this hop connects to a node with which we have a direct channel,
2213 // ignore the network graph and, if the last hop was added, add our
2214 // direct channel to the candidate set.
2216 // Note that we *must* check if the last hop was added as `add_entry`
2217 // always assumes that the third argument is a node to which we have a
2219 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2220 sort_first_hop_channels(first_channels, &used_liquidities,
2221 recommended_value_msat, our_node_pubkey);
2222 for details in first_channels {
2223 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2224 add_entry!(first_hop_candidate, our_node_id,
2225 NodeId::from_pubkey(&hop.src_node_id),
2226 aggregate_next_hops_fee_msat,
2227 aggregate_path_contribution_msat,
2228 aggregate_next_hops_path_htlc_minimum_msat,
2229 aggregate_next_hops_path_penalty_msat,
2230 aggregate_next_hops_cltv_delta,
2231 aggregate_next_hops_path_length);
2239 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2241 // At this point, targets are filled with the data from first and
2242 // last hops communicated by the caller, and the payment receiver.
2243 let mut found_new_path = false;
2246 // If this loop terminates due the exhaustion of targets, two situations are possible:
2247 // - not enough outgoing liquidity:
2248 // 0 < already_collected_value_msat < final_value_msat
2249 // - enough outgoing liquidity:
2250 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2251 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2252 // paths_collection will be stopped because found_new_path==false.
2253 // This is not necessarily a routing failure.
2254 '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() {
2256 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2257 // traversing the graph and arrange the path out of what we found.
2258 if node_id == our_node_id {
2259 let mut new_entry = dist.remove(&our_node_id).unwrap();
2260 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2263 let mut features_set = false;
2264 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2265 for details in first_channels {
2266 if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2267 if details.get_outbound_payment_scid().unwrap() == scid {
2268 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2269 features_set = true;
2276 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2277 if let Some(node_info) = node.announcement_info.as_ref() {
2278 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2280 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2283 // We can fill in features for everything except hops which were
2284 // provided via the invoice we're paying. We could guess based on the
2285 // recipient's features but for now we simply avoid guessing at all.
2289 // Means we succesfully traversed from the payer to the payee, now
2290 // save this path for the payment route. Also, update the liquidity
2291 // remaining on the used hops, so that we take them into account
2292 // while looking for more paths.
2293 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2297 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2298 Some(payment_hop) => payment_hop,
2299 // We can't arrive at None because, if we ever add an entry to targets,
2300 // we also fill in the entry in dist (see add_entry!).
2301 None => unreachable!(),
2303 // We "propagate" the fees one hop backward (topologically) here,
2304 // so that fees paid for a HTLC forwarding on the current channel are
2305 // associated with the previous channel (where they will be subtracted).
2306 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2307 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2309 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2310 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2312 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2313 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2315 let mut payment_path = PaymentPath {hops: ordered_hops};
2317 // We could have possibly constructed a slightly inconsistent path: since we reduce
2318 // value being transferred along the way, we could have violated htlc_minimum_msat
2319 // on some channels we already passed (assuming dest->source direction). Here, we
2320 // recompute the fees again, so that if that's the case, we match the currently
2321 // underpaid htlc_minimum_msat with fees.
2322 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2323 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2324 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2326 // Since a path allows to transfer as much value as
2327 // the smallest channel it has ("bottleneck"), we should recompute
2328 // the fees so sender HTLC don't overpay fees when traversing
2329 // larger channels than the bottleneck. This may happen because
2330 // when we were selecting those channels we were not aware how much value
2331 // this path will transfer, and the relative fee for them
2332 // might have been computed considering a larger value.
2333 // Remember that we used these channels so that we don't rely
2334 // on the same liquidity in future paths.
2335 let mut prevented_redundant_path_selection = false;
2336 let prev_hop_iter = core::iter::once(&our_node_id)
2337 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2338 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2339 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2340 let used_liquidity_msat = used_liquidities
2341 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2342 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2343 .or_insert(spent_on_hop_msat);
2344 let hop_capacity = hop.candidate.effective_capacity();
2345 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2346 if *used_liquidity_msat == hop_max_msat {
2347 // If this path used all of this channel's available liquidity, we know
2348 // this path will not be selected again in the next loop iteration.
2349 prevented_redundant_path_selection = true;
2351 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2353 if !prevented_redundant_path_selection {
2354 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2355 // we'll probably end up picking the same path again on the next iteration.
2356 // Decrease the available liquidity of a hop in the middle of the path.
2357 let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2358 let exhausted = u64::max_value();
2360 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2361 LoggedCandidateHop(victim_candidate));
2362 *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2363 *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2366 // Track the total amount all our collected paths allow to send so that we know
2367 // when to stop looking for more paths
2368 already_collected_value_msat += value_contribution_msat;
2370 payment_paths.push(payment_path);
2371 found_new_path = true;
2372 break 'path_construction;
2375 // If we found a path back to the payee, we shouldn't try to process it again. This is
2376 // the equivalent of the `elem.was_processed` check in
2377 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2378 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2380 // Otherwise, since the current target node is not us,
2381 // keep "unrolling" the payment graph from payee to payer by
2382 // finding a way to reach the current target from the payer side.
2383 match network_nodes.get(&node_id) {
2386 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2387 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2388 total_cltv_delta, path_length_to_node);
2394 if !found_new_path && channel_saturation_pow_half != 0 {
2395 channel_saturation_pow_half = 0;
2396 continue 'paths_collection;
2398 // If we don't support MPP, no use trying to gather more value ever.
2399 break 'paths_collection;
2403 // Stop either when the recommended value is reached or if no new path was found in this
2405 // In the latter case, making another path finding attempt won't help,
2406 // because we deterministically terminated the search due to low liquidity.
2407 if !found_new_path && channel_saturation_pow_half != 0 {
2408 channel_saturation_pow_half = 0;
2409 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2410 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2411 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2412 break 'paths_collection;
2413 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2414 // Further, if this was our first walk of the graph, and we weren't limited by an
2415 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2416 // limited by an htlc_minimum_msat value, find another path with a higher value,
2417 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2418 // still keeping a lower total fee than this path.
2419 if !hit_minimum_limit {
2420 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2421 break 'paths_collection;
2423 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2424 path_value_msat = recommended_value_msat;
2428 let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2429 num_ignored_cltv_delta_limit + num_ignored_previously_failed + num_ignored_total_fee_limit;
2430 if num_ignored_total > 0 {
2431 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);
2435 if payment_paths.len() == 0 {
2436 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2439 if already_collected_value_msat < final_value_msat {
2440 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2444 let mut selected_route = payment_paths;
2446 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2447 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2449 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2450 // the value they contribute towards the payment amount.
2451 // We sort in descending order as we will remove from the front in `retain`, next.
2452 selected_route.sort_unstable_by(|a, b|
2453 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2454 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2457 // We should make sure that at least 1 path left.
2458 let mut paths_left = selected_route.len();
2459 selected_route.retain(|path| {
2460 if paths_left == 1 {
2463 let path_value_msat = path.get_value_msat();
2464 if path_value_msat <= overpaid_value_msat {
2465 overpaid_value_msat -= path_value_msat;
2471 debug_assert!(selected_route.len() > 0);
2473 if overpaid_value_msat != 0 {
2475 // Now, subtract the remaining overpaid value from the most-expensive path.
2476 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2477 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2478 selected_route.sort_unstable_by(|a, b| {
2479 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2480 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2481 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2483 let expensive_payment_path = selected_route.first_mut().unwrap();
2485 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2486 // can't go negative.
2487 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2488 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2492 // Sort by the path itself and combine redundant paths.
2493 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2494 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2496 selected_route.sort_unstable_by_key(|path| {
2497 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2498 debug_assert!(path.hops.len() <= key.len());
2499 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2504 for idx in 0..(selected_route.len() - 1) {
2505 if idx + 1 >= selected_route.len() { break; }
2506 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2507 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2508 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2509 selected_route[idx].update_value_and_recompute_fees(new_value);
2510 selected_route.remove(idx + 1);
2514 let mut paths = Vec::new();
2515 for payment_path in selected_route {
2516 let mut hops = Vec::with_capacity(payment_path.hops.len());
2517 let mut prev_hop_node_id = our_node_id;
2518 for (hop, node_features) in payment_path.hops.iter()
2519 .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2521 let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2522 // If we sourced the hop from the graph we're sure the target node is announced.
2524 } else if let CandidateRouteHop::FirstHop { details } = hop.candidate {
2525 // If this is a first hop we also know if it's announced.
2528 // If we sourced it any other way, we double-check the network graph to see if
2529 // there are announced channels between the endpoints. If so, the hop might be
2530 // referring to any of the announced channels, as its `short_channel_id` might be
2531 // an alias, in which case we don't take any chances here.
2532 network_graph.node(&hop.node_id).map_or(false, |hop_node|
2533 hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2534 .map_or(false, |c| c.as_directed_from(&prev_hop_node_id).is_some()))
2538 hops.push(RouteHop {
2539 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)})?,
2540 node_features: node_features.clone(),
2541 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2542 channel_features: hop.candidate.features(),
2543 fee_msat: hop.fee_msat,
2544 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2545 maybe_announced_channel,
2548 prev_hop_node_id = hop.node_id;
2550 let mut final_cltv_delta = final_cltv_expiry_delta;
2551 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2552 if let Some(blinded_path) = h.candidate.blinded_path() {
2553 final_cltv_delta = h.candidate.cltv_expiry_delta();
2555 hops: blinded_path.blinded_hops.clone(),
2556 blinding_point: blinded_path.blinding_point,
2557 excess_final_cltv_expiry_delta: 0,
2558 final_value_msat: h.fee_msat,
2562 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2563 // applicable for the previous hop.
2564 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2565 core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2568 paths.push(Path { hops, blinded_tail });
2570 // Make sure we would never create a route with more paths than we allow.
2571 debug_assert!(paths.len() <= payment_params.max_path_count.into());
2573 // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2574 if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2575 if paths.iter().map(|p| p.fee_msat()).sum::<u64>() > max_total_routing_fee_msat {
2576 return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2577 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2581 if let Some(node_features) = payment_params.payee.node_features() {
2582 for path in paths.iter_mut() {
2583 path.hops.last_mut().unwrap().node_features = node_features.clone();
2587 let route = Route { paths, route_params: Some(route_params.clone()) };
2588 log_info!(logger, "Got route: {}", log_route!(route));
2592 // When an adversarial intermediary node observes a payment, it may be able to infer its
2593 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2594 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2595 // payment path by adding a randomized 'shadow route' offset to the final hop.
2596 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2597 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2599 let network_channels = network_graph.channels();
2600 let network_nodes = network_graph.nodes();
2602 for path in route.paths.iter_mut() {
2603 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2605 // Remember the last three nodes of the random walk and avoid looping back on them.
2606 // Init with the last three nodes from the actual path, if possible.
2607 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2608 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2609 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2611 // Choose the last publicly known node as the starting point for the random walk.
2612 let mut cur_hop: Option<NodeId> = None;
2613 let mut path_nonce = [0u8; 12];
2614 if let Some(starting_hop) = path.hops.iter().rev()
2615 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2616 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2617 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2620 // Init PRNG with the path-dependant nonce, which is static for private paths.
2621 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2622 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2624 // Pick a random path length in [1 .. 3]
2625 prng.process_in_place(&mut random_path_bytes);
2626 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2628 for random_hop in 0..random_walk_length {
2629 // If we don't find a suitable offset in the public network graph, we default to
2630 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2631 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2633 if let Some(cur_node_id) = cur_hop {
2634 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2635 // Randomly choose the next unvisited hop.
2636 prng.process_in_place(&mut random_path_bytes);
2637 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2638 .checked_rem(cur_node.channels.len())
2639 .and_then(|index| cur_node.channels.get(index))
2640 .and_then(|id| network_channels.get(id)) {
2641 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2642 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2643 nodes_to_avoid[random_hop] = *next_id;
2644 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2645 cur_hop = Some(*next_id);
2652 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2653 .checked_add(random_hop_offset)
2654 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2657 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2658 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2659 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2661 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2662 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2663 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2664 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2665 max_path_offset = cmp::max(
2666 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2667 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2668 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2670 // Add 'shadow' CLTV offset to the final hop
2671 if let Some(tail) = path.blinded_tail.as_mut() {
2672 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2673 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2675 if let Some(last_hop) = path.hops.last_mut() {
2676 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2677 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2682 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2683 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2685 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2686 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2687 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2688 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2689 ) -> Result<Route, LightningError>
2690 where L::Target: Logger, GL::Target: Logger {
2691 let graph_lock = network_graph.read_only();
2692 let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2693 &graph_lock, logger, random_seed_bytes)?;
2694 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2698 fn build_route_from_hops_internal<L: Deref>(
2699 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2700 network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2701 ) -> Result<Route, LightningError> where L::Target: Logger {
2704 our_node_id: NodeId,
2705 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2708 impl ScoreLookUp for HopScorer {
2709 type ScoreParams = ();
2710 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2711 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2713 let mut cur_id = self.our_node_id;
2714 for i in 0..self.hop_ids.len() {
2715 if let Some(next_id) = self.hop_ids[i] {
2716 if cur_id == *source && next_id == *target {
2728 impl<'a> Writeable for HopScorer {
2730 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2735 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2736 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2739 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2740 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2741 for i in 0..hops.len() {
2742 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2745 let scorer = HopScorer { our_node_id, hop_ids };
2747 get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2752 use crate::blinded_path::{BlindedHop, BlindedPath};
2753 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2754 use crate::routing::utxo::UtxoResult;
2755 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2756 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2757 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2758 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2759 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2760 use crate::chain::transaction::OutPoint;
2761 use crate::sign::EntropySource;
2762 use crate::ln::ChannelId;
2763 use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2764 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2765 use crate::ln::channelmanager;
2766 use crate::offers::invoice::BlindedPayInfo;
2767 use crate::util::config::UserConfig;
2768 use crate::util::test_utils as ln_test_utils;
2769 use crate::util::chacha20::ChaCha20;
2770 use crate::util::ser::{Readable, Writeable};
2772 use crate::util::ser::Writer;
2774 use bitcoin::hashes::Hash;
2775 use bitcoin::network::constants::Network;
2776 use bitcoin::blockdata::constants::genesis_block;
2777 use bitcoin::blockdata::script::Builder;
2778 use bitcoin::blockdata::opcodes;
2779 use bitcoin::blockdata::transaction::TxOut;
2783 use bitcoin::secp256k1::{PublicKey,SecretKey};
2784 use bitcoin::secp256k1::Secp256k1;
2786 use crate::io::Cursor;
2787 use crate::prelude::*;
2788 use crate::sync::Arc;
2790 use core::convert::TryInto;
2792 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2793 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2794 channelmanager::ChannelDetails {
2795 channel_id: ChannelId::new_zero(),
2796 counterparty: channelmanager::ChannelCounterparty {
2799 unspendable_punishment_reserve: 0,
2800 forwarding_info: None,
2801 outbound_htlc_minimum_msat: None,
2802 outbound_htlc_maximum_msat: None,
2804 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2807 outbound_scid_alias: None,
2808 inbound_scid_alias: None,
2809 channel_value_satoshis: 0,
2811 outbound_capacity_msat,
2812 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2813 next_outbound_htlc_minimum_msat: 0,
2814 inbound_capacity_msat: 42,
2815 unspendable_punishment_reserve: None,
2816 confirmations_required: None,
2817 confirmations: None,
2818 force_close_spend_delay: None,
2819 is_outbound: true, is_channel_ready: true,
2820 is_usable: true, is_public: true,
2821 inbound_htlc_minimum_msat: None,
2822 inbound_htlc_maximum_msat: None,
2824 feerate_sat_per_1000_weight: None,
2825 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2830 fn simple_route_test() {
2831 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2832 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2833 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2834 let scorer = ln_test_utils::TestScorer::new();
2835 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2836 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2838 // Simple route to 2 via 1
2840 let route_params = RouteParameters::from_payment_params_and_value(
2841 payment_params.clone(), 0);
2842 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2843 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
2844 &Default::default(), &random_seed_bytes) {
2845 assert_eq!(err, "Cannot send a payment of 0 msat");
2846 } else { panic!(); }
2848 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2849 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2850 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2851 assert_eq!(route.paths[0].hops.len(), 2);
2853 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2854 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2855 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2856 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2857 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2858 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2860 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2861 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2862 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2863 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2864 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2865 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2869 fn invalid_first_hop_test() {
2870 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2871 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2872 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2873 let scorer = ln_test_utils::TestScorer::new();
2874 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2875 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2877 // Simple route to 2 via 1
2879 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2881 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2882 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2883 &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
2884 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
2885 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2886 } else { panic!(); }
2888 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2889 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2890 assert_eq!(route.paths[0].hops.len(), 2);
2894 fn htlc_minimum_test() {
2895 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2896 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2897 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2898 let scorer = ln_test_utils::TestScorer::new();
2899 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2900 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2902 // Simple route to 2 via 1
2904 // Disable other paths
2905 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2906 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2907 short_channel_id: 12,
2909 flags: 2, // to disable
2910 cltv_expiry_delta: 0,
2911 htlc_minimum_msat: 0,
2912 htlc_maximum_msat: MAX_VALUE_MSAT,
2914 fee_proportional_millionths: 0,
2915 excess_data: Vec::new()
2917 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2919 short_channel_id: 3,
2921 flags: 2, // to disable
2922 cltv_expiry_delta: 0,
2923 htlc_minimum_msat: 0,
2924 htlc_maximum_msat: MAX_VALUE_MSAT,
2926 fee_proportional_millionths: 0,
2927 excess_data: Vec::new()
2929 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2930 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2931 short_channel_id: 13,
2933 flags: 2, // to disable
2934 cltv_expiry_delta: 0,
2935 htlc_minimum_msat: 0,
2936 htlc_maximum_msat: MAX_VALUE_MSAT,
2938 fee_proportional_millionths: 0,
2939 excess_data: Vec::new()
2941 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2942 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2943 short_channel_id: 6,
2945 flags: 2, // to disable
2946 cltv_expiry_delta: 0,
2947 htlc_minimum_msat: 0,
2948 htlc_maximum_msat: MAX_VALUE_MSAT,
2950 fee_proportional_millionths: 0,
2951 excess_data: Vec::new()
2953 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2955 short_channel_id: 7,
2957 flags: 2, // to disable
2958 cltv_expiry_delta: 0,
2959 htlc_minimum_msat: 0,
2960 htlc_maximum_msat: MAX_VALUE_MSAT,
2962 fee_proportional_millionths: 0,
2963 excess_data: Vec::new()
2966 // Check against amount_to_transfer_over_msat.
2967 // Set minimal HTLC of 200_000_000 msat.
2968 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2970 short_channel_id: 2,
2973 cltv_expiry_delta: 0,
2974 htlc_minimum_msat: 200_000_000,
2975 htlc_maximum_msat: MAX_VALUE_MSAT,
2977 fee_proportional_millionths: 0,
2978 excess_data: Vec::new()
2981 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2983 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2984 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2985 short_channel_id: 4,
2988 cltv_expiry_delta: 0,
2989 htlc_minimum_msat: 0,
2990 htlc_maximum_msat: 199_999_999,
2992 fee_proportional_millionths: 0,
2993 excess_data: Vec::new()
2996 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2997 let route_params = RouteParameters::from_payment_params_and_value(
2998 payment_params, 199_999_999);
2999 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3000 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3001 &Default::default(), &random_seed_bytes) {
3002 assert_eq!(err, "Failed to find a path to the given destination");
3003 } else { panic!(); }
3005 // Lift the restriction on the first hop.
3006 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3007 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3008 short_channel_id: 2,
3011 cltv_expiry_delta: 0,
3012 htlc_minimum_msat: 0,
3013 htlc_maximum_msat: MAX_VALUE_MSAT,
3015 fee_proportional_millionths: 0,
3016 excess_data: Vec::new()
3019 // A payment above the minimum should pass
3020 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3021 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3022 assert_eq!(route.paths[0].hops.len(), 2);
3026 fn htlc_minimum_overpay_test() {
3027 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3028 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3029 let config = UserConfig::default();
3030 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3031 let scorer = ln_test_utils::TestScorer::new();
3032 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3033 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3035 // A route to node#2 via two paths.
3036 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3037 // Thus, they can't send 60 without overpaying.
3038 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3039 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3040 short_channel_id: 2,
3043 cltv_expiry_delta: 0,
3044 htlc_minimum_msat: 35_000,
3045 htlc_maximum_msat: 40_000,
3047 fee_proportional_millionths: 0,
3048 excess_data: Vec::new()
3050 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3051 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3052 short_channel_id: 12,
3055 cltv_expiry_delta: 0,
3056 htlc_minimum_msat: 35_000,
3057 htlc_maximum_msat: 40_000,
3059 fee_proportional_millionths: 0,
3060 excess_data: Vec::new()
3064 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3065 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3066 short_channel_id: 13,
3069 cltv_expiry_delta: 0,
3070 htlc_minimum_msat: 0,
3071 htlc_maximum_msat: MAX_VALUE_MSAT,
3073 fee_proportional_millionths: 0,
3074 excess_data: Vec::new()
3076 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3077 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3078 short_channel_id: 4,
3081 cltv_expiry_delta: 0,
3082 htlc_minimum_msat: 0,
3083 htlc_maximum_msat: MAX_VALUE_MSAT,
3085 fee_proportional_millionths: 0,
3086 excess_data: Vec::new()
3089 // Disable other paths
3090 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3092 short_channel_id: 1,
3094 flags: 2, // to disable
3095 cltv_expiry_delta: 0,
3096 htlc_minimum_msat: 0,
3097 htlc_maximum_msat: MAX_VALUE_MSAT,
3099 fee_proportional_millionths: 0,
3100 excess_data: Vec::new()
3103 let mut route_params = RouteParameters::from_payment_params_and_value(
3104 payment_params.clone(), 60_000);
3105 route_params.max_total_routing_fee_msat = Some(15_000);
3106 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3107 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3108 // Overpay fees to hit htlc_minimum_msat.
3109 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3110 // TODO: this could be better balanced to overpay 10k and not 15k.
3111 assert_eq!(overpaid_fees, 15_000);
3113 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3114 // while taking even more fee to match htlc_minimum_msat.
3115 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3116 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3117 short_channel_id: 12,
3120 cltv_expiry_delta: 0,
3121 htlc_minimum_msat: 65_000,
3122 htlc_maximum_msat: 80_000,
3124 fee_proportional_millionths: 0,
3125 excess_data: Vec::new()
3127 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3129 short_channel_id: 2,
3132 cltv_expiry_delta: 0,
3133 htlc_minimum_msat: 0,
3134 htlc_maximum_msat: MAX_VALUE_MSAT,
3136 fee_proportional_millionths: 0,
3137 excess_data: Vec::new()
3139 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3140 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3141 short_channel_id: 4,
3144 cltv_expiry_delta: 0,
3145 htlc_minimum_msat: 0,
3146 htlc_maximum_msat: MAX_VALUE_MSAT,
3148 fee_proportional_millionths: 100_000,
3149 excess_data: Vec::new()
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 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3155 assert_eq!(route.paths.len(), 1);
3156 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3157 let fees = route.paths[0].hops[0].fee_msat;
3158 assert_eq!(fees, 5_000);
3160 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3161 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3162 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3163 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3164 // the other channel.
3165 assert_eq!(route.paths.len(), 1);
3166 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3167 let fees = route.paths[0].hops[0].fee_msat;
3168 assert_eq!(fees, 5_000);
3172 fn disable_channels_test() {
3173 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3174 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3175 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3176 let scorer = ln_test_utils::TestScorer::new();
3177 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3178 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3180 // // Disable channels 4 and 12 by flags=2
3181 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3183 short_channel_id: 4,
3185 flags: 2, // to disable
3186 cltv_expiry_delta: 0,
3187 htlc_minimum_msat: 0,
3188 htlc_maximum_msat: MAX_VALUE_MSAT,
3190 fee_proportional_millionths: 0,
3191 excess_data: Vec::new()
3193 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3195 short_channel_id: 12,
3197 flags: 2, // to disable
3198 cltv_expiry_delta: 0,
3199 htlc_minimum_msat: 0,
3200 htlc_maximum_msat: MAX_VALUE_MSAT,
3202 fee_proportional_millionths: 0,
3203 excess_data: Vec::new()
3206 // If all the channels require some features we don't understand, route should fail
3207 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3208 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3209 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3210 &Default::default(), &random_seed_bytes) {
3211 assert_eq!(err, "Failed to find a path to the given destination");
3212 } else { panic!(); }
3214 // If we specify a channel to node7, that overrides our local channel view and that gets used
3215 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3216 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3217 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3218 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3219 &Default::default(), &random_seed_bytes).unwrap();
3220 assert_eq!(route.paths[0].hops.len(), 2);
3222 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3223 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3224 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3225 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3226 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3227 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3229 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3230 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3231 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3232 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3233 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3234 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3238 fn disable_node_test() {
3239 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3240 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3241 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3242 let scorer = ln_test_utils::TestScorer::new();
3243 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3244 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3246 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3247 let mut unknown_features = NodeFeatures::empty();
3248 unknown_features.set_unknown_feature_required();
3249 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3250 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3251 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3253 // If all nodes require some features we don't understand, route should fail
3254 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3255 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3256 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3257 &Default::default(), &random_seed_bytes) {
3258 assert_eq!(err, "Failed to find a path to the given destination");
3259 } else { panic!(); }
3261 // If we specify a channel to node7, that overrides our local channel view and that gets used
3262 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3263 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3264 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3265 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3266 &Default::default(), &random_seed_bytes).unwrap();
3267 assert_eq!(route.paths[0].hops.len(), 2);
3269 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3270 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3271 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3272 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3273 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3274 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3276 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3277 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3278 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3279 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3280 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3281 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3283 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3284 // naively) assume that the user checked the feature bits on the invoice, which override
3285 // the node_announcement.
3289 fn our_chans_test() {
3290 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3291 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3292 let scorer = ln_test_utils::TestScorer::new();
3293 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3294 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3296 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3297 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3298 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3299 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3300 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3301 assert_eq!(route.paths[0].hops.len(), 3);
3303 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3304 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3305 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3306 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3307 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3308 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3310 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3311 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3312 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3313 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3314 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3315 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3317 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3318 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3319 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3320 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3321 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3322 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3324 // If we specify a channel to node7, that overrides our local channel view and that gets used
3325 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3326 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3327 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3328 InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3329 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3330 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3331 &Default::default(), &random_seed_bytes).unwrap();
3332 assert_eq!(route.paths[0].hops.len(), 2);
3334 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3335 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3336 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3337 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3338 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3339 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3341 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3342 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3343 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3344 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3345 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3346 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3349 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3350 let zero_fees = RoutingFees {
3352 proportional_millionths: 0,
3354 vec![RouteHint(vec![RouteHintHop {
3355 src_node_id: nodes[3],
3356 short_channel_id: 8,
3358 cltv_expiry_delta: (8 << 4) | 1,
3359 htlc_minimum_msat: None,
3360 htlc_maximum_msat: None,
3362 ]), RouteHint(vec![RouteHintHop {
3363 src_node_id: nodes[4],
3364 short_channel_id: 9,
3367 proportional_millionths: 0,
3369 cltv_expiry_delta: (9 << 4) | 1,
3370 htlc_minimum_msat: None,
3371 htlc_maximum_msat: None,
3372 }]), RouteHint(vec![RouteHintHop {
3373 src_node_id: nodes[5],
3374 short_channel_id: 10,
3376 cltv_expiry_delta: (10 << 4) | 1,
3377 htlc_minimum_msat: None,
3378 htlc_maximum_msat: None,
3382 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3383 let zero_fees = RoutingFees {
3385 proportional_millionths: 0,
3387 vec![RouteHint(vec![RouteHintHop {
3388 src_node_id: nodes[2],
3389 short_channel_id: 5,
3392 proportional_millionths: 0,
3394 cltv_expiry_delta: (5 << 4) | 1,
3395 htlc_minimum_msat: None,
3396 htlc_maximum_msat: None,
3398 src_node_id: nodes[3],
3399 short_channel_id: 8,
3401 cltv_expiry_delta: (8 << 4) | 1,
3402 htlc_minimum_msat: None,
3403 htlc_maximum_msat: None,
3405 ]), RouteHint(vec![RouteHintHop {
3406 src_node_id: nodes[4],
3407 short_channel_id: 9,
3410 proportional_millionths: 0,
3412 cltv_expiry_delta: (9 << 4) | 1,
3413 htlc_minimum_msat: None,
3414 htlc_maximum_msat: None,
3415 }]), RouteHint(vec![RouteHintHop {
3416 src_node_id: nodes[5],
3417 short_channel_id: 10,
3419 cltv_expiry_delta: (10 << 4) | 1,
3420 htlc_minimum_msat: None,
3421 htlc_maximum_msat: None,
3426 fn partial_route_hint_test() {
3427 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3428 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3429 let scorer = ln_test_utils::TestScorer::new();
3430 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3431 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3433 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3434 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3435 // RouteHint may be partially used by the algo to build the best path.
3437 // First check that last hop can't have its source as the payee.
3438 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3439 src_node_id: nodes[6],
3440 short_channel_id: 8,
3443 proportional_millionths: 0,
3445 cltv_expiry_delta: (8 << 4) | 1,
3446 htlc_minimum_msat: None,
3447 htlc_maximum_msat: None,
3450 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3451 invalid_last_hops.push(invalid_last_hop);
3453 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3454 .with_route_hints(invalid_last_hops).unwrap();
3455 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3456 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3457 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3458 &Default::default(), &random_seed_bytes) {
3459 assert_eq!(err, "Route hint cannot have the payee as the source.");
3460 } else { panic!(); }
3463 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3464 .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3465 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3466 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3467 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3468 assert_eq!(route.paths[0].hops.len(), 5);
3470 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3471 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3472 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3473 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3474 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3475 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3477 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3478 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3479 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3480 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3481 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3482 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3484 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3485 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3486 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3487 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3488 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3489 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3491 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3492 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3493 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3494 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3495 // If we have a peer in the node map, we'll use their features here since we don't have
3496 // a way of figuring out their features from the invoice:
3497 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3498 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3500 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3501 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3502 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3503 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3504 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3505 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3508 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3509 let zero_fees = RoutingFees {
3511 proportional_millionths: 0,
3513 vec![RouteHint(vec![RouteHintHop {
3514 src_node_id: nodes[3],
3515 short_channel_id: 8,
3517 cltv_expiry_delta: (8 << 4) | 1,
3518 htlc_minimum_msat: None,
3519 htlc_maximum_msat: None,
3520 }]), RouteHint(vec![
3522 ]), RouteHint(vec![RouteHintHop {
3523 src_node_id: nodes[5],
3524 short_channel_id: 10,
3526 cltv_expiry_delta: (10 << 4) | 1,
3527 htlc_minimum_msat: None,
3528 htlc_maximum_msat: None,
3533 fn ignores_empty_last_hops_test() {
3534 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3535 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3536 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3537 let scorer = ln_test_utils::TestScorer::new();
3538 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3539 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3541 // Test handling of an empty RouteHint passed in Invoice.
3542 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3543 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3544 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3545 assert_eq!(route.paths[0].hops.len(), 5);
3547 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3548 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3549 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3550 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3551 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3552 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3554 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3555 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3556 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3557 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3558 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3559 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3561 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3562 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3563 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3564 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3565 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3566 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3568 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3569 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3570 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3571 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3572 // If we have a peer in the node map, we'll use their features here since we don't have
3573 // a way of figuring out their features from the invoice:
3574 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3575 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3577 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3578 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3579 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3580 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3581 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3582 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3585 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3587 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3588 let zero_fees = RoutingFees {
3590 proportional_millionths: 0,
3592 vec![RouteHint(vec![RouteHintHop {
3593 src_node_id: hint_hops[0],
3594 short_channel_id: 0xff00,
3597 proportional_millionths: 0,
3599 cltv_expiry_delta: (5 << 4) | 1,
3600 htlc_minimum_msat: None,
3601 htlc_maximum_msat: None,
3603 src_node_id: hint_hops[1],
3604 short_channel_id: 0xff01,
3606 cltv_expiry_delta: (8 << 4) | 1,
3607 htlc_minimum_msat: None,
3608 htlc_maximum_msat: None,
3613 fn multi_hint_last_hops_test() {
3614 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3615 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3616 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3617 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3618 let scorer = ln_test_utils::TestScorer::new();
3619 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3620 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3621 // Test through channels 2, 3, 0xff00, 0xff01.
3622 // Test shows that multiple hop hints are considered.
3624 // Disabling channels 6 & 7 by flags=2
3625 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3627 short_channel_id: 6,
3629 flags: 2, // to disable
3630 cltv_expiry_delta: 0,
3631 htlc_minimum_msat: 0,
3632 htlc_maximum_msat: MAX_VALUE_MSAT,
3634 fee_proportional_millionths: 0,
3635 excess_data: Vec::new()
3637 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3639 short_channel_id: 7,
3641 flags: 2, // to disable
3642 cltv_expiry_delta: 0,
3643 htlc_minimum_msat: 0,
3644 htlc_maximum_msat: MAX_VALUE_MSAT,
3646 fee_proportional_millionths: 0,
3647 excess_data: Vec::new()
3650 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3651 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3652 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3653 assert_eq!(route.paths[0].hops.len(), 4);
3655 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3656 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3657 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3658 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3659 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3660 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3662 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3663 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3664 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3665 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3666 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3667 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3669 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3670 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3671 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3672 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3673 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3674 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3676 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3677 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3678 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3679 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3680 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3681 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3685 fn private_multi_hint_last_hops_test() {
3686 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3687 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3689 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3690 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3692 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3693 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3694 let scorer = ln_test_utils::TestScorer::new();
3695 // Test through channels 2, 3, 0xff00, 0xff01.
3696 // Test shows that multiple hop hints are considered.
3698 // Disabling channels 6 & 7 by flags=2
3699 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3700 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3701 short_channel_id: 6,
3703 flags: 2, // to disable
3704 cltv_expiry_delta: 0,
3705 htlc_minimum_msat: 0,
3706 htlc_maximum_msat: MAX_VALUE_MSAT,
3708 fee_proportional_millionths: 0,
3709 excess_data: Vec::new()
3711 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3713 short_channel_id: 7,
3715 flags: 2, // to disable
3716 cltv_expiry_delta: 0,
3717 htlc_minimum_msat: 0,
3718 htlc_maximum_msat: MAX_VALUE_MSAT,
3720 fee_proportional_millionths: 0,
3721 excess_data: Vec::new()
3724 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3725 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3726 Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
3727 assert_eq!(route.paths[0].hops.len(), 4);
3729 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3730 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3731 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3732 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3733 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3734 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3736 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3737 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3738 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3739 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3740 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3741 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3743 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3744 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3745 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3746 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3747 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3748 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3750 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3751 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3752 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3753 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3754 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3755 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3758 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3759 let zero_fees = RoutingFees {
3761 proportional_millionths: 0,
3763 vec![RouteHint(vec![RouteHintHop {
3764 src_node_id: nodes[4],
3765 short_channel_id: 11,
3767 cltv_expiry_delta: (11 << 4) | 1,
3768 htlc_minimum_msat: None,
3769 htlc_maximum_msat: None,
3771 src_node_id: nodes[3],
3772 short_channel_id: 8,
3774 cltv_expiry_delta: (8 << 4) | 1,
3775 htlc_minimum_msat: None,
3776 htlc_maximum_msat: None,
3777 }]), RouteHint(vec![RouteHintHop {
3778 src_node_id: nodes[4],
3779 short_channel_id: 9,
3782 proportional_millionths: 0,
3784 cltv_expiry_delta: (9 << 4) | 1,
3785 htlc_minimum_msat: None,
3786 htlc_maximum_msat: None,
3787 }]), RouteHint(vec![RouteHintHop {
3788 src_node_id: nodes[5],
3789 short_channel_id: 10,
3791 cltv_expiry_delta: (10 << 4) | 1,
3792 htlc_minimum_msat: None,
3793 htlc_maximum_msat: None,
3798 fn last_hops_with_public_channel_test() {
3799 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3800 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3801 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3802 let scorer = ln_test_utils::TestScorer::new();
3803 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3804 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3805 // This test shows that public routes can be present in the invoice
3806 // which would be handled in the same manner.
3808 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3809 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3810 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3811 assert_eq!(route.paths[0].hops.len(), 5);
3813 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3814 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3815 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3816 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3817 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3818 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3820 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3821 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3822 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3823 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3824 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3825 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3827 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3828 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3829 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3830 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3831 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3832 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3834 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3835 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3836 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3837 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3838 // If we have a peer in the node map, we'll use their features here since we don't have
3839 // a way of figuring out their features from the invoice:
3840 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3841 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3843 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3844 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3845 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3846 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3847 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3848 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3852 fn our_chans_last_hop_connect_test() {
3853 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3854 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3855 let scorer = ln_test_utils::TestScorer::new();
3856 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3857 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3859 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3860 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3861 let mut last_hops = last_hops(&nodes);
3862 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3863 .with_route_hints(last_hops.clone()).unwrap();
3864 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3865 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3866 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3867 &Default::default(), &random_seed_bytes).unwrap();
3868 assert_eq!(route.paths[0].hops.len(), 2);
3870 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3871 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3872 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3873 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3874 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3875 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3877 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3878 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3879 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3880 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3881 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3882 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3884 last_hops[0].0[0].fees.base_msat = 1000;
3886 // Revert to via 6 as the fee on 8 goes up
3887 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3888 .with_route_hints(last_hops).unwrap();
3889 let route_params = RouteParameters::from_payment_params_and_value(
3890 payment_params.clone(), 100);
3891 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3892 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3893 assert_eq!(route.paths[0].hops.len(), 4);
3895 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3896 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3897 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3898 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3899 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3900 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3902 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3903 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3904 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3905 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3906 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3907 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3909 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3910 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3911 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3912 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3913 // If we have a peer in the node map, we'll use their features here since we don't have
3914 // a way of figuring out their features from the invoice:
3915 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3916 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3918 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3919 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3920 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3921 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3922 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3923 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3925 // ...but still use 8 for larger payments as 6 has a variable feerate
3926 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
3927 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3928 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3929 assert_eq!(route.paths[0].hops.len(), 5);
3931 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3932 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3933 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3934 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3935 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3936 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3938 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3939 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3940 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3941 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3942 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3943 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3945 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3946 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3947 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3948 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3949 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3950 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3952 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3953 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3954 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3955 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3956 // If we have a peer in the node map, we'll use their features here since we don't have
3957 // a way of figuring out their features from the invoice:
3958 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3959 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3961 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3962 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3963 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3964 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3965 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3966 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3969 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> {
3970 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3971 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3972 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3974 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3975 let last_hops = RouteHint(vec![RouteHintHop {
3976 src_node_id: middle_node_id,
3977 short_channel_id: 8,
3980 proportional_millionths: last_hop_fee_prop,
3982 cltv_expiry_delta: (8 << 4) | 1,
3983 htlc_minimum_msat: None,
3984 htlc_maximum_msat: last_hop_htlc_max,
3986 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3987 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3988 let scorer = ln_test_utils::TestScorer::new();
3989 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3990 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3991 let logger = ln_test_utils::TestLogger::new();
3992 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3993 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
3994 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
3995 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
3996 &random_seed_bytes);
4001 fn unannounced_path_test() {
4002 // We should be able to send a payment to a destination without any help of a routing graph
4003 // if we have a channel with a common counterparty that appears in the first and last hop
4005 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4007 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4008 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4009 assert_eq!(route.paths[0].hops.len(), 2);
4011 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4012 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4013 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4014 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4015 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4016 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4018 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4019 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4020 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4021 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4022 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4023 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4027 fn overflow_unannounced_path_test_liquidity_underflow() {
4028 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4029 // the last-hop had a fee which overflowed a u64, we'd panic.
4030 // This was due to us adding the first-hop from us unconditionally, causing us to think
4031 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4032 // In this test, we previously hit a subtraction underflow due to having less available
4033 // liquidity at the last hop than 0.
4034 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());
4038 fn overflow_unannounced_path_test_feerate_overflow() {
4039 // This tests for the same case as above, except instead of hitting a subtraction
4040 // underflow, we hit a case where the fee charged at a hop overflowed.
4041 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());
4045 fn available_amount_while_routing_test() {
4046 // Tests whether we choose the correct available channel amount while routing.
4048 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4049 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4050 let scorer = ln_test_utils::TestScorer::new();
4051 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4052 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4053 let config = UserConfig::default();
4054 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4056 // We will use a simple single-path route from
4057 // our node to node2 via node0: channels {1, 3}.
4059 // First disable all other paths.
4060 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4061 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4062 short_channel_id: 2,
4065 cltv_expiry_delta: 0,
4066 htlc_minimum_msat: 0,
4067 htlc_maximum_msat: 100_000,
4069 fee_proportional_millionths: 0,
4070 excess_data: Vec::new()
4072 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4074 short_channel_id: 12,
4077 cltv_expiry_delta: 0,
4078 htlc_minimum_msat: 0,
4079 htlc_maximum_msat: 100_000,
4081 fee_proportional_millionths: 0,
4082 excess_data: Vec::new()
4085 // Make the first channel (#1) very permissive,
4086 // and we will be testing all limits on the second channel.
4087 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4089 short_channel_id: 1,
4092 cltv_expiry_delta: 0,
4093 htlc_minimum_msat: 0,
4094 htlc_maximum_msat: 1_000_000_000,
4096 fee_proportional_millionths: 0,
4097 excess_data: Vec::new()
4100 // First, let's see if routing works if we have absolutely no idea about the available amount.
4101 // In this case, it should be set to 250_000 sats.
4102 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4104 short_channel_id: 3,
4107 cltv_expiry_delta: 0,
4108 htlc_minimum_msat: 0,
4109 htlc_maximum_msat: 250_000_000,
4111 fee_proportional_millionths: 0,
4112 excess_data: Vec::new()
4116 // Attempt to route more than available results in a failure.
4117 let route_params = RouteParameters::from_payment_params_and_value(
4118 payment_params.clone(), 250_000_001);
4119 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4120 &our_id, &route_params, &network_graph.read_only(), None,
4121 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4122 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4123 } else { panic!(); }
4127 // Now, attempt to route an exact amount we have should be fine.
4128 let route_params = RouteParameters::from_payment_params_and_value(
4129 payment_params.clone(), 250_000_000);
4130 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4131 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4132 assert_eq!(route.paths.len(), 1);
4133 let path = route.paths.last().unwrap();
4134 assert_eq!(path.hops.len(), 2);
4135 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4136 assert_eq!(path.final_value_msat(), 250_000_000);
4139 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4140 // Disable channel #1 and use another first hop.
4141 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4143 short_channel_id: 1,
4146 cltv_expiry_delta: 0,
4147 htlc_minimum_msat: 0,
4148 htlc_maximum_msat: 1_000_000_000,
4150 fee_proportional_millionths: 0,
4151 excess_data: Vec::new()
4154 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4155 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4158 // Attempt to route more than available results in a failure.
4159 let route_params = RouteParameters::from_payment_params_and_value(
4160 payment_params.clone(), 200_000_001);
4161 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4162 &our_id, &route_params, &network_graph.read_only(),
4163 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4164 &Default::default(), &random_seed_bytes) {
4165 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4166 } else { panic!(); }
4170 // Now, attempt to route an exact amount we have should be fine.
4171 let route_params = RouteParameters::from_payment_params_and_value(
4172 payment_params.clone(), 200_000_000);
4173 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4174 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4175 &Default::default(), &random_seed_bytes).unwrap();
4176 assert_eq!(route.paths.len(), 1);
4177 let path = route.paths.last().unwrap();
4178 assert_eq!(path.hops.len(), 2);
4179 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4180 assert_eq!(path.final_value_msat(), 200_000_000);
4183 // Enable channel #1 back.
4184 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4186 short_channel_id: 1,
4189 cltv_expiry_delta: 0,
4190 htlc_minimum_msat: 0,
4191 htlc_maximum_msat: 1_000_000_000,
4193 fee_proportional_millionths: 0,
4194 excess_data: Vec::new()
4198 // Now let's see if routing works if we know only htlc_maximum_msat.
4199 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4201 short_channel_id: 3,
4204 cltv_expiry_delta: 0,
4205 htlc_minimum_msat: 0,
4206 htlc_maximum_msat: 15_000,
4208 fee_proportional_millionths: 0,
4209 excess_data: Vec::new()
4213 // Attempt to route more than available results in a failure.
4214 let route_params = RouteParameters::from_payment_params_and_value(
4215 payment_params.clone(), 15_001);
4216 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4217 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4218 &scorer, &Default::default(), &random_seed_bytes) {
4219 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4220 } else { panic!(); }
4224 // Now, attempt to route an exact amount we have should be fine.
4225 let route_params = RouteParameters::from_payment_params_and_value(
4226 payment_params.clone(), 15_000);
4227 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4228 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4229 assert_eq!(route.paths.len(), 1);
4230 let path = route.paths.last().unwrap();
4231 assert_eq!(path.hops.len(), 2);
4232 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4233 assert_eq!(path.final_value_msat(), 15_000);
4236 // Now let's see if routing works if we know only capacity from the UTXO.
4238 // We can't change UTXO capacity on the fly, so we'll disable
4239 // the existing channel and add another one with the capacity we need.
4240 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4241 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4242 short_channel_id: 3,
4245 cltv_expiry_delta: 0,
4246 htlc_minimum_msat: 0,
4247 htlc_maximum_msat: MAX_VALUE_MSAT,
4249 fee_proportional_millionths: 0,
4250 excess_data: Vec::new()
4253 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4254 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4255 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4256 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4257 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4259 *chain_monitor.utxo_ret.lock().unwrap() =
4260 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4261 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4263 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4264 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4265 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4266 short_channel_id: 333,
4269 cltv_expiry_delta: (3 << 4) | 1,
4270 htlc_minimum_msat: 0,
4271 htlc_maximum_msat: 15_000,
4273 fee_proportional_millionths: 0,
4274 excess_data: Vec::new()
4276 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4277 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4278 short_channel_id: 333,
4281 cltv_expiry_delta: (3 << 4) | 2,
4282 htlc_minimum_msat: 0,
4283 htlc_maximum_msat: 15_000,
4285 fee_proportional_millionths: 0,
4286 excess_data: Vec::new()
4290 // Attempt to route more than available results in a failure.
4291 let route_params = RouteParameters::from_payment_params_and_value(
4292 payment_params.clone(), 15_001);
4293 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4294 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4295 &scorer, &Default::default(), &random_seed_bytes) {
4296 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4297 } else { panic!(); }
4301 // Now, attempt to route an exact amount we have should be fine.
4302 let route_params = RouteParameters::from_payment_params_and_value(
4303 payment_params.clone(), 15_000);
4304 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4305 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4306 assert_eq!(route.paths.len(), 1);
4307 let path = route.paths.last().unwrap();
4308 assert_eq!(path.hops.len(), 2);
4309 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4310 assert_eq!(path.final_value_msat(), 15_000);
4313 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4314 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4316 short_channel_id: 333,
4319 cltv_expiry_delta: 0,
4320 htlc_minimum_msat: 0,
4321 htlc_maximum_msat: 10_000,
4323 fee_proportional_millionths: 0,
4324 excess_data: Vec::new()
4328 // Attempt to route more than available results in a failure.
4329 let route_params = RouteParameters::from_payment_params_and_value(
4330 payment_params.clone(), 10_001);
4331 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4332 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4333 &scorer, &Default::default(), &random_seed_bytes) {
4334 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4335 } else { panic!(); }
4339 // Now, attempt to route an exact amount we have should be fine.
4340 let route_params = RouteParameters::from_payment_params_and_value(
4341 payment_params.clone(), 10_000);
4342 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4343 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4344 assert_eq!(route.paths.len(), 1);
4345 let path = route.paths.last().unwrap();
4346 assert_eq!(path.hops.len(), 2);
4347 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4348 assert_eq!(path.final_value_msat(), 10_000);
4353 fn available_liquidity_last_hop_test() {
4354 // Check that available liquidity properly limits the path even when only
4355 // one of the latter hops is limited.
4356 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4357 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4358 let scorer = ln_test_utils::TestScorer::new();
4359 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4360 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4361 let config = UserConfig::default();
4362 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4364 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4365 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4366 // Total capacity: 50 sats.
4368 // Disable other potential paths.
4369 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4370 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4371 short_channel_id: 2,
4374 cltv_expiry_delta: 0,
4375 htlc_minimum_msat: 0,
4376 htlc_maximum_msat: 100_000,
4378 fee_proportional_millionths: 0,
4379 excess_data: Vec::new()
4381 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4382 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4383 short_channel_id: 7,
4386 cltv_expiry_delta: 0,
4387 htlc_minimum_msat: 0,
4388 htlc_maximum_msat: 100_000,
4390 fee_proportional_millionths: 0,
4391 excess_data: Vec::new()
4396 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4398 short_channel_id: 12,
4401 cltv_expiry_delta: 0,
4402 htlc_minimum_msat: 0,
4403 htlc_maximum_msat: 100_000,
4405 fee_proportional_millionths: 0,
4406 excess_data: Vec::new()
4408 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4410 short_channel_id: 13,
4413 cltv_expiry_delta: 0,
4414 htlc_minimum_msat: 0,
4415 htlc_maximum_msat: 100_000,
4417 fee_proportional_millionths: 0,
4418 excess_data: Vec::new()
4421 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4423 short_channel_id: 6,
4426 cltv_expiry_delta: 0,
4427 htlc_minimum_msat: 0,
4428 htlc_maximum_msat: 50_000,
4430 fee_proportional_millionths: 0,
4431 excess_data: Vec::new()
4433 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4434 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4435 short_channel_id: 11,
4438 cltv_expiry_delta: 0,
4439 htlc_minimum_msat: 0,
4440 htlc_maximum_msat: 100_000,
4442 fee_proportional_millionths: 0,
4443 excess_data: Vec::new()
4446 // Attempt to route more than available results in a failure.
4447 let route_params = RouteParameters::from_payment_params_and_value(
4448 payment_params.clone(), 60_000);
4449 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4450 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4451 &scorer, &Default::default(), &random_seed_bytes) {
4452 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4453 } else { panic!(); }
4457 // Now, attempt to route 49 sats (just a bit below the capacity).
4458 let route_params = RouteParameters::from_payment_params_and_value(
4459 payment_params.clone(), 49_000);
4460 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4461 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4462 assert_eq!(route.paths.len(), 1);
4463 let mut total_amount_paid_msat = 0;
4464 for path in &route.paths {
4465 assert_eq!(path.hops.len(), 4);
4466 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4467 total_amount_paid_msat += path.final_value_msat();
4469 assert_eq!(total_amount_paid_msat, 49_000);
4473 // Attempt to route an exact amount is also fine
4474 let route_params = RouteParameters::from_payment_params_and_value(
4475 payment_params, 50_000);
4476 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4477 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4478 assert_eq!(route.paths.len(), 1);
4479 let mut total_amount_paid_msat = 0;
4480 for path in &route.paths {
4481 assert_eq!(path.hops.len(), 4);
4482 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4483 total_amount_paid_msat += path.final_value_msat();
4485 assert_eq!(total_amount_paid_msat, 50_000);
4490 fn ignore_fee_first_hop_test() {
4491 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4492 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4493 let scorer = ln_test_utils::TestScorer::new();
4494 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4495 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4496 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4498 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4499 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4501 short_channel_id: 1,
4504 cltv_expiry_delta: 0,
4505 htlc_minimum_msat: 0,
4506 htlc_maximum_msat: 100_000,
4507 fee_base_msat: 1_000_000,
4508 fee_proportional_millionths: 0,
4509 excess_data: Vec::new()
4511 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4512 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4513 short_channel_id: 3,
4516 cltv_expiry_delta: 0,
4517 htlc_minimum_msat: 0,
4518 htlc_maximum_msat: 50_000,
4520 fee_proportional_millionths: 0,
4521 excess_data: Vec::new()
4525 let route_params = RouteParameters::from_payment_params_and_value(
4526 payment_params, 50_000);
4527 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4528 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4529 assert_eq!(route.paths.len(), 1);
4530 let mut total_amount_paid_msat = 0;
4531 for path in &route.paths {
4532 assert_eq!(path.hops.len(), 2);
4533 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4534 total_amount_paid_msat += path.final_value_msat();
4536 assert_eq!(total_amount_paid_msat, 50_000);
4541 fn simple_mpp_route_test() {
4542 let (secp_ctx, _, _, _, _) = build_graph();
4543 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4544 let config = UserConfig::default();
4545 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4546 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4547 do_simple_mpp_route_test(clear_payment_params);
4549 // MPP to a 1-hop blinded path for nodes[2]
4550 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4551 let blinded_path = BlindedPath {
4552 introduction_node_id: nodes[2],
4553 blinding_point: ln_test_utils::pubkey(42),
4554 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4556 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4558 fee_proportional_millionths: 0,
4559 htlc_minimum_msat: 0,
4560 htlc_maximum_msat: 0,
4561 cltv_expiry_delta: 0,
4562 features: BlindedHopFeatures::empty(),
4564 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4565 .with_bolt12_features(bolt12_features.clone()).unwrap();
4566 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4568 // MPP to 3 2-hop blinded paths
4569 let mut blinded_path_node_0 = blinded_path.clone();
4570 blinded_path_node_0.introduction_node_id = nodes[0];
4571 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4572 let mut node_0_payinfo = blinded_payinfo.clone();
4573 node_0_payinfo.htlc_maximum_msat = 50_000;
4575 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4576 blinded_path_node_7.introduction_node_id = nodes[7];
4577 let mut node_7_payinfo = blinded_payinfo.clone();
4578 node_7_payinfo.htlc_maximum_msat = 60_000;
4580 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4581 blinded_path_node_1.introduction_node_id = nodes[1];
4582 let mut node_1_payinfo = blinded_payinfo.clone();
4583 node_1_payinfo.htlc_maximum_msat = 180_000;
4585 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4587 (node_0_payinfo, blinded_path_node_0),
4588 (node_7_payinfo, blinded_path_node_7),
4589 (node_1_payinfo, blinded_path_node_1)
4591 .with_bolt12_features(bolt12_features).unwrap();
4592 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4596 fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4597 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4598 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4599 let scorer = ln_test_utils::TestScorer::new();
4600 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4601 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4603 // We need a route consisting of 3 paths:
4604 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4605 // To achieve this, the amount being transferred should be around
4606 // the total capacity of these 3 paths.
4608 // First, we set limits on these (previously unlimited) channels.
4609 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4611 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4612 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4613 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4614 short_channel_id: 1,
4617 cltv_expiry_delta: 0,
4618 htlc_minimum_msat: 0,
4619 htlc_maximum_msat: 100_000,
4621 fee_proportional_millionths: 0,
4622 excess_data: Vec::new()
4624 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4625 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4626 short_channel_id: 3,
4629 cltv_expiry_delta: 0,
4630 htlc_minimum_msat: 0,
4631 htlc_maximum_msat: 50_000,
4633 fee_proportional_millionths: 0,
4634 excess_data: Vec::new()
4637 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4638 // (total limit 60).
4639 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4641 short_channel_id: 12,
4644 cltv_expiry_delta: 0,
4645 htlc_minimum_msat: 0,
4646 htlc_maximum_msat: 60_000,
4648 fee_proportional_millionths: 0,
4649 excess_data: Vec::new()
4651 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4653 short_channel_id: 13,
4656 cltv_expiry_delta: 0,
4657 htlc_minimum_msat: 0,
4658 htlc_maximum_msat: 60_000,
4660 fee_proportional_millionths: 0,
4661 excess_data: Vec::new()
4664 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4665 // (total capacity 180 sats).
4666 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4668 short_channel_id: 2,
4671 cltv_expiry_delta: 0,
4672 htlc_minimum_msat: 0,
4673 htlc_maximum_msat: 200_000,
4675 fee_proportional_millionths: 0,
4676 excess_data: Vec::new()
4678 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4680 short_channel_id: 4,
4683 cltv_expiry_delta: 0,
4684 htlc_minimum_msat: 0,
4685 htlc_maximum_msat: 180_000,
4687 fee_proportional_millionths: 0,
4688 excess_data: Vec::new()
4692 // Attempt to route more than available results in a failure.
4693 let route_params = RouteParameters::from_payment_params_and_value(
4694 payment_params.clone(), 300_000);
4695 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4696 &our_id, &route_params, &network_graph.read_only(), None,
4697 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4698 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4699 } else { panic!(); }
4703 // Attempt to route while setting max_path_count to 0 results in a failure.
4704 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4705 let route_params = RouteParameters::from_payment_params_and_value(
4706 zero_payment_params, 100);
4707 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4708 &our_id, &route_params, &network_graph.read_only(), None,
4709 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4710 assert_eq!(err, "Can't find a route with no paths allowed.");
4711 } else { panic!(); }
4715 // Attempt to route while setting max_path_count to 3 results in a failure.
4716 // This is the case because the minimal_value_contribution_msat would require each path
4717 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4718 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4719 let route_params = RouteParameters::from_payment_params_and_value(
4720 fail_payment_params, 250_000);
4721 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4722 &our_id, &route_params, &network_graph.read_only(), None,
4723 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4724 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4725 } else { panic!(); }
4729 // Now, attempt to route 250 sats (just a bit below the capacity).
4730 // Our algorithm should provide us with these 3 paths.
4731 let route_params = RouteParameters::from_payment_params_and_value(
4732 payment_params.clone(), 250_000);
4733 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4734 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4735 assert_eq!(route.paths.len(), 3);
4736 let mut total_amount_paid_msat = 0;
4737 for path in &route.paths {
4738 if let Some(bt) = &path.blinded_tail {
4739 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4741 assert_eq!(path.hops.len(), 2);
4742 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4744 total_amount_paid_msat += path.final_value_msat();
4746 assert_eq!(total_amount_paid_msat, 250_000);
4750 // Attempt to route an exact amount is also fine
4751 let route_params = RouteParameters::from_payment_params_and_value(
4752 payment_params.clone(), 290_000);
4753 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4754 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4755 assert_eq!(route.paths.len(), 3);
4756 let mut total_amount_paid_msat = 0;
4757 for path in &route.paths {
4758 if payment_params.payee.blinded_route_hints().len() != 0 {
4759 assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4760 if let Some(bt) = &path.blinded_tail {
4761 assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4762 if bt.hops.len() > 1 {
4763 assert_eq!(path.hops.last().unwrap().pubkey,
4764 payment_params.payee.blinded_route_hints().iter()
4765 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4766 .map(|(_, p)| p.introduction_node_id).unwrap());
4768 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4771 assert_eq!(path.hops.len(), 2);
4772 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4774 total_amount_paid_msat += path.final_value_msat();
4776 assert_eq!(total_amount_paid_msat, 290_000);
4781 fn long_mpp_route_test() {
4782 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4783 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4784 let scorer = ln_test_utils::TestScorer::new();
4785 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4786 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4787 let config = UserConfig::default();
4788 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4789 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4791 // We need a route consisting of 3 paths:
4792 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4793 // Note that these paths overlap (channels 5, 12, 13).
4794 // We will route 300 sats.
4795 // Each path will have 100 sats capacity, those channels which
4796 // are used twice will have 200 sats capacity.
4798 // Disable other potential paths.
4799 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4801 short_channel_id: 2,
4804 cltv_expiry_delta: 0,
4805 htlc_minimum_msat: 0,
4806 htlc_maximum_msat: 100_000,
4808 fee_proportional_millionths: 0,
4809 excess_data: Vec::new()
4811 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4812 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4813 short_channel_id: 7,
4816 cltv_expiry_delta: 0,
4817 htlc_minimum_msat: 0,
4818 htlc_maximum_msat: 100_000,
4820 fee_proportional_millionths: 0,
4821 excess_data: Vec::new()
4824 // Path via {node0, node2} is channels {1, 3, 5}.
4825 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4826 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4827 short_channel_id: 1,
4830 cltv_expiry_delta: 0,
4831 htlc_minimum_msat: 0,
4832 htlc_maximum_msat: 100_000,
4834 fee_proportional_millionths: 0,
4835 excess_data: Vec::new()
4837 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4838 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4839 short_channel_id: 3,
4842 cltv_expiry_delta: 0,
4843 htlc_minimum_msat: 0,
4844 htlc_maximum_msat: 100_000,
4846 fee_proportional_millionths: 0,
4847 excess_data: Vec::new()
4850 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4851 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4852 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4853 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4854 short_channel_id: 5,
4857 cltv_expiry_delta: 0,
4858 htlc_minimum_msat: 0,
4859 htlc_maximum_msat: 200_000,
4861 fee_proportional_millionths: 0,
4862 excess_data: Vec::new()
4865 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4866 // Add 100 sats to the capacities of {12, 13}, because these channels
4867 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4868 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4870 short_channel_id: 12,
4873 cltv_expiry_delta: 0,
4874 htlc_minimum_msat: 0,
4875 htlc_maximum_msat: 200_000,
4877 fee_proportional_millionths: 0,
4878 excess_data: Vec::new()
4880 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4882 short_channel_id: 13,
4885 cltv_expiry_delta: 0,
4886 htlc_minimum_msat: 0,
4887 htlc_maximum_msat: 200_000,
4889 fee_proportional_millionths: 0,
4890 excess_data: Vec::new()
4893 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4895 short_channel_id: 6,
4898 cltv_expiry_delta: 0,
4899 htlc_minimum_msat: 0,
4900 htlc_maximum_msat: 100_000,
4902 fee_proportional_millionths: 0,
4903 excess_data: Vec::new()
4905 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4906 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4907 short_channel_id: 11,
4910 cltv_expiry_delta: 0,
4911 htlc_minimum_msat: 0,
4912 htlc_maximum_msat: 100_000,
4914 fee_proportional_millionths: 0,
4915 excess_data: Vec::new()
4918 // Path via {node7, node2} is channels {12, 13, 5}.
4919 // We already limited them to 200 sats (they are used twice for 100 sats).
4920 // Nothing to do here.
4923 // Attempt to route more than available results in a failure.
4924 let route_params = RouteParameters::from_payment_params_and_value(
4925 payment_params.clone(), 350_000);
4926 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4927 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4928 &scorer, &Default::default(), &random_seed_bytes) {
4929 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4930 } else { panic!(); }
4934 // Now, attempt to route 300 sats (exact amount we can route).
4935 // Our algorithm should provide us with these 3 paths, 100 sats each.
4936 let route_params = RouteParameters::from_payment_params_and_value(
4937 payment_params, 300_000);
4938 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4939 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4940 assert_eq!(route.paths.len(), 3);
4942 let mut total_amount_paid_msat = 0;
4943 for path in &route.paths {
4944 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4945 total_amount_paid_msat += path.final_value_msat();
4947 assert_eq!(total_amount_paid_msat, 300_000);
4953 fn mpp_cheaper_route_test() {
4954 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4955 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4956 let scorer = ln_test_utils::TestScorer::new();
4957 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4958 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4959 let config = UserConfig::default();
4960 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4962 // This test checks that if we have two cheaper paths and one more expensive path,
4963 // so that liquidity-wise any 2 of 3 combination is sufficient,
4964 // two cheaper paths will be taken.
4965 // These paths have equal available liquidity.
4967 // We need a combination of 3 paths:
4968 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4969 // Note that these paths overlap (channels 5, 12, 13).
4970 // Each path will have 100 sats capacity, those channels which
4971 // are used twice will have 200 sats capacity.
4973 // Disable other potential paths.
4974 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4975 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4976 short_channel_id: 2,
4979 cltv_expiry_delta: 0,
4980 htlc_minimum_msat: 0,
4981 htlc_maximum_msat: 100_000,
4983 fee_proportional_millionths: 0,
4984 excess_data: Vec::new()
4986 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4988 short_channel_id: 7,
4991 cltv_expiry_delta: 0,
4992 htlc_minimum_msat: 0,
4993 htlc_maximum_msat: 100_000,
4995 fee_proportional_millionths: 0,
4996 excess_data: Vec::new()
4999 // Path via {node0, node2} is channels {1, 3, 5}.
5000 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5002 short_channel_id: 1,
5005 cltv_expiry_delta: 0,
5006 htlc_minimum_msat: 0,
5007 htlc_maximum_msat: 100_000,
5009 fee_proportional_millionths: 0,
5010 excess_data: Vec::new()
5012 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5014 short_channel_id: 3,
5017 cltv_expiry_delta: 0,
5018 htlc_minimum_msat: 0,
5019 htlc_maximum_msat: 100_000,
5021 fee_proportional_millionths: 0,
5022 excess_data: Vec::new()
5025 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5026 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5027 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5029 short_channel_id: 5,
5032 cltv_expiry_delta: 0,
5033 htlc_minimum_msat: 0,
5034 htlc_maximum_msat: 200_000,
5036 fee_proportional_millionths: 0,
5037 excess_data: Vec::new()
5040 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5041 // Add 100 sats to the capacities of {12, 13}, because these channels
5042 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5043 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5045 short_channel_id: 12,
5048 cltv_expiry_delta: 0,
5049 htlc_minimum_msat: 0,
5050 htlc_maximum_msat: 200_000,
5052 fee_proportional_millionths: 0,
5053 excess_data: Vec::new()
5055 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5057 short_channel_id: 13,
5060 cltv_expiry_delta: 0,
5061 htlc_minimum_msat: 0,
5062 htlc_maximum_msat: 200_000,
5064 fee_proportional_millionths: 0,
5065 excess_data: Vec::new()
5068 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5070 short_channel_id: 6,
5073 cltv_expiry_delta: 0,
5074 htlc_minimum_msat: 0,
5075 htlc_maximum_msat: 100_000,
5076 fee_base_msat: 1_000,
5077 fee_proportional_millionths: 0,
5078 excess_data: Vec::new()
5080 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5082 short_channel_id: 11,
5085 cltv_expiry_delta: 0,
5086 htlc_minimum_msat: 0,
5087 htlc_maximum_msat: 100_000,
5089 fee_proportional_millionths: 0,
5090 excess_data: Vec::new()
5093 // Path via {node7, node2} is channels {12, 13, 5}.
5094 // We already limited them to 200 sats (they are used twice for 100 sats).
5095 // Nothing to do here.
5098 // Now, attempt to route 180 sats.
5099 // Our algorithm should provide us with these 2 paths.
5100 let route_params = RouteParameters::from_payment_params_and_value(
5101 payment_params, 180_000);
5102 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5103 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5104 assert_eq!(route.paths.len(), 2);
5106 let mut total_value_transferred_msat = 0;
5107 let mut total_paid_msat = 0;
5108 for path in &route.paths {
5109 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5110 total_value_transferred_msat += path.final_value_msat();
5111 for hop in &path.hops {
5112 total_paid_msat += hop.fee_msat;
5115 // If we paid fee, this would be higher.
5116 assert_eq!(total_value_transferred_msat, 180_000);
5117 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5118 assert_eq!(total_fees_paid, 0);
5123 fn fees_on_mpp_route_test() {
5124 // This test makes sure that MPP algorithm properly takes into account
5125 // fees charged on the channels, by making the fees impactful:
5126 // if the fee is not properly accounted for, the behavior is different.
5127 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5128 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5129 let scorer = ln_test_utils::TestScorer::new();
5130 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5131 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5132 let config = UserConfig::default();
5133 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5135 // We need a route consisting of 2 paths:
5136 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5137 // We will route 200 sats, Each path will have 100 sats capacity.
5139 // This test is not particularly stable: e.g.,
5140 // there's a way to route via {node0, node2, node4}.
5141 // It works while pathfinding is deterministic, but can be broken otherwise.
5142 // It's fine to ignore this concern for now.
5144 // Disable other potential paths.
5145 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5146 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5147 short_channel_id: 2,
5150 cltv_expiry_delta: 0,
5151 htlc_minimum_msat: 0,
5152 htlc_maximum_msat: 100_000,
5154 fee_proportional_millionths: 0,
5155 excess_data: Vec::new()
5158 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5160 short_channel_id: 7,
5163 cltv_expiry_delta: 0,
5164 htlc_minimum_msat: 0,
5165 htlc_maximum_msat: 100_000,
5167 fee_proportional_millionths: 0,
5168 excess_data: Vec::new()
5171 // Path via {node0, node2} is channels {1, 3, 5}.
5172 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5174 short_channel_id: 1,
5177 cltv_expiry_delta: 0,
5178 htlc_minimum_msat: 0,
5179 htlc_maximum_msat: 100_000,
5181 fee_proportional_millionths: 0,
5182 excess_data: Vec::new()
5184 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5186 short_channel_id: 3,
5189 cltv_expiry_delta: 0,
5190 htlc_minimum_msat: 0,
5191 htlc_maximum_msat: 100_000,
5193 fee_proportional_millionths: 0,
5194 excess_data: Vec::new()
5197 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5198 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5200 short_channel_id: 5,
5203 cltv_expiry_delta: 0,
5204 htlc_minimum_msat: 0,
5205 htlc_maximum_msat: 100_000,
5207 fee_proportional_millionths: 0,
5208 excess_data: Vec::new()
5211 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5212 // All channels should be 100 sats capacity. But for the fee experiment,
5213 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5214 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5215 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5216 // so no matter how large are other channels,
5217 // the whole path will be limited by 100 sats with just these 2 conditions:
5218 // - channel 12 capacity is 250 sats
5219 // - fee for channel 6 is 150 sats
5220 // Let's test this by enforcing these 2 conditions and removing other limits.
5221 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5223 short_channel_id: 12,
5226 cltv_expiry_delta: 0,
5227 htlc_minimum_msat: 0,
5228 htlc_maximum_msat: 250_000,
5230 fee_proportional_millionths: 0,
5231 excess_data: Vec::new()
5233 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5235 short_channel_id: 13,
5238 cltv_expiry_delta: 0,
5239 htlc_minimum_msat: 0,
5240 htlc_maximum_msat: MAX_VALUE_MSAT,
5242 fee_proportional_millionths: 0,
5243 excess_data: Vec::new()
5246 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5248 short_channel_id: 6,
5251 cltv_expiry_delta: 0,
5252 htlc_minimum_msat: 0,
5253 htlc_maximum_msat: MAX_VALUE_MSAT,
5254 fee_base_msat: 150_000,
5255 fee_proportional_millionths: 0,
5256 excess_data: Vec::new()
5258 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5260 short_channel_id: 11,
5263 cltv_expiry_delta: 0,
5264 htlc_minimum_msat: 0,
5265 htlc_maximum_msat: MAX_VALUE_MSAT,
5267 fee_proportional_millionths: 0,
5268 excess_data: Vec::new()
5272 // Attempt to route more than available results in a failure.
5273 let route_params = RouteParameters::from_payment_params_and_value(
5274 payment_params.clone(), 210_000);
5275 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5276 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5277 &scorer, &Default::default(), &random_seed_bytes) {
5278 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5279 } else { panic!(); }
5283 // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5284 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5285 max_total_routing_fee_msat: Some(149_999) };
5286 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5287 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5288 &scorer, &(), &random_seed_bytes) {
5289 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5290 } else { panic!(); }
5294 // Now, attempt to route 200 sats (exact amount we can route).
5295 let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5296 max_total_routing_fee_msat: Some(150_000) };
5297 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5298 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5299 assert_eq!(route.paths.len(), 2);
5301 let mut total_amount_paid_msat = 0;
5302 for path in &route.paths {
5303 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5304 total_amount_paid_msat += path.final_value_msat();
5306 assert_eq!(total_amount_paid_msat, 200_000);
5307 assert_eq!(route.get_total_fees(), 150_000);
5312 fn mpp_with_last_hops() {
5313 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5314 // via a single last-hop route hint, we'd fail to route if we first collected routes
5315 // totaling close but not quite enough to fund the full payment.
5317 // This was because we considered last-hop hints to have exactly the sought payment amount
5318 // instead of the amount we were trying to collect, needlessly limiting our path searching
5319 // at the very first hop.
5321 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5322 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5323 // to only have the remaining to-collect amount in available liquidity.
5325 // This bug appeared in production in some specific channel configurations.
5326 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5327 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5328 let scorer = ln_test_utils::TestScorer::new();
5329 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5330 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5331 let config = UserConfig::default();
5332 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5333 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5334 src_node_id: nodes[2],
5335 short_channel_id: 42,
5336 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5337 cltv_expiry_delta: 42,
5338 htlc_minimum_msat: None,
5339 htlc_maximum_msat: None,
5340 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5342 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5343 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5344 // would first use the no-fee route and then fail to find a path along the second route as
5345 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5346 // under 5% of our payment amount.
5347 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5349 short_channel_id: 1,
5352 cltv_expiry_delta: (5 << 4) | 5,
5353 htlc_minimum_msat: 0,
5354 htlc_maximum_msat: 99_000,
5355 fee_base_msat: u32::max_value(),
5356 fee_proportional_millionths: u32::max_value(),
5357 excess_data: Vec::new()
5359 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5360 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5361 short_channel_id: 2,
5364 cltv_expiry_delta: (5 << 4) | 3,
5365 htlc_minimum_msat: 0,
5366 htlc_maximum_msat: 99_000,
5367 fee_base_msat: u32::max_value(),
5368 fee_proportional_millionths: u32::max_value(),
5369 excess_data: Vec::new()
5371 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5372 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5373 short_channel_id: 4,
5376 cltv_expiry_delta: (4 << 4) | 1,
5377 htlc_minimum_msat: 0,
5378 htlc_maximum_msat: MAX_VALUE_MSAT,
5380 fee_proportional_millionths: 0,
5381 excess_data: Vec::new()
5383 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5384 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5385 short_channel_id: 13,
5387 flags: 0|2, // Channel disabled
5388 cltv_expiry_delta: (13 << 4) | 1,
5389 htlc_minimum_msat: 0,
5390 htlc_maximum_msat: MAX_VALUE_MSAT,
5392 fee_proportional_millionths: 2000000,
5393 excess_data: Vec::new()
5396 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5398 let route_params = RouteParameters::from_payment_params_and_value(
5399 payment_params, 100_000);
5400 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5401 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5402 assert_eq!(route.paths.len(), 2);
5403 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5404 // Paths are manually ordered ordered by SCID, so:
5405 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5406 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5407 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5408 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5409 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5410 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5411 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5412 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5413 assert_eq!(route.get_total_fees(), 1);
5414 assert_eq!(route.get_total_amount(), 100_000);
5418 fn drop_lowest_channel_mpp_route_test() {
5419 // This test checks that low-capacity channel is dropped when after
5420 // path finding we realize that we found more capacity than we need.
5421 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5422 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5423 let scorer = ln_test_utils::TestScorer::new();
5424 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5425 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5426 let config = UserConfig::default();
5427 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5428 .with_max_channel_saturation_power_of_half(0);
5430 // We need a route consisting of 3 paths:
5431 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5433 // The first and the second paths should be sufficient, but the third should be
5434 // cheaper, so that we select it but drop later.
5436 // First, we set limits on these (previously unlimited) channels.
5437 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5439 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5440 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5442 short_channel_id: 1,
5445 cltv_expiry_delta: 0,
5446 htlc_minimum_msat: 0,
5447 htlc_maximum_msat: 100_000,
5449 fee_proportional_millionths: 0,
5450 excess_data: Vec::new()
5452 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5454 short_channel_id: 3,
5457 cltv_expiry_delta: 0,
5458 htlc_minimum_msat: 0,
5459 htlc_maximum_msat: 50_000,
5461 fee_proportional_millionths: 0,
5462 excess_data: Vec::new()
5465 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5466 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5467 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5468 short_channel_id: 12,
5471 cltv_expiry_delta: 0,
5472 htlc_minimum_msat: 0,
5473 htlc_maximum_msat: 60_000,
5475 fee_proportional_millionths: 0,
5476 excess_data: Vec::new()
5478 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5480 short_channel_id: 13,
5483 cltv_expiry_delta: 0,
5484 htlc_minimum_msat: 0,
5485 htlc_maximum_msat: 60_000,
5487 fee_proportional_millionths: 0,
5488 excess_data: Vec::new()
5491 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5492 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5493 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5494 short_channel_id: 2,
5497 cltv_expiry_delta: 0,
5498 htlc_minimum_msat: 0,
5499 htlc_maximum_msat: 20_000,
5501 fee_proportional_millionths: 0,
5502 excess_data: Vec::new()
5504 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5505 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5506 short_channel_id: 4,
5509 cltv_expiry_delta: 0,
5510 htlc_minimum_msat: 0,
5511 htlc_maximum_msat: 20_000,
5513 fee_proportional_millionths: 0,
5514 excess_data: Vec::new()
5518 // Attempt to route more than available results in a failure.
5519 let route_params = RouteParameters::from_payment_params_and_value(
5520 payment_params.clone(), 150_000);
5521 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5522 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5523 &scorer, &Default::default(), &random_seed_bytes) {
5524 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5525 } else { panic!(); }
5529 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5530 // Our algorithm should provide us with these 3 paths.
5531 let route_params = RouteParameters::from_payment_params_and_value(
5532 payment_params.clone(), 125_000);
5533 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5534 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5535 assert_eq!(route.paths.len(), 3);
5536 let mut total_amount_paid_msat = 0;
5537 for path in &route.paths {
5538 assert_eq!(path.hops.len(), 2);
5539 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5540 total_amount_paid_msat += path.final_value_msat();
5542 assert_eq!(total_amount_paid_msat, 125_000);
5546 // Attempt to route without the last small cheap channel
5547 let route_params = RouteParameters::from_payment_params_and_value(
5548 payment_params, 90_000);
5549 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5550 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5551 assert_eq!(route.paths.len(), 2);
5552 let mut total_amount_paid_msat = 0;
5553 for path in &route.paths {
5554 assert_eq!(path.hops.len(), 2);
5555 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5556 total_amount_paid_msat += path.final_value_msat();
5558 assert_eq!(total_amount_paid_msat, 90_000);
5563 fn min_criteria_consistency() {
5564 // Test that we don't use an inconsistent metric between updating and walking nodes during
5565 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5566 // was updated with a different criterion from the heap sorting, resulting in loops in
5567 // calculated paths. We test for that specific case here.
5569 // We construct a network that looks like this:
5571 // node2 -1(3)2- node3
5575 // node1 -1(5)2- node4 -1(1)2- node6
5581 // We create a loop on the side of our real path - our destination is node 6, with a
5582 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5583 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5584 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5585 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5586 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5587 // "previous hop" being set to node 3, creating a loop in the path.
5588 let secp_ctx = Secp256k1::new();
5589 let logger = Arc::new(ln_test_utils::TestLogger::new());
5590 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5591 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5592 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5593 let scorer = ln_test_utils::TestScorer::new();
5594 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5595 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5596 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5598 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5599 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5601 short_channel_id: 6,
5604 cltv_expiry_delta: (6 << 4) | 0,
5605 htlc_minimum_msat: 0,
5606 htlc_maximum_msat: MAX_VALUE_MSAT,
5608 fee_proportional_millionths: 0,
5609 excess_data: Vec::new()
5611 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5613 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5614 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5616 short_channel_id: 5,
5619 cltv_expiry_delta: (5 << 4) | 0,
5620 htlc_minimum_msat: 0,
5621 htlc_maximum_msat: MAX_VALUE_MSAT,
5623 fee_proportional_millionths: 0,
5624 excess_data: Vec::new()
5626 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5628 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5629 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5630 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5631 short_channel_id: 4,
5634 cltv_expiry_delta: (4 << 4) | 0,
5635 htlc_minimum_msat: 0,
5636 htlc_maximum_msat: MAX_VALUE_MSAT,
5638 fee_proportional_millionths: 0,
5639 excess_data: Vec::new()
5641 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5643 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5644 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5645 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5646 short_channel_id: 3,
5649 cltv_expiry_delta: (3 << 4) | 0,
5650 htlc_minimum_msat: 0,
5651 htlc_maximum_msat: MAX_VALUE_MSAT,
5653 fee_proportional_millionths: 0,
5654 excess_data: Vec::new()
5656 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5658 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5659 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5661 short_channel_id: 2,
5664 cltv_expiry_delta: (2 << 4) | 0,
5665 htlc_minimum_msat: 0,
5666 htlc_maximum_msat: MAX_VALUE_MSAT,
5668 fee_proportional_millionths: 0,
5669 excess_data: Vec::new()
5672 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5673 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5674 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5675 short_channel_id: 1,
5678 cltv_expiry_delta: (1 << 4) | 0,
5679 htlc_minimum_msat: 100,
5680 htlc_maximum_msat: MAX_VALUE_MSAT,
5682 fee_proportional_millionths: 0,
5683 excess_data: Vec::new()
5685 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5688 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5689 let route_params = RouteParameters::from_payment_params_and_value(
5690 payment_params, 10_000);
5691 let route = get_route(&our_id, &route_params, &network.read_only(), None,
5692 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5693 assert_eq!(route.paths.len(), 1);
5694 assert_eq!(route.paths[0].hops.len(), 3);
5696 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5697 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5698 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5699 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5700 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5701 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5703 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5704 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5705 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5706 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5707 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5708 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5710 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5711 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5712 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5713 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5714 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5715 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5721 fn exact_fee_liquidity_limit() {
5722 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5723 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5724 // we calculated fees on a higher value, resulting in us ignoring such paths.
5725 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5726 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5727 let scorer = ln_test_utils::TestScorer::new();
5728 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5729 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5730 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5732 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5734 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5735 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5736 short_channel_id: 2,
5739 cltv_expiry_delta: 0,
5740 htlc_minimum_msat: 0,
5741 htlc_maximum_msat: 85_000,
5743 fee_proportional_millionths: 0,
5744 excess_data: Vec::new()
5747 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5749 short_channel_id: 12,
5752 cltv_expiry_delta: (4 << 4) | 1,
5753 htlc_minimum_msat: 0,
5754 htlc_maximum_msat: 270_000,
5756 fee_proportional_millionths: 1000000,
5757 excess_data: Vec::new()
5761 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5762 // 200% fee charged channel 13 in the 1-to-2 direction.
5763 let mut route_params = RouteParameters::from_payment_params_and_value(
5764 payment_params, 90_000);
5765 route_params.max_total_routing_fee_msat = Some(90_000*2);
5766 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5767 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5768 assert_eq!(route.paths.len(), 1);
5769 assert_eq!(route.paths[0].hops.len(), 2);
5771 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5772 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5773 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5774 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5775 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5776 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5778 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5779 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5780 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5781 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5782 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5783 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5788 fn htlc_max_reduction_below_min() {
5789 // Test that if, while walking the graph, we reduce the value being sent to meet an
5790 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5791 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5792 // resulting in us thinking there is no possible path, even if other paths exist.
5793 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5794 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5795 let scorer = ln_test_utils::TestScorer::new();
5796 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5797 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5798 let config = UserConfig::default();
5799 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5801 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5802 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5803 // then try to send 90_000.
5804 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5806 short_channel_id: 2,
5809 cltv_expiry_delta: 0,
5810 htlc_minimum_msat: 0,
5811 htlc_maximum_msat: 80_000,
5813 fee_proportional_millionths: 0,
5814 excess_data: Vec::new()
5816 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5818 short_channel_id: 4,
5821 cltv_expiry_delta: (4 << 4) | 1,
5822 htlc_minimum_msat: 90_000,
5823 htlc_maximum_msat: MAX_VALUE_MSAT,
5825 fee_proportional_millionths: 0,
5826 excess_data: Vec::new()
5830 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5831 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5832 // expensive) channels 12-13 path.
5833 let mut route_params = RouteParameters::from_payment_params_and_value(
5834 payment_params, 90_000);
5835 route_params.max_total_routing_fee_msat = Some(90_000*2);
5836 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5837 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5838 assert_eq!(route.paths.len(), 1);
5839 assert_eq!(route.paths[0].hops.len(), 2);
5841 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5842 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5843 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5844 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5845 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5846 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5848 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5849 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5850 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5851 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5852 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5853 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5858 fn multiple_direct_first_hops() {
5859 // Previously we'd only ever considered one first hop path per counterparty.
5860 // However, as we don't restrict users to one channel per peer, we really need to support
5861 // looking at all first hop paths.
5862 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5863 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5864 // route over multiple channels with the same first hop.
5865 let secp_ctx = Secp256k1::new();
5866 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5867 let logger = Arc::new(ln_test_utils::TestLogger::new());
5868 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5869 let scorer = ln_test_utils::TestScorer::new();
5870 let config = UserConfig::default();
5871 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5872 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5873 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5876 let route_params = RouteParameters::from_payment_params_and_value(
5877 payment_params.clone(), 100_000);
5878 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5879 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5880 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5881 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5882 assert_eq!(route.paths.len(), 1);
5883 assert_eq!(route.paths[0].hops.len(), 1);
5885 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5886 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5887 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5890 let route_params = RouteParameters::from_payment_params_and_value(
5891 payment_params.clone(), 100_000);
5892 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5893 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5894 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5895 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5896 assert_eq!(route.paths.len(), 2);
5897 assert_eq!(route.paths[0].hops.len(), 1);
5898 assert_eq!(route.paths[1].hops.len(), 1);
5900 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5901 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5903 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5904 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5906 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5907 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5911 // If we have a bunch of outbound channels to the same node, where most are not
5912 // sufficient to pay the full payment, but one is, we should default to just using the
5913 // one single channel that has sufficient balance, avoiding MPP.
5915 // If we have several options above the 3xpayment value threshold, we should pick the
5916 // smallest of them, avoiding further fragmenting our available outbound balance to
5918 let route_params = RouteParameters::from_payment_params_and_value(
5919 payment_params, 100_000);
5920 let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
5921 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5922 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5923 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5924 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5925 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5926 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5927 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5928 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5929 ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5930 assert_eq!(route.paths.len(), 1);
5931 assert_eq!(route.paths[0].hops.len(), 1);
5933 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5934 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5935 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5940 fn prefers_shorter_route_with_higher_fees() {
5941 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5942 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5943 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5945 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5946 let scorer = ln_test_utils::TestScorer::new();
5947 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5948 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5949 let route_params = RouteParameters::from_payment_params_and_value(
5950 payment_params.clone(), 100);
5951 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5952 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5953 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5955 assert_eq!(route.get_total_fees(), 100);
5956 assert_eq!(route.get_total_amount(), 100);
5957 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5959 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5960 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5961 let scorer = FixedPenaltyScorer::with_penalty(100);
5962 let route_params = RouteParameters::from_payment_params_and_value(
5963 payment_params, 100);
5964 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
5965 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5966 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5968 assert_eq!(route.get_total_fees(), 300);
5969 assert_eq!(route.get_total_amount(), 100);
5970 assert_eq!(path, vec![2, 4, 7, 10]);
5973 struct BadChannelScorer {
5974 short_channel_id: u64,
5978 impl Writeable for BadChannelScorer {
5979 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5981 impl ScoreLookUp for BadChannelScorer {
5982 type ScoreParams = ();
5983 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5984 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5988 struct BadNodeScorer {
5993 impl Writeable for BadNodeScorer {
5994 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5997 impl ScoreLookUp for BadNodeScorer {
5998 type ScoreParams = ();
5999 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6000 if *target == self.node_id { u64::max_value() } else { 0 }
6005 fn avoids_routing_through_bad_channels_and_nodes() {
6006 let (secp_ctx, network, _, _, logger) = build_graph();
6007 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6008 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6009 let network_graph = network.read_only();
6011 // A path to nodes[6] exists when no penalties are applied to any channel.
6012 let scorer = ln_test_utils::TestScorer::new();
6013 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6014 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6015 let route_params = RouteParameters::from_payment_params_and_value(
6016 payment_params, 100);
6017 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6018 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6019 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6021 assert_eq!(route.get_total_fees(), 100);
6022 assert_eq!(route.get_total_amount(), 100);
6023 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6025 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6026 let scorer = BadChannelScorer { short_channel_id: 6 };
6027 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6028 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6029 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6031 assert_eq!(route.get_total_fees(), 300);
6032 assert_eq!(route.get_total_amount(), 100);
6033 assert_eq!(path, vec![2, 4, 7, 10]);
6035 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6036 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6037 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6038 &scorer, &Default::default(), &random_seed_bytes) {
6039 Err(LightningError { err, .. } ) => {
6040 assert_eq!(err, "Failed to find a path to the given destination");
6042 Ok(_) => panic!("Expected error"),
6047 fn total_fees_single_path() {
6049 paths: vec![Path { hops: vec![
6051 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6052 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6053 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6056 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6057 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6058 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6061 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6062 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6063 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6065 ], blinded_tail: None }],
6069 assert_eq!(route.get_total_fees(), 250);
6070 assert_eq!(route.get_total_amount(), 225);
6074 fn total_fees_multi_path() {
6076 paths: vec![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 }, Path { hops: vec![
6089 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6090 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6091 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6094 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6095 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6096 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6098 ], blinded_tail: None }],
6102 assert_eq!(route.get_total_fees(), 200);
6103 assert_eq!(route.get_total_amount(), 300);
6107 fn total_empty_route_no_panic() {
6108 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6109 // would both panic if the route was completely empty. We test to ensure they return 0
6110 // here, even though its somewhat nonsensical as a route.
6111 let route = Route { paths: Vec::new(), route_params: None };
6113 assert_eq!(route.get_total_fees(), 0);
6114 assert_eq!(route.get_total_amount(), 0);
6118 fn limits_total_cltv_delta() {
6119 let (secp_ctx, network, _, _, logger) = build_graph();
6120 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6121 let network_graph = network.read_only();
6123 let scorer = ln_test_utils::TestScorer::new();
6125 // Make sure that generally there is at least one route available
6126 let feasible_max_total_cltv_delta = 1008;
6127 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6128 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6129 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6130 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6131 let route_params = RouteParameters::from_payment_params_and_value(
6132 feasible_payment_params, 100);
6133 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6134 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6135 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6136 assert_ne!(path.len(), 0);
6138 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6139 let fail_max_total_cltv_delta = 23;
6140 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6141 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6142 let route_params = RouteParameters::from_payment_params_and_value(
6143 fail_payment_params, 100);
6144 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6145 &Default::default(), &random_seed_bytes)
6147 Err(LightningError { err, .. } ) => {
6148 assert_eq!(err, "Failed to find a path to the given destination");
6150 Ok(_) => panic!("Expected error"),
6155 fn avoids_recently_failed_paths() {
6156 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6157 // randomly inserting channels into it until we can't find a route anymore.
6158 let (secp_ctx, network, _, _, logger) = build_graph();
6159 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6160 let network_graph = network.read_only();
6162 let scorer = ln_test_utils::TestScorer::new();
6163 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6164 .with_max_path_count(1);
6165 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6166 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6168 // We should be able to find a route initially, and then after we fail a few random
6169 // channels eventually we won't be able to any longer.
6170 let route_params = RouteParameters::from_payment_params_and_value(
6171 payment_params.clone(), 100);
6172 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6173 &scorer, &Default::default(), &random_seed_bytes).is_ok());
6175 let route_params = RouteParameters::from_payment_params_and_value(
6176 payment_params.clone(), 100);
6177 if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6178 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6180 for chan in route.paths[0].hops.iter() {
6181 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6183 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6184 % route.paths[0].hops.len();
6185 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6191 fn limits_path_length() {
6192 let (secp_ctx, network, _, _, logger) = build_line_graph();
6193 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6194 let network_graph = network.read_only();
6196 let scorer = ln_test_utils::TestScorer::new();
6197 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6198 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6200 // First check we can actually create a long route on this graph.
6201 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6202 let route_params = RouteParameters::from_payment_params_and_value(
6203 feasible_payment_params, 100);
6204 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6205 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6206 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6207 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6209 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6210 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6211 let route_params = RouteParameters::from_payment_params_and_value(
6212 fail_payment_params, 100);
6213 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6214 &Default::default(), &random_seed_bytes)
6216 Err(LightningError { err, .. } ) => {
6217 assert_eq!(err, "Failed to find a path to the given destination");
6219 Ok(_) => panic!("Expected error"),
6224 fn adds_and_limits_cltv_offset() {
6225 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6226 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6228 let scorer = ln_test_utils::TestScorer::new();
6230 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6231 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6232 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6233 let route_params = RouteParameters::from_payment_params_and_value(
6234 payment_params.clone(), 100);
6235 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6236 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6237 assert_eq!(route.paths.len(), 1);
6239 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6241 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6242 let mut route_default = route.clone();
6243 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6244 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6245 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6246 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6247 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6249 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6250 let mut route_limited = route.clone();
6251 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6252 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6253 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6254 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6255 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6259 fn adds_plausible_cltv_offset() {
6260 let (secp_ctx, network, _, _, logger) = build_graph();
6261 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6262 let network_graph = network.read_only();
6263 let network_nodes = network_graph.nodes();
6264 let network_channels = network_graph.channels();
6265 let scorer = ln_test_utils::TestScorer::new();
6266 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6267 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6268 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6270 let route_params = RouteParameters::from_payment_params_and_value(
6271 payment_params.clone(), 100);
6272 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6273 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6274 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6276 let mut path_plausibility = vec![];
6278 for p in route.paths {
6279 // 1. Select random observation point
6280 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6281 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6283 prng.process_in_place(&mut random_bytes);
6284 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6285 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6287 // 2. Calculate what CLTV expiry delta we would observe there
6288 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6290 // 3. Starting from the observation point, find candidate paths
6291 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6292 candidates.push_back((observation_point, vec![]));
6294 let mut found_plausible_candidate = false;
6296 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6297 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6298 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6299 found_plausible_candidate = true;
6300 break 'candidate_loop;
6304 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6305 for channel_id in &cur_node.channels {
6306 if let Some(channel_info) = network_channels.get(&channel_id) {
6307 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6308 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6309 if cur_path_cltv_deltas.iter().sum::<u32>()
6310 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6311 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6312 new_path_cltv_deltas.push(next_cltv_expiry_delta);
6313 candidates.push_back((*next_id, new_path_cltv_deltas));
6321 path_plausibility.push(found_plausible_candidate);
6323 assert!(path_plausibility.iter().all(|x| *x));
6327 fn builds_correct_path_from_hops() {
6328 let (secp_ctx, network, _, _, logger) = build_graph();
6329 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6330 let network_graph = network.read_only();
6332 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6333 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6335 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6336 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6337 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6338 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6339 Arc::clone(&logger), &random_seed_bytes).unwrap();
6340 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6341 assert_eq!(hops.len(), route.paths[0].hops.len());
6342 for (idx, hop_pubkey) in hops.iter().enumerate() {
6343 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6348 fn avoids_saturating_channels() {
6349 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6350 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6351 let decay_params = ProbabilisticScoringDecayParameters::default();
6352 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6354 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6355 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6356 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6357 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6358 short_channel_id: 4,
6361 cltv_expiry_delta: (4 << 4) | 1,
6362 htlc_minimum_msat: 0,
6363 htlc_maximum_msat: 250_000_000,
6365 fee_proportional_millionths: 0,
6366 excess_data: Vec::new()
6368 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6370 short_channel_id: 13,
6373 cltv_expiry_delta: (13 << 4) | 1,
6374 htlc_minimum_msat: 0,
6375 htlc_maximum_msat: 250_000_000,
6377 fee_proportional_millionths: 0,
6378 excess_data: Vec::new()
6381 let config = UserConfig::default();
6382 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6383 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6384 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6385 // 100,000 sats is less than the available liquidity on each channel, set above.
6386 let route_params = RouteParameters::from_payment_params_and_value(
6387 payment_params, 100_000_000);
6388 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6389 Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6390 assert_eq!(route.paths.len(), 2);
6391 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6392 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6395 #[cfg(not(feature = "no-std"))]
6396 pub(super) fn random_init_seed() -> u64 {
6397 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6398 use core::hash::{BuildHasher, Hasher};
6399 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6400 println!("Using seed of {}", seed);
6405 #[cfg(not(feature = "no-std"))]
6406 fn generate_routes() {
6407 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6409 let logger = ln_test_utils::TestLogger::new();
6410 let graph = match super::bench_utils::read_network_graph(&logger) {
6418 let params = ProbabilisticScoringFeeParameters::default();
6419 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6420 let features = super::Bolt11InvoiceFeatures::empty();
6422 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6426 #[cfg(not(feature = "no-std"))]
6427 fn generate_routes_mpp() {
6428 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6430 let logger = ln_test_utils::TestLogger::new();
6431 let graph = match super::bench_utils::read_network_graph(&logger) {
6439 let params = ProbabilisticScoringFeeParameters::default();
6440 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6441 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6443 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
6447 #[cfg(not(feature = "no-std"))]
6448 fn generate_large_mpp_routes() {
6449 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6451 let logger = ln_test_utils::TestLogger::new();
6452 let graph = match super::bench_utils::read_network_graph(&logger) {
6460 let params = ProbabilisticScoringFeeParameters::default();
6461 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6462 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6464 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
6468 fn honors_manual_penalties() {
6469 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6470 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6472 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6473 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6475 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6476 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6478 // First check set manual penalties are returned by the scorer.
6479 let usage = ChannelUsage {
6481 inflight_htlc_msat: 0,
6482 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6484 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6485 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6486 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6488 // Then check we can get a normal route
6489 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6490 let route_params = RouteParameters::from_payment_params_and_value(
6491 payment_params, 100);
6492 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6493 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6494 assert!(route.is_ok());
6496 // Then check that we can't get a route if we ban an intermediate node.
6497 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6498 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6499 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6500 assert!(route.is_err());
6502 // Finally make sure we can route again, when we remove the ban.
6503 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6504 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6505 Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6506 assert!(route.is_ok());
6510 fn abide_by_route_hint_max_htlc() {
6511 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6512 // params in the final route.
6513 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6514 let netgraph = network_graph.read_only();
6515 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6516 let scorer = ln_test_utils::TestScorer::new();
6517 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6518 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6519 let config = UserConfig::default();
6521 let max_htlc_msat = 50_000;
6522 let route_hint_1 = RouteHint(vec![RouteHintHop {
6523 src_node_id: nodes[2],
6524 short_channel_id: 42,
6527 proportional_millionths: 0,
6529 cltv_expiry_delta: 10,
6530 htlc_minimum_msat: None,
6531 htlc_maximum_msat: Some(max_htlc_msat),
6533 let dest_node_id = ln_test_utils::pubkey(42);
6534 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6535 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6536 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6538 // Make sure we'll error if our route hints don't have enough liquidity according to their
6539 // htlc_maximum_msat.
6540 let mut route_params = RouteParameters::from_payment_params_and_value(
6541 payment_params, max_htlc_msat + 1);
6542 route_params.max_total_routing_fee_msat = None;
6543 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6544 &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6547 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6548 } else { panic!(); }
6550 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6551 let mut route_hint_2 = route_hint_1.clone();
6552 route_hint_2.0[0].short_channel_id = 43;
6553 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6554 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6555 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6556 let mut route_params = RouteParameters::from_payment_params_and_value(
6557 payment_params, max_htlc_msat + 1);
6558 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
6559 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6560 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6561 assert_eq!(route.paths.len(), 2);
6562 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6563 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6567 fn direct_channel_to_hints_with_max_htlc() {
6568 // Check that if we have a first hop channel peer that's connected to multiple provided route
6569 // hints, that we properly split the payment between the route hints if needed.
6570 let logger = Arc::new(ln_test_utils::TestLogger::new());
6571 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6572 let scorer = ln_test_utils::TestScorer::new();
6573 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6574 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6575 let config = UserConfig::default();
6577 let our_node_id = ln_test_utils::pubkey(42);
6578 let intermed_node_id = ln_test_utils::pubkey(43);
6579 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6581 let amt_msat = 900_000;
6582 let max_htlc_msat = 500_000;
6583 let route_hint_1 = RouteHint(vec![RouteHintHop {
6584 src_node_id: intermed_node_id,
6585 short_channel_id: 44,
6588 proportional_millionths: 0,
6590 cltv_expiry_delta: 10,
6591 htlc_minimum_msat: None,
6592 htlc_maximum_msat: Some(max_htlc_msat),
6594 src_node_id: intermed_node_id,
6595 short_channel_id: 45,
6598 proportional_millionths: 0,
6600 cltv_expiry_delta: 10,
6601 htlc_minimum_msat: None,
6602 // Check that later route hint max htlcs don't override earlier ones
6603 htlc_maximum_msat: Some(max_htlc_msat - 50),
6605 let mut route_hint_2 = route_hint_1.clone();
6606 route_hint_2.0[0].short_channel_id = 46;
6607 route_hint_2.0[1].short_channel_id = 47;
6608 let dest_node_id = ln_test_utils::pubkey(44);
6609 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6610 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6611 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6613 let route_params = RouteParameters::from_payment_params_and_value(
6614 payment_params, amt_msat);
6615 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6616 Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6617 &Default::default(), &random_seed_bytes).unwrap();
6618 assert_eq!(route.paths.len(), 2);
6619 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6620 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6621 assert_eq!(route.get_total_amount(), amt_msat);
6623 // Re-run but with two first hop channels connected to the same route hint peers that must be
6625 let first_hops = vec![
6626 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6627 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6629 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6630 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6631 &Default::default(), &random_seed_bytes).unwrap();
6632 assert_eq!(route.paths.len(), 2);
6633 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6634 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6635 assert_eq!(route.get_total_amount(), amt_msat);
6637 // Make sure this works for blinded route hints.
6638 let blinded_path = BlindedPath {
6639 introduction_node_id: intermed_node_id,
6640 blinding_point: ln_test_utils::pubkey(42),
6642 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6643 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6646 let blinded_payinfo = BlindedPayInfo {
6648 fee_proportional_millionths: 0,
6649 htlc_minimum_msat: 1,
6650 htlc_maximum_msat: max_htlc_msat,
6651 cltv_expiry_delta: 10,
6652 features: BlindedHopFeatures::empty(),
6654 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6655 let payment_params = PaymentParameters::blinded(vec![
6656 (blinded_payinfo.clone(), blinded_path.clone()),
6657 (blinded_payinfo.clone(), blinded_path.clone())])
6658 .with_bolt12_features(bolt12_features).unwrap();
6659 let route_params = RouteParameters::from_payment_params_and_value(
6660 payment_params, amt_msat);
6661 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6662 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6663 &Default::default(), &random_seed_bytes).unwrap();
6664 assert_eq!(route.paths.len(), 2);
6665 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6666 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6667 assert_eq!(route.get_total_amount(), amt_msat);
6671 fn blinded_route_ser() {
6672 let blinded_path_1 = BlindedPath {
6673 introduction_node_id: ln_test_utils::pubkey(42),
6674 blinding_point: ln_test_utils::pubkey(43),
6676 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6677 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6680 let blinded_path_2 = BlindedPath {
6681 introduction_node_id: ln_test_utils::pubkey(46),
6682 blinding_point: ln_test_utils::pubkey(47),
6684 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6685 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6688 // (De)serialize a Route with 1 blinded path out of two total paths.
6689 let mut route = Route { paths: vec![Path {
6690 hops: vec![RouteHop {
6691 pubkey: ln_test_utils::pubkey(50),
6692 node_features: NodeFeatures::empty(),
6693 short_channel_id: 42,
6694 channel_features: ChannelFeatures::empty(),
6696 cltv_expiry_delta: 0,
6697 maybe_announced_channel: true,
6699 blinded_tail: Some(BlindedTail {
6700 hops: blinded_path_1.blinded_hops,
6701 blinding_point: blinded_path_1.blinding_point,
6702 excess_final_cltv_expiry_delta: 40,
6703 final_value_msat: 100,
6705 hops: vec![RouteHop {
6706 pubkey: ln_test_utils::pubkey(51),
6707 node_features: NodeFeatures::empty(),
6708 short_channel_id: 43,
6709 channel_features: ChannelFeatures::empty(),
6711 cltv_expiry_delta: 0,
6712 maybe_announced_channel: true,
6713 }], blinded_tail: None }],
6716 let encoded_route = route.encode();
6717 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6718 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6719 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6721 // (De)serialize a Route with two paths, each containing a blinded tail.
6722 route.paths[1].blinded_tail = Some(BlindedTail {
6723 hops: blinded_path_2.blinded_hops,
6724 blinding_point: blinded_path_2.blinding_point,
6725 excess_final_cltv_expiry_delta: 41,
6726 final_value_msat: 101,
6728 let encoded_route = route.encode();
6729 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6730 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6731 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6735 fn blinded_path_inflight_processing() {
6736 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6737 // account for the blinded tail's final amount_msat.
6738 let mut inflight_htlcs = InFlightHtlcs::new();
6739 let blinded_path = BlindedPath {
6740 introduction_node_id: ln_test_utils::pubkey(43),
6741 blinding_point: ln_test_utils::pubkey(48),
6742 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6745 hops: vec![RouteHop {
6746 pubkey: ln_test_utils::pubkey(42),
6747 node_features: NodeFeatures::empty(),
6748 short_channel_id: 42,
6749 channel_features: ChannelFeatures::empty(),
6751 cltv_expiry_delta: 0,
6752 maybe_announced_channel: false,
6755 pubkey: blinded_path.introduction_node_id,
6756 node_features: NodeFeatures::empty(),
6757 short_channel_id: 43,
6758 channel_features: ChannelFeatures::empty(),
6760 cltv_expiry_delta: 0,
6761 maybe_announced_channel: false,
6763 blinded_tail: Some(BlindedTail {
6764 hops: blinded_path.blinded_hops,
6765 blinding_point: blinded_path.blinding_point,
6766 excess_final_cltv_expiry_delta: 0,
6767 final_value_msat: 200,
6770 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6771 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6772 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6776 fn blinded_path_cltv_shadow_offset() {
6777 // Make sure we add a shadow offset when sending to blinded paths.
6778 let blinded_path = BlindedPath {
6779 introduction_node_id: ln_test_utils::pubkey(43),
6780 blinding_point: ln_test_utils::pubkey(44),
6782 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6783 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6786 let mut route = Route { paths: vec![Path {
6787 hops: vec![RouteHop {
6788 pubkey: ln_test_utils::pubkey(42),
6789 node_features: NodeFeatures::empty(),
6790 short_channel_id: 42,
6791 channel_features: ChannelFeatures::empty(),
6793 cltv_expiry_delta: 0,
6794 maybe_announced_channel: false,
6797 pubkey: blinded_path.introduction_node_id,
6798 node_features: NodeFeatures::empty(),
6799 short_channel_id: 43,
6800 channel_features: ChannelFeatures::empty(),
6802 cltv_expiry_delta: 0,
6803 maybe_announced_channel: false,
6806 blinded_tail: Some(BlindedTail {
6807 hops: blinded_path.blinded_hops,
6808 blinding_point: blinded_path.blinding_point,
6809 excess_final_cltv_expiry_delta: 0,
6810 final_value_msat: 200,
6812 }], route_params: None};
6814 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6815 let (_, network_graph, _, _, _) = build_line_graph();
6816 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6817 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6818 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6822 fn simple_blinded_route_hints() {
6823 do_simple_blinded_route_hints(1);
6824 do_simple_blinded_route_hints(2);
6825 do_simple_blinded_route_hints(3);
6828 fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6829 // Check that we can generate a route to a blinded path with the expected hops.
6830 let (secp_ctx, network, _, _, logger) = build_graph();
6831 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6832 let network_graph = network.read_only();
6834 let scorer = ln_test_utils::TestScorer::new();
6835 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6836 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6838 let mut blinded_path = BlindedPath {
6839 introduction_node_id: nodes[2],
6840 blinding_point: ln_test_utils::pubkey(42),
6841 blinded_hops: Vec::with_capacity(num_blinded_hops),
6843 for i in 0..num_blinded_hops {
6844 blinded_path.blinded_hops.push(
6845 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6848 let blinded_payinfo = BlindedPayInfo {
6850 fee_proportional_millionths: 500,
6851 htlc_minimum_msat: 1000,
6852 htlc_maximum_msat: 100_000_000,
6853 cltv_expiry_delta: 15,
6854 features: BlindedHopFeatures::empty(),
6857 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6858 let route_params = RouteParameters::from_payment_params_and_value(
6859 payment_params, 1001);
6860 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6861 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6862 assert_eq!(route.paths.len(), 1);
6863 assert_eq!(route.paths[0].hops.len(), 2);
6865 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6866 assert_eq!(tail.hops, blinded_path.blinded_hops);
6867 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6868 assert_eq!(tail.final_value_msat, 1001);
6870 let final_hop = route.paths[0].hops.last().unwrap();
6871 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6872 if tail.hops.len() > 1 {
6873 assert_eq!(final_hop.fee_msat,
6874 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6875 assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6877 assert_eq!(final_hop.fee_msat, 0);
6878 assert_eq!(final_hop.cltv_expiry_delta, 0);
6883 fn blinded_path_routing_errors() {
6884 // Check that we can generate a route to a blinded path with the expected hops.
6885 let (secp_ctx, network, _, _, logger) = build_graph();
6886 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6887 let network_graph = network.read_only();
6889 let scorer = ln_test_utils::TestScorer::new();
6890 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6891 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6893 let mut invalid_blinded_path = BlindedPath {
6894 introduction_node_id: nodes[2],
6895 blinding_point: ln_test_utils::pubkey(42),
6897 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6900 let blinded_payinfo = BlindedPayInfo {
6902 fee_proportional_millionths: 500,
6903 htlc_minimum_msat: 1000,
6904 htlc_maximum_msat: 100_000_000,
6905 cltv_expiry_delta: 15,
6906 features: BlindedHopFeatures::empty(),
6909 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6910 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6911 let payment_params = PaymentParameters::blinded(vec![
6912 (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6913 (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6914 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6915 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6916 &scorer, &Default::default(), &random_seed_bytes)
6918 Err(LightningError { err, .. }) => {
6919 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6921 _ => panic!("Expected error")
6924 invalid_blinded_path.introduction_node_id = our_id;
6925 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
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, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6933 _ => panic!("Expected error")
6936 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6937 invalid_blinded_path.blinded_hops.clear();
6938 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6939 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
6940 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6941 &Default::default(), &random_seed_bytes)
6943 Err(LightningError { err, .. }) => {
6944 assert_eq!(err, "0-hop blinded path provided");
6946 _ => panic!("Expected error")
6951 fn matching_intro_node_paths_provided() {
6952 // Check that if multiple blinded paths with the same intro node are provided in payment
6953 // parameters, we'll return the correct paths in the resulting MPP route.
6954 let (secp_ctx, network, _, _, logger) = build_graph();
6955 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6956 let network_graph = network.read_only();
6958 let scorer = ln_test_utils::TestScorer::new();
6959 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6960 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6961 let config = UserConfig::default();
6963 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6964 let blinded_path_1 = BlindedPath {
6965 introduction_node_id: nodes[2],
6966 blinding_point: ln_test_utils::pubkey(42),
6968 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6969 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6972 let blinded_payinfo_1 = BlindedPayInfo {
6974 fee_proportional_millionths: 0,
6975 htlc_minimum_msat: 0,
6976 htlc_maximum_msat: 30_000,
6977 cltv_expiry_delta: 0,
6978 features: BlindedHopFeatures::empty(),
6981 let mut blinded_path_2 = blinded_path_1.clone();
6982 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6983 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6984 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6986 let blinded_hints = vec![
6987 (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6988 (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6990 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6991 .with_bolt12_features(bolt12_features.clone()).unwrap();
6993 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
6994 route_params.max_total_routing_fee_msat = Some(100_000);
6995 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6996 &scorer, &Default::default(), &random_seed_bytes).unwrap();
6997 assert_eq!(route.paths.len(), 2);
6998 let mut total_amount_paid_msat = 0;
6999 for path in route.paths.into_iter() {
7000 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7001 if let Some(bt) = &path.blinded_tail {
7002 assert_eq!(bt.blinding_point,
7003 blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7004 .map(|(_, bp)| bp.blinding_point).unwrap());
7005 } else { panic!(); }
7006 total_amount_paid_msat += path.final_value_msat();
7008 assert_eq!(total_amount_paid_msat, 100_000);
7012 fn direct_to_intro_node() {
7013 // This previously caused a debug panic in the router when asserting
7014 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7015 // direct channels we failed to account for the fee charged for use of the blinded path.
7018 // node0 -1(1)2 - node1
7019 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7020 // doesn't account for the blinded path fee.
7022 let secp_ctx = Secp256k1::new();
7023 let logger = Arc::new(ln_test_utils::TestLogger::new());
7024 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7025 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7026 let scorer = ln_test_utils::TestScorer::new();
7027 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7028 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7030 let amt_msat = 10_000_000;
7031 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7032 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7033 ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7034 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7036 short_channel_id: 1,
7039 cltv_expiry_delta: 42,
7040 htlc_minimum_msat: 1_000,
7041 htlc_maximum_msat: 10_000_000,
7043 fee_proportional_millionths: 0,
7044 excess_data: Vec::new()
7046 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7048 short_channel_id: 1,
7051 cltv_expiry_delta: 42,
7052 htlc_minimum_msat: 1_000,
7053 htlc_maximum_msat: 10_000_000,
7055 fee_proportional_millionths: 0,
7056 excess_data: Vec::new()
7058 let first_hops = vec![
7059 get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7061 let blinded_path = BlindedPath {
7062 introduction_node_id: nodes[1],
7063 blinding_point: ln_test_utils::pubkey(42),
7065 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7066 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7069 let blinded_payinfo = BlindedPayInfo {
7070 fee_base_msat: 1000,
7071 fee_proportional_millionths: 0,
7072 htlc_minimum_msat: 1000,
7073 htlc_maximum_msat: MAX_VALUE_MSAT,
7074 cltv_expiry_delta: 0,
7075 features: BlindedHopFeatures::empty(),
7077 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7079 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7081 let netgraph = network_graph.read_only();
7082 let route_params = RouteParameters::from_payment_params_and_value(
7083 payment_params.clone(), amt_msat);
7084 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7085 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7086 &Default::default(), &random_seed_bytes) {
7087 assert_eq!(err, "Failed to find a path to the given destination");
7088 } else { panic!("Expected error") }
7090 // Sending an exact amount accounting for the blinded path fee works.
7091 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7092 let route_params = RouteParameters::from_payment_params_and_value(
7093 payment_params, amt_minus_blinded_path_fee);
7094 let route = get_route(&nodes[0], &route_params, &netgraph,
7095 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7096 &Default::default(), &random_seed_bytes).unwrap();
7097 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7098 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7102 fn direct_to_matching_intro_nodes() {
7103 // This previously caused us to enter `unreachable` code in the following situation:
7104 // 1. We add a route candidate for intro_node contributing a high amount
7105 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7106 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7107 // amount, and update our route candidate for intro_node for the lower amount
7108 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7109 // lower contribution amount, but fail (this was previously caused by failure to account for
7110 // blinded path fees when adding first_hop<>intro_node candidates)
7111 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7112 // candidate still thinks its path is contributing the original higher amount. This caused us
7113 // to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7115 let secp_ctx = Secp256k1::new();
7116 let logger = Arc::new(ln_test_utils::TestLogger::new());
7117 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7118 let scorer = ln_test_utils::TestScorer::new();
7119 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7120 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7121 let config = UserConfig::default();
7123 // Values are taken from the fuzz input that uncovered this panic.
7124 let amt_msat = 21_7020_5185_1403_2640;
7125 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7126 let first_hops = vec![
7127 get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7128 18446744073709551615)];
7130 let blinded_path = BlindedPath {
7131 introduction_node_id: nodes[1],
7132 blinding_point: ln_test_utils::pubkey(42),
7134 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7135 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7138 let blinded_payinfo = BlindedPayInfo {
7139 fee_base_msat: 5046_2720,
7140 fee_proportional_millionths: 0,
7141 htlc_minimum_msat: 4503_5996_2737_0496,
7142 htlc_maximum_msat: 45_0359_9627_3704_9600,
7143 cltv_expiry_delta: 0,
7144 features: BlindedHopFeatures::empty(),
7146 let mut blinded_hints = vec![
7147 (blinded_payinfo.clone(), blinded_path.clone()),
7148 (blinded_payinfo.clone(), blinded_path.clone()),
7150 blinded_hints[1].0.fee_base_msat = 419_4304;
7151 blinded_hints[1].0.fee_proportional_millionths = 257;
7152 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7153 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7154 blinded_hints[1].0.cltv_expiry_delta = 0;
7156 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7157 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7158 .with_bolt12_features(bolt12_features.clone()).unwrap();
7160 let netgraph = network_graph.read_only();
7161 let route_params = RouteParameters::from_payment_params_and_value(
7162 payment_params, amt_msat);
7163 let route = get_route(&nodes[0], &route_params, &netgraph,
7164 Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7165 &Default::default(), &random_seed_bytes).unwrap();
7166 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7167 assert_eq!(route.get_total_amount(), amt_msat);
7171 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
7172 pub(crate) mod bench_utils {
7176 use bitcoin::hashes::Hash;
7177 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7179 use crate::chain::transaction::OutPoint;
7180 use crate::routing::scoring::ScoreUpdate;
7181 use crate::sign::{EntropySource, KeysManager};
7182 use crate::ln::ChannelId;
7183 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
7184 use crate::ln::features::Bolt11InvoiceFeatures;
7185 use crate::routing::gossip::NetworkGraph;
7186 use crate::util::config::UserConfig;
7187 use crate::util::ser::ReadableArgs;
7188 use crate::util::test_utils::TestLogger;
7190 /// Tries to open a network graph file, or panics with a URL to fetch it.
7191 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
7192 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
7193 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
7194 .or_else(|_| { // Fall back to guessing based on the binary location
7195 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
7196 let mut path = std::env::current_exe().unwrap();
7197 path.pop(); // lightning-...
7199 path.pop(); // debug
7200 path.pop(); // target
7201 path.push("lightning");
7202 path.push("net_graph-2023-01-18.bin");
7205 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
7206 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
7207 let mut path = std::env::current_exe().unwrap();
7208 path.pop(); // bench...
7210 path.pop(); // debug
7211 path.pop(); // target
7212 path.pop(); // bench
7213 path.push("lightning");
7214 path.push("net_graph-2023-01-18.bin");
7217 .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");
7218 #[cfg(require_route_graph_test)]
7219 return Ok(res.unwrap());
7220 #[cfg(not(require_route_graph_test))]
7224 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
7225 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
7228 pub(crate) fn payer_pubkey() -> PublicKey {
7229 let secp_ctx = Secp256k1::new();
7230 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
7234 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
7236 channel_id: ChannelId::new_zero(),
7237 counterparty: ChannelCounterparty {
7238 features: channelmanager::provided_init_features(&UserConfig::default()),
7240 unspendable_punishment_reserve: 0,
7241 forwarding_info: None,
7242 outbound_htlc_minimum_msat: None,
7243 outbound_htlc_maximum_msat: None,
7245 funding_txo: Some(OutPoint {
7246 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
7249 short_channel_id: Some(1),
7250 inbound_scid_alias: None,
7251 outbound_scid_alias: None,
7252 channel_value_satoshis: 10_000_000_000,
7254 outbound_capacity_msat: 10_000_000_000,
7255 next_outbound_htlc_minimum_msat: 0,
7256 next_outbound_htlc_limit_msat: 10_000_000_000,
7257 inbound_capacity_msat: 0,
7258 unspendable_punishment_reserve: None,
7259 confirmations_required: None,
7260 confirmations: None,
7261 force_close_spend_delay: None,
7263 is_channel_ready: true,
7266 inbound_htlc_minimum_msat: None,
7267 inbound_htlc_maximum_msat: None,
7269 feerate_sat_per_1000_weight: None,
7270 channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
7274 pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
7275 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
7276 starting_amount: u64, route_count: usize,
7277 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
7278 let payer = payer_pubkey();
7279 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7280 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7282 let nodes = graph.read_only().nodes().clone();
7283 let mut route_endpoints = Vec::new();
7284 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
7285 // with some routes we picked being un-routable.
7286 for _ in 0..route_count * 3 / 2 {
7288 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7289 let src = PublicKey::from_slice(nodes.unordered_keys()
7290 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7291 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7292 let dst = PublicKey::from_slice(nodes.unordered_keys()
7293 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7294 let params = PaymentParameters::from_node_id(dst, 42)
7295 .with_bolt11_features(features.clone()).unwrap();
7296 let first_hop = first_hop(src);
7297 let amt_msat = starting_amount + seed % 1_000_000;
7298 let route_params = RouteParameters::from_payment_params_and_value(
7299 params.clone(), amt_msat);
7301 get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
7302 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
7304 // ...and seed the scorer with success and failure data...
7305 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7306 let mut score_amt = seed % 1_000_000_000;
7308 // Generate fail/success paths for a wider range of potential amounts with
7309 // MPP enabled to give us a chance to apply penalties for more potential
7311 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7312 let params = PaymentParameters::from_node_id(dst, 42)
7313 .with_bolt11_features(mpp_features).unwrap();
7314 let route_params = RouteParameters::from_payment_params_and_value(
7315 params.clone(), score_amt);
7316 let route_res = get_route(&payer, &route_params, &graph.read_only(),
7317 Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
7318 &random_seed_bytes);
7319 if let Ok(route) = route_res {
7320 for path in route.paths {
7321 if seed & 0x80 == 0 {
7322 scorer.payment_path_successful(&path);
7324 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7325 scorer.payment_path_failed(&path, short_channel_id);
7327 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7331 // If we couldn't find a path with a higer amount, reduce and try again.
7335 route_endpoints.push((first_hop, params, amt_msat));
7341 // Because we've changed channel scores, it's possible we'll take different routes to the
7342 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7343 // requires a too-high CLTV delta.
7344 route_endpoints.retain(|(first_hop, params, amt_msat)| {
7345 let route_params = RouteParameters::from_payment_params_and_value(
7346 params.clone(), *amt_msat);
7347 get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7348 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7350 route_endpoints.truncate(route_count);
7351 assert_eq!(route_endpoints.len(), route_count);
7359 use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7360 use crate::sign::{EntropySource, KeysManager};
7361 use crate::ln::channelmanager;
7362 use crate::ln::features::Bolt11InvoiceFeatures;
7363 use crate::routing::gossip::NetworkGraph;
7364 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7365 use crate::util::config::UserConfig;
7366 use crate::util::logger::{Logger, Record};
7367 use crate::util::test_utils::TestLogger;
7369 use criterion::Criterion;
7371 struct DummyLogger {}
7372 impl Logger for DummyLogger {
7373 fn log(&self, _record: &Record) {}
7376 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7377 let logger = TestLogger::new();
7378 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7379 let scorer = FixedPenaltyScorer::with_penalty(0);
7380 generate_routes(bench, &network_graph, scorer, &Default::default(),
7381 Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
7384 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7385 let logger = TestLogger::new();
7386 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7387 let scorer = FixedPenaltyScorer::with_penalty(0);
7388 generate_routes(bench, &network_graph, scorer, &Default::default(),
7389 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7390 "generate_mpp_routes_with_zero_penalty_scorer");
7393 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7394 let logger = TestLogger::new();
7395 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7396 let params = ProbabilisticScoringFeeParameters::default();
7397 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7398 generate_routes(bench, &network_graph, scorer, ¶ms, Bolt11InvoiceFeatures::empty(), 0,
7399 "generate_routes_with_probabilistic_scorer");
7402 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7403 let logger = TestLogger::new();
7404 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7405 let params = ProbabilisticScoringFeeParameters::default();
7406 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7407 generate_routes(bench, &network_graph, scorer, ¶ms,
7408 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7409 "generate_mpp_routes_with_probabilistic_scorer");
7412 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7413 let logger = TestLogger::new();
7414 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7415 let params = ProbabilisticScoringFeeParameters::default();
7416 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7417 generate_routes(bench, &network_graph, scorer, ¶ms,
7418 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7419 "generate_large_mpp_routes_with_probabilistic_scorer");
7422 pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7423 let logger = TestLogger::new();
7424 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7425 let mut params = ProbabilisticScoringFeeParameters::default();
7426 params.linear_success_probability = false;
7427 let scorer = ProbabilisticScorer::new(
7428 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7429 generate_routes(bench, &network_graph, scorer, ¶ms,
7430 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7431 "generate_routes_with_nonlinear_probabilistic_scorer");
7434 pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7435 let logger = TestLogger::new();
7436 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7437 let mut params = ProbabilisticScoringFeeParameters::default();
7438 params.linear_success_probability = false;
7439 let scorer = ProbabilisticScorer::new(
7440 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7441 generate_routes(bench, &network_graph, scorer, ¶ms,
7442 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7443 "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
7446 pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7447 let logger = TestLogger::new();
7448 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7449 let mut params = ProbabilisticScoringFeeParameters::default();
7450 params.linear_success_probability = false;
7451 let scorer = ProbabilisticScorer::new(
7452 ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7453 generate_routes(bench, &network_graph, scorer, ¶ms,
7454 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7455 "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
7458 fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7459 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7460 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7461 bench_name: &'static str,
7463 let payer = bench_utils::payer_pubkey();
7464 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7465 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7467 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7468 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7470 // ...then benchmark finding paths between the nodes we learned.
7472 bench.bench_function(bench_name, |b| b.iter(|| {
7473 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7474 let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
7475 assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7476 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());