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::{Bolt12InvoiceFeatures, ChannelFeatures, InvoiceFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Invoice as Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
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, MutexGuard};
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: Score<ScoreParams = SP>> where
38 S::Target: for <'a> LockableScore<'a, Locked = MutexGuard<'a, Sc>>,
42 random_seed_bytes: Mutex<[u8; 32]>,
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
49 S::Target: for <'a> LockableScore<'a, Locked = MutexGuard<'a, 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: Score<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
60 S::Target: for <'a> LockableScore<'a, Locked = MutexGuard<'a, 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.lock(), inflight_htlcs),
83 /// A trait defining behavior for routing a payment.
85 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
87 &self, payer: &PublicKey, route_params: &RouteParameters,
88 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
89 ) -> Result<Route, LightningError>;
90 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
91 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
92 fn find_route_with_id(
93 &self, payer: &PublicKey, route_params: &RouteParameters,
94 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
95 _payment_hash: PaymentHash, _payment_id: PaymentId
96 ) -> Result<Route, LightningError> {
97 self.find_route(payer, route_params, first_hops, inflight_htlcs)
101 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
103 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
106 /// [`Score`]: crate::routing::scoring::Score
107 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score> {
109 // Maps a channel's short channel id and its direction to the liquidity used up.
110 inflight_htlcs: &'a InFlightHtlcs,
113 impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> {
114 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
115 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
116 ScorerAccountingForInFlightHtlcs {
124 impl<'a, S: Score> Writeable for ScorerAccountingForInFlightHtlcs<'a, S> {
125 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
128 impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> {
129 type ScoreParams = S::ScoreParams;
130 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
131 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
132 source, target, short_channel_id
134 let usage = ChannelUsage {
135 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
139 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
141 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
145 fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64) {
146 self.scorer.payment_path_failed(path, short_channel_id)
149 fn payment_path_successful(&mut self, path: &Path) {
150 self.scorer.payment_path_successful(path)
153 fn probe_failed(&mut self, path: &Path, short_channel_id: u64) {
154 self.scorer.probe_failed(path, short_channel_id)
157 fn probe_successful(&mut self, path: &Path) {
158 self.scorer.probe_successful(path)
162 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
163 /// in-use channel liquidity.
165 pub struct InFlightHtlcs(
166 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
167 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
168 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
170 HashMap<(u64, bool), u64>
174 /// Constructs an empty `InFlightHtlcs`.
175 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
177 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
178 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
179 if path.hops.is_empty() { return };
181 let mut cumulative_msat = 0;
182 if let Some(tail) = &path.blinded_tail {
183 cumulative_msat += tail.final_value_msat;
186 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
187 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
188 // the router excludes the payer node. In the following lines, the payer's information is
189 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
190 // in our sliding window of two.
191 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
192 .map(|hop| hop.pubkey)
193 .chain(core::iter::once(payer_node_id));
195 // Taking the reversed vector from above, we zip it with just the reversed hops list to
196 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
197 // the total amount sent.
198 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
199 cumulative_msat += next_hop.fee_msat;
201 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
202 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
203 .or_insert(cumulative_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,
255 impl_writeable_tlv_based!(RouteHop, {
256 (0, pubkey, required),
257 (2, node_features, required),
258 (4, short_channel_id, required),
259 (6, channel_features, required),
260 (8, fee_msat, required),
261 (10, cltv_expiry_delta, required),
264 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
265 /// their BOLT12 [`Invoice`].
267 /// [`Invoice`]: crate::offers::invoice::Invoice
268 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
269 pub struct BlindedTail {
270 /// The hops of the [`BlindedPath`] provided by the recipient.
272 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
273 pub hops: Vec<BlindedHop>,
274 /// The blinding point of the [`BlindedPath`] provided by the recipient.
276 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
277 pub blinding_point: PublicKey,
278 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
279 /// inferring the destination. May be 0.
280 pub excess_final_cltv_expiry_delta: u32,
281 /// The total amount paid on this [`Path`], excluding the fees.
282 pub final_value_msat: u64,
285 impl_writeable_tlv_based!(BlindedTail, {
287 (2, blinding_point, required),
288 (4, excess_final_cltv_expiry_delta, required),
289 (6, final_value_msat, required),
292 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
293 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
294 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
296 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
297 pub hops: Vec<RouteHop>,
298 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
299 pub blinded_tail: Option<BlindedTail>,
303 /// Gets the fees for a given path, excluding any excess paid to the recipient.
304 pub fn fee_msat(&self) -> u64 {
305 match &self.blinded_tail {
306 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
308 // Do not count last hop of each path since that's the full value of the payment
309 self.hops.split_last().map_or(0,
310 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
315 /// Gets the total amount paid on this [`Path`], excluding the fees.
316 pub fn final_value_msat(&self) -> u64 {
317 match &self.blinded_tail {
318 Some(blinded_tail) => blinded_tail.final_value_msat,
319 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
323 /// Gets the final hop's CLTV expiry delta.
324 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
325 match &self.blinded_tail {
327 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
332 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
333 /// it can take multiple paths. Each path is composed of one or more hops through the network.
334 #[derive(Clone, Hash, PartialEq, Eq)]
336 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
337 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
339 pub paths: Vec<Path>,
340 /// The `payment_params` parameter passed to [`find_route`].
341 /// This is used by `ChannelManager` to track information which may be required for retries,
342 /// provided back to you via [`Event::PaymentPathFailed`].
344 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
345 pub payment_params: Option<PaymentParameters>,
349 /// Returns the total amount of fees paid on this [`Route`].
351 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
352 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
353 pub fn get_total_fees(&self) -> u64 {
354 self.paths.iter().map(|path| path.fee_msat()).sum()
357 /// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
358 /// requested if we had to reach htlc_minimum_msat.
359 pub fn get_total_amount(&self) -> u64 {
360 self.paths.iter().map(|path| path.final_value_msat()).sum()
364 const SERIALIZATION_VERSION: u8 = 1;
365 const MIN_SERIALIZATION_VERSION: u8 = 1;
367 impl Writeable for Route {
368 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
369 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
370 (self.paths.len() as u64).write(writer)?;
371 let mut blinded_tails = Vec::new();
372 for path in self.paths.iter() {
373 (path.hops.len() as u8).write(writer)?;
374 for (idx, hop) in path.hops.iter().enumerate() {
376 if let Some(blinded_tail) = &path.blinded_tail {
377 if blinded_tails.is_empty() {
378 blinded_tails = Vec::with_capacity(path.hops.len());
380 blinded_tails.push(None);
383 blinded_tails.push(Some(blinded_tail));
384 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
387 write_tlv_fields!(writer, {
388 (1, self.payment_params, option),
389 (2, blinded_tails, optional_vec),
395 impl Readable for Route {
396 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
397 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
398 let path_count: u64 = Readable::read(reader)?;
399 if path_count == 0 { return Err(DecodeError::InvalidValue); }
400 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
401 let mut min_final_cltv_expiry_delta = u32::max_value();
402 for _ in 0..path_count {
403 let hop_count: u8 = Readable::read(reader)?;
404 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
405 for _ in 0..hop_count {
406 hops.push(Readable::read(reader)?);
408 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
409 min_final_cltv_expiry_delta =
410 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
411 paths.push(Path { hops, blinded_tail: None });
413 _init_and_read_tlv_fields!(reader, {
414 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
415 (2, blinded_tails, optional_vec),
417 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
418 if blinded_tails.len() != 0 {
419 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
420 for (mut path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
421 path.blinded_tail = blinded_tail_opt;
424 Ok(Route { paths, payment_params })
428 /// Parameters needed to find a [`Route`].
430 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
431 /// [`Event::PaymentPathFailed`].
433 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
434 #[derive(Clone, Debug, PartialEq, Eq)]
435 pub struct RouteParameters {
436 /// The parameters of the failed payment path.
437 pub payment_params: PaymentParameters,
439 /// The amount in msats sent on the failed payment path.
440 pub final_value_msat: u64,
443 impl Writeable for RouteParameters {
444 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
445 write_tlv_fields!(writer, {
446 (0, self.payment_params, required),
447 (2, self.final_value_msat, required),
448 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
449 // `RouteParameters` directly. For compatibility, we write it here.
450 (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
456 impl Readable for RouteParameters {
457 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
458 _init_and_read_tlv_fields!(reader, {
459 (0, payment_params, (required: ReadableArgs, 0)),
460 (2, final_value_msat, required),
461 (4, final_cltv_delta, option),
463 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
464 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
465 if final_cltv_expiry_delta == &0 {
466 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
471 final_value_msat: final_value_msat.0.unwrap(),
476 /// Maximum total CTLV difference we allow for a full payment path.
477 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
479 /// Maximum number of paths we allow an (MPP) payment to have.
480 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
481 // limits, but for now more than 10 paths likely carries too much one-path failure.
482 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
484 // The median hop CLTV expiry delta currently seen in the network.
485 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
487 // During routing, we only consider paths shorter than our maximum length estimate.
488 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
489 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
490 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
492 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
493 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
494 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
495 // (payment_secret and total_msat) = 93 bytes for the final hop.
496 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
497 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
498 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
500 /// Information used to route a payment.
501 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
502 pub struct PaymentParameters {
503 /// Information about the payee, such as their features and route hints for their channels.
506 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
507 pub expiry_time: Option<u64>,
509 /// The maximum total CLTV delta we accept for the route.
510 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
511 pub max_total_cltv_expiry_delta: u32,
513 /// The maximum number of paths that may be used by (MPP) payments.
514 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
515 pub max_path_count: u8,
517 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
518 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
519 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
520 /// increasing failure probability for those paths.
522 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
523 /// restriction have been found. While paths which meet this criteria will be searched for, it
524 /// is ultimately up to the scorer to select them over other paths.
526 /// A value of 0 will allow payments up to and including a channel's total announced usable
527 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
530 pub max_channel_saturation_power_of_half: u8,
532 /// A list of SCIDs which this payment was previously attempted over and which caused the
533 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
535 pub previously_failed_channels: Vec<u64>,
538 impl Writeable for PaymentParameters {
539 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
540 let mut clear_hints = &vec![];
541 let mut blinded_hints = &vec![];
543 Payee::Clear { route_hints, .. } => clear_hints = route_hints,
544 Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
546 write_tlv_fields!(writer, {
547 (0, self.payee.node_id(), option),
548 (1, self.max_total_cltv_expiry_delta, required),
549 (2, self.payee.features(), option),
550 (3, self.max_path_count, required),
551 (4, *clear_hints, vec_type),
552 (5, self.max_channel_saturation_power_of_half, required),
553 (6, self.expiry_time, option),
554 (7, self.previously_failed_channels, vec_type),
555 (8, *blinded_hints, optional_vec),
556 (9, self.payee.final_cltv_expiry_delta(), option),
562 impl ReadableArgs<u32> for PaymentParameters {
563 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
564 _init_and_read_tlv_fields!(reader, {
565 (0, payee_pubkey, option),
566 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
567 (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
568 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
569 (4, route_hints, vec_type),
570 (5, max_channel_saturation_power_of_half, (default_value, 2)),
571 (6, expiry_time, option),
572 (7, previously_failed_channels, vec_type),
573 (8, blinded_route_hints, optional_vec),
574 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
576 let clear_route_hints = route_hints.unwrap_or(vec![]);
577 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
578 let payee = if blinded_route_hints.len() != 0 {
579 if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
581 route_hints: blinded_route_hints,
582 features: features.and_then(|f: Features| f.bolt12()),
586 route_hints: clear_route_hints,
587 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
588 features: features.and_then(|f| f.bolt11()),
589 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
593 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
594 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
596 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
598 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
604 impl PaymentParameters {
605 /// Creates a payee with the node id of the given `pubkey`.
607 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
609 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
611 payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
613 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
614 max_path_count: DEFAULT_MAX_PATH_COUNT,
615 max_channel_saturation_power_of_half: 2,
616 previously_failed_channels: Vec::new(),
620 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
622 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
625 /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
626 /// whether your router will be allowed to find a multi-part route for this payment. If you
627 /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
628 /// [`RecipientOnionFields::secret_only`].
630 /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
631 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
632 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
633 .with_bolt11_features(InvoiceFeatures::for_keysend(allow_mpp))
634 .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
637 /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
638 /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
639 /// [`PaymentParameters::expiry_time`].
640 pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
641 Self::blinded(invoice.payment_paths().to_vec())
642 .with_bolt12_features(invoice.features().clone()).unwrap()
643 .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
646 fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
648 payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
650 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
651 max_path_count: DEFAULT_MAX_PATH_COUNT,
652 max_channel_saturation_power_of_half: 2,
653 previously_failed_channels: Vec::new(),
657 /// Includes the payee's features. Errors if the parameters were not initialized with
658 /// [`PaymentParameters::from_bolt12_invoice`].
660 /// This is not exported to bindings users since bindings don't support move semantics
661 pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
663 Payee::Clear { .. } => Err(()),
664 Payee::Blinded { route_hints, .. } =>
665 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
669 /// Includes the payee's features. Errors if the parameters were initialized with
670 /// [`PaymentParameters::from_bolt12_invoice`].
672 /// This is not exported to bindings users since bindings don't support move semantics
673 pub fn with_bolt11_features(self, features: InvoiceFeatures) -> Result<Self, ()> {
675 Payee::Blinded { .. } => Err(()),
676 Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
678 payee: Payee::Clear {
679 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
685 /// Includes hints for routing to the payee. Errors if the parameters were initialized with
686 /// [`PaymentParameters::from_bolt12_invoice`].
688 /// This is not exported to bindings users since bindings don't support move semantics
689 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
691 Payee::Blinded { .. } => Err(()),
692 Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
694 payee: Payee::Clear {
695 route_hints, node_id, features, final_cltv_expiry_delta,
701 /// Includes a payment expiration in seconds relative to the UNIX epoch.
703 /// This is not exported to bindings users since bindings don't support move semantics
704 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
705 Self { expiry_time: Some(expiry_time), ..self }
708 /// Includes a limit for the total CLTV expiry delta which is considered during routing
710 /// This is not exported to bindings users since bindings don't support move semantics
711 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
712 Self { max_total_cltv_expiry_delta, ..self }
715 /// Includes a limit for the maximum number of payment paths that may be used.
717 /// This is not exported to bindings users since bindings don't support move semantics
718 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
719 Self { max_path_count, ..self }
722 /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
723 /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
725 /// This is not exported to bindings users since bindings don't support move semantics
726 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
727 Self { max_channel_saturation_power_of_half, ..self }
731 /// The recipient of a payment, differing based on whether they've hidden their identity with route
733 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
735 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
736 /// will be included in the final [`Route`].
738 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
740 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
741 /// Features supported by the payee.
743 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
745 features: Option<Bolt12InvoiceFeatures>,
747 /// The recipient included these route hints in their BOLT11 invoice.
749 /// The node id of the payee.
751 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
752 route_hints: Vec<RouteHint>,
753 /// Features supported by the payee.
755 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
756 /// does not contain any features.
758 /// [`for_keysend`]: PaymentParameters::for_keysend
759 features: Option<InvoiceFeatures>,
760 /// The minimum CLTV delta at the end of the route. This value must not be zero.
761 final_cltv_expiry_delta: u32,
766 fn node_id(&self) -> Option<PublicKey> {
768 Self::Clear { node_id, .. } => Some(*node_id),
772 fn node_features(&self) -> Option<NodeFeatures> {
774 Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
775 Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
778 fn supports_basic_mpp(&self) -> bool {
780 Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
781 Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
784 fn features(&self) -> Option<FeaturesRef> {
786 Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
787 Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
790 fn final_cltv_expiry_delta(&self) -> Option<u32> {
792 Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
798 enum FeaturesRef<'a> {
799 Bolt11(&'a InvoiceFeatures),
800 Bolt12(&'a Bolt12InvoiceFeatures),
803 Bolt11(InvoiceFeatures),
804 Bolt12(Bolt12InvoiceFeatures),
808 fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
810 Self::Bolt12(f) => Some(f),
814 fn bolt11(self) -> Option<InvoiceFeatures> {
816 Self::Bolt11(f) => Some(f),
822 impl<'a> Writeable for FeaturesRef<'a> {
823 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
825 Self::Bolt11(f) => Ok(f.write(w)?),
826 Self::Bolt12(f) => Ok(f.write(w)?),
831 impl ReadableArgs<bool> for Features {
832 fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
833 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
834 Ok(Self::Bolt12(Readable::read(reader)?))
838 /// A list of hops along a payment path terminating with a channel to the recipient.
839 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
840 pub struct RouteHint(pub Vec<RouteHintHop>);
842 impl Writeable for RouteHint {
843 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
844 (self.0.len() as u64).write(writer)?;
845 for hop in self.0.iter() {
852 impl Readable for RouteHint {
853 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
854 let hop_count: u64 = Readable::read(reader)?;
855 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
856 for _ in 0..hop_count {
857 hops.push(Readable::read(reader)?);
863 /// A channel descriptor for a hop along a payment path.
864 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
865 pub struct RouteHintHop {
866 /// The node_id of the non-target end of the route
867 pub src_node_id: PublicKey,
868 /// The short_channel_id of this channel
869 pub short_channel_id: u64,
870 /// The fees which must be paid to use this channel
871 pub fees: RoutingFees,
872 /// The difference in CLTV values between this node and the next node.
873 pub cltv_expiry_delta: u16,
874 /// The minimum value, in msat, which must be relayed to the next hop.
875 pub htlc_minimum_msat: Option<u64>,
876 /// The maximum value in msat available for routing with a single HTLC.
877 pub htlc_maximum_msat: Option<u64>,
880 impl_writeable_tlv_based!(RouteHintHop, {
881 (0, src_node_id, required),
882 (1, htlc_minimum_msat, option),
883 (2, short_channel_id, required),
884 (3, htlc_maximum_msat, option),
886 (6, cltv_expiry_delta, required),
889 #[derive(Eq, PartialEq)]
890 struct RouteGraphNode {
892 lowest_fee_to_node: u64,
893 total_cltv_delta: u32,
894 // The maximum value a yet-to-be-constructed payment path might flow through this node.
895 // This value is upper-bounded by us by:
896 // - how much is needed for a path being constructed
897 // - how much value can channels following this node (up to the destination) can contribute,
898 // considering their capacity and fees
899 value_contribution_msat: u64,
900 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
901 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
902 path_htlc_minimum_msat: u64,
903 /// All penalties incurred from this hop on the way to the destination, as calculated using
905 path_penalty_msat: u64,
906 /// The number of hops walked up to this node.
907 path_length_to_node: u8,
910 impl cmp::Ord for RouteGraphNode {
911 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
912 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
913 .saturating_add(other.path_penalty_msat);
914 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
915 .saturating_add(self.path_penalty_msat);
916 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
920 impl cmp::PartialOrd for RouteGraphNode {
921 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
922 Some(self.cmp(other))
926 /// A wrapper around the various hop representations.
928 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
929 #[derive(Clone, Debug)]
930 enum CandidateRouteHop<'a> {
931 /// A hop from the payer, where the outbound liquidity is known.
933 details: &'a ChannelDetails,
935 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
937 info: DirectedChannelInfo<'a>,
938 short_channel_id: u64,
940 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
942 hint: &'a RouteHintHop,
946 impl<'a> CandidateRouteHop<'a> {
947 fn short_channel_id(&self) -> u64 {
949 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
950 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
951 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
955 // NOTE: This may alloc memory so avoid calling it in a hot code path.
956 fn features(&self) -> ChannelFeatures {
958 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
959 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
960 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
964 fn cltv_expiry_delta(&self) -> u32 {
966 CandidateRouteHop::FirstHop { .. } => 0,
967 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
968 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
972 fn htlc_minimum_msat(&self) -> u64 {
974 CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
975 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
976 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
980 fn fees(&self) -> RoutingFees {
982 CandidateRouteHop::FirstHop { .. } => RoutingFees {
983 base_msat: 0, proportional_millionths: 0,
985 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
986 CandidateRouteHop::PrivateHop { hint } => hint.fees,
990 fn effective_capacity(&self) -> EffectiveCapacity {
992 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
993 liquidity_msat: details.next_outbound_htlc_limit_msat,
995 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
996 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
997 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
998 CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
999 EffectiveCapacity::Infinite,
1005 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1006 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1008 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1009 EffectiveCapacity::Infinite => u64::max_value(),
1010 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1011 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1012 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1013 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1014 // expected to have been generated from up-to-date capacity information.
1015 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1016 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1017 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1021 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1022 -> bool where I1::Item: PartialEq<I2::Item> {
1024 let a = iter_a.next();
1025 let b = iter_b.next();
1026 if a.is_none() && b.is_none() { return true; }
1027 if a.is_none() || b.is_none() { return false; }
1028 if a.unwrap().ne(&b.unwrap()) { return false; }
1032 /// It's useful to keep track of the hops associated with the fees required to use them,
1033 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1034 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1035 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1037 struct PathBuildingHop<'a> {
1038 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1039 // is a larger refactor and will require careful performance analysis.
1041 candidate: CandidateRouteHop<'a>,
1044 /// All the fees paid *after* this channel on the way to the destination
1045 next_hops_fee_msat: u64,
1046 /// Fee paid for the use of the current channel (see candidate.fees()).
1047 /// The value will be actually deducted from the counterparty balance on the previous link.
1048 hop_use_fee_msat: u64,
1049 /// Used to compare channels when choosing the for routing.
1050 /// Includes paying for the use of a hop and the following hops, as well as
1051 /// an estimated cost of reaching this hop.
1052 /// Might get stale when fees are recomputed. Primarily for internal use.
1053 total_fee_msat: u64,
1054 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1055 /// walk and may be invalid thereafter.
1056 path_htlc_minimum_msat: u64,
1057 /// All penalties incurred from this channel on the way to the destination, as calculated using
1058 /// channel scoring.
1059 path_penalty_msat: u64,
1060 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1061 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1062 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1063 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1064 /// avoid processing them again.
1065 was_processed: bool,
1066 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1067 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1068 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1069 // value_contribution_msat, which requires tracking it here. See comments below where it is
1070 // used for more info.
1071 value_contribution_msat: u64,
1074 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1075 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1076 let mut debug_struct = f.debug_struct("PathBuildingHop");
1078 .field("node_id", &self.node_id)
1079 .field("short_channel_id", &self.candidate.short_channel_id())
1080 .field("total_fee_msat", &self.total_fee_msat)
1081 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1082 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1083 .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)))
1084 .field("path_penalty_msat", &self.path_penalty_msat)
1085 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1086 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1087 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1088 let debug_struct = debug_struct
1089 .field("value_contribution_msat", &self.value_contribution_msat);
1090 debug_struct.finish()
1094 // Instantiated with a list of hops with correct data in them collected during path finding,
1095 // an instance of this struct should be further modified only via given methods.
1097 struct PaymentPath<'a> {
1098 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1101 impl<'a> PaymentPath<'a> {
1102 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1103 fn get_value_msat(&self) -> u64 {
1104 self.hops.last().unwrap().0.fee_msat
1107 fn get_path_penalty_msat(&self) -> u64 {
1108 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1111 fn get_total_fee_paid_msat(&self) -> u64 {
1112 if self.hops.len() < 1 {
1116 // Can't use next_hops_fee_msat because it gets outdated.
1117 for (i, (hop, _)) in self.hops.iter().enumerate() {
1118 if i != self.hops.len() - 1 {
1119 result += hop.fee_msat;
1125 fn get_cost_msat(&self) -> u64 {
1126 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1129 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1130 // to change fees may result in an inconsistency.
1132 // Sometimes we call this function right after constructing a path which is inconsistent in
1133 // that it the value being transferred has decreased while we were doing path finding, leading
1134 // to the fees being paid not lining up with the actual limits.
1136 // Note that this function is not aware of the available_liquidity limit, and thus does not
1137 // support increasing the value being transferred beyond what was selected during the initial
1139 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1140 let mut total_fee_paid_msat = 0 as u64;
1141 for i in (0..self.hops.len()).rev() {
1142 let last_hop = i == self.hops.len() - 1;
1144 // For non-last-hop, this value will represent the fees paid on the current hop. It
1145 // will consist of the fees for the use of the next hop, and extra fees to match
1146 // htlc_minimum_msat of the current channel. Last hop is handled separately.
1147 let mut cur_hop_fees_msat = 0;
1149 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1152 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1153 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1154 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1155 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1156 // set it too high just to maliciously take more fees by exploiting this
1157 // match htlc_minimum_msat logic.
1158 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1159 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1160 // Note that there is a risk that *previous hops* (those closer to us, as we go
1161 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1163 // This might make us end up with a broken route, although this should be super-rare
1164 // in practice, both because of how healthy channels look like, and how we pick
1165 // channels in add_entry.
1166 // Also, this can't be exploited more heavily than *announce a free path and fail
1168 cur_hop_transferred_amount_msat += extra_fees_msat;
1169 total_fee_paid_msat += extra_fees_msat;
1170 cur_hop_fees_msat += extra_fees_msat;
1174 // Final hop is a special case: it usually has just value_msat (by design), but also
1175 // it still could overpay for the htlc_minimum_msat.
1176 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1178 // Propagate updated fees for the use of the channels to one hop back, where they
1179 // will be actually paid (fee_msat). The last hop is handled above separately.
1180 cur_hop.fee_msat = cur_hop_fees_msat;
1183 // Fee for the use of the current hop which will be deducted on the previous hop.
1184 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1185 // this channel is free for us.
1187 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1188 cur_hop.hop_use_fee_msat = new_fee;
1189 total_fee_paid_msat += new_fee;
1191 // It should not be possible because this function is called only to reduce the
1192 // value. In that case, compute_fee was already called with the same fees for
1193 // larger amount and there was no overflow.
1202 /// Calculate the fees required to route the given amount over a channel with the given fees.
1203 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1204 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1205 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1209 /// Calculate the fees required to route the given amount over a channel with the given fees,
1210 /// saturating to [`u64::max_value`].
1211 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1212 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1213 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1214 .saturating_add(channel_fees.base_msat as u64)
1217 /// The default `features` we assume for a node in a route, when no `features` are known about that
1220 /// Default features are:
1221 /// * variable_length_onion_optional
1222 fn default_node_features() -> NodeFeatures {
1223 let mut features = NodeFeatures::empty();
1224 features.set_variable_length_onion_optional();
1228 struct LoggedPayeePubkey(Option<PublicKey>);
1229 impl fmt::Display for LoggedPayeePubkey {
1230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1233 "payee node id ".fmt(f)?;
1237 "blinded payee".fmt(f)
1244 fn sort_first_hop_channels(
1245 channels: &mut Vec<&ChannelDetails>, used_channel_liquidities: &HashMap<(u64, bool), u64>,
1246 recommended_value_msat: u64, our_node_pubkey: &PublicKey
1248 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1249 // most like to use.
1251 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1252 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1255 // Second, because simply always sorting in descending order would always use our largest
1256 // available outbound capacity, needlessly fragmenting our available channel capacities,
1257 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1258 // which have enough, but not too much, capacity for the payment.
1260 // Available outbound balances factor in liquidity already reserved for previously found paths.
1261 channels.sort_unstable_by(|chan_a, chan_b| {
1262 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1263 .saturating_sub(*used_channel_liquidities.get(&(chan_a.get_outbound_payment_scid().unwrap(),
1264 our_node_pubkey < &chan_a.counterparty.node_id)).unwrap_or(&0));
1265 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1266 .saturating_sub(*used_channel_liquidities.get(&(chan_b.get_outbound_payment_scid().unwrap(),
1267 our_node_pubkey < &chan_b.counterparty.node_id)).unwrap_or(&0));
1268 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1269 // Sort in descending order
1270 chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1272 // Sort in ascending order
1273 chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1278 /// Finds a route from us (payer) to the given target node (payee).
1280 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
1281 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1283 /// Private routing paths between a public node and the target may be included in `params.payee`.
1285 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1286 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1287 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1289 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1290 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1291 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1295 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
1296 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
1301 /// Panics if first_hops contains channels without short_channel_ids;
1302 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1304 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1305 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1306 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1307 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1308 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1309 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1310 scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1311 ) -> Result<Route, LightningError>
1312 where L::Target: Logger, GL::Target: Logger {
1313 let graph_lock = network_graph.read_only();
1314 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1315 route_params.final_value_msat, logger, scorer, score_params,
1316 random_seed_bytes)?;
1317 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1321 pub(crate) fn get_route<L: Deref, S: Score>(
1322 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1323 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, logger: L, scorer: &S, score_params: &S::ScoreParams,
1324 _random_seed_bytes: &[u8; 32]
1325 ) -> Result<Route, LightningError>
1326 where L::Target: Logger {
1327 // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1328 // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1329 // so use a dummy id for this in the blinded case.
1330 let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1331 const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1332 let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1333 let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1334 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1336 if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1337 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1340 if final_value_msat > MAX_VALUE_MSAT {
1341 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1344 if final_value_msat == 0 {
1345 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1348 match &payment_params.payee {
1349 Payee::Clear { route_hints, node_id, .. } => {
1350 for route in route_hints.iter() {
1351 for hop in &route.0 {
1352 if hop.src_node_id == *node_id {
1353 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1358 _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1361 let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1362 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1363 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});
1366 // The general routing idea is the following:
1367 // 1. Fill first/last hops communicated by the caller.
1368 // 2. Attempt to construct a path from payer to payee for transferring
1369 // any ~sufficient (described later) value.
1370 // If succeed, remember which channels were used and how much liquidity they have available,
1371 // so that future paths don't rely on the same liquidity.
1372 // 3. Proceed to the next step if:
1373 // - we hit the recommended target value;
1374 // - OR if we could not construct a new path. Any next attempt will fail too.
1375 // Otherwise, repeat step 2.
1376 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1377 // (not recommended value).
1378 // 5. If yes, proceed. If not, fail routing.
1379 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1380 // transferred up to the transfer target value.
1381 // 7. Reduce the value of the last path until we are sending only the target value.
1382 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1383 // them so that we're not sending two HTLCs along the same path.
1385 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1386 // distance from the payee
1388 // We are not a faithful Dijkstra's implementation because we can change values which impact
1389 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1390 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1391 // the value we are currently attempting to send over a path, we simply reduce the value being
1392 // sent along the path for any hops after that channel. This may imply that later fees (which
1393 // we've already tabulated) are lower because a smaller value is passing through the channels
1394 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1395 // channels which were selected earlier (and which may still be used for other paths without a
1396 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1399 // One potentially problematic case for this algorithm would be if there are many
1400 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1401 // graph walking), we may never find a path which is not liquidity-limited and has lower
1402 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1403 // Because we only consider paths with at least 5% of the total value being sent, the damage
1404 // from such a case should be limited, however this could be further reduced in the future by
1405 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1406 // limits for the purposes of fee calculation.
1408 // Alternatively, we could store more detailed path information in the heap (targets, below)
1409 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1410 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1411 // and practically (as we would need to store dynamically-allocated path information in heap
1412 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1413 // results of such an algorithm would likely be biased towards lower-value paths.
1415 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1416 // outside of our current search value, running a path search more times to gather candidate
1417 // paths at different values. While this may be acceptable, further path searches may increase
1418 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1419 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1420 // the same time, remaining generic across different payment values.
1422 let network_channels = network_graph.channels();
1423 let network_nodes = network_graph.nodes();
1425 if payment_params.max_path_count == 0 {
1426 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1429 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1430 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1432 let allow_mpp = if payment_params.max_path_count == 1 {
1434 } else if payment_params.payee.supports_basic_mpp() {
1436 } else if let Some(payee) = payee_node_id_opt {
1437 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1438 |info| info.features.supports_basic_mpp()))
1441 log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1442 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1443 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1446 // Prepare the data we'll use for payee-to-payer search by
1447 // inserting first hops suggested by the caller as targets.
1448 // Our search will then attempt to reach them while traversing from the payee node.
1449 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1450 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1451 if let Some(hops) = first_hops {
1453 if chan.get_outbound_payment_scid().is_none() {
1454 panic!("first_hops should be filled in with usable channels, not pending ones");
1456 if chan.counterparty.node_id == *our_node_pubkey {
1457 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1460 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1461 .or_insert(Vec::new())
1464 if first_hop_targets.is_empty() {
1465 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1469 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1470 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1471 // adding duplicate entries when we find a better path to a given node.
1472 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1474 // Map from node_id to information about the best current path to that node, including feerate
1476 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1478 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1479 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1480 // htlc_minimum with extra fees while still finding a cheaper path.
1481 let mut hit_minimum_limit;
1483 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1484 // We start with a path_value of the exact amount we want, and if that generates a route we may
1485 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1486 // amount we want in total across paths, selecting the best subset at the end.
1487 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1488 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1489 let mut path_value_msat = final_value_msat;
1491 // Routing Fragmentation Mitigation heuristic:
1493 // Routing fragmentation across many payment paths increases the overall routing
1494 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1495 // Taking too many smaller paths also increases the chance of payment failure.
1496 // Thus to avoid this effect, we require from our collected links to provide
1497 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1498 // This requirement is currently set to be 1/max_path_count of the payment
1499 // value to ensure we only ever return routes that do not violate this limit.
1500 let minimal_value_contribution_msat: u64 = if allow_mpp {
1501 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1506 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1507 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1508 // drop the requirement by setting this to 0.
1509 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1511 // Keep track of how much liquidity has been used in selected channels. Used to determine
1512 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1513 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1514 // liquidity used in one direction will not offset any used in the opposite direction.
1515 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1516 HashMap::with_capacity(network_nodes.len());
1518 // Keeping track of how much value we already collected across other paths. Helps to decide
1519 // when we want to stop looking for new paths.
1520 let mut already_collected_value_msat = 0;
1522 for (_, channels) in first_hop_targets.iter_mut() {
1523 sort_first_hop_channels(channels, &used_channel_liquidities, recommended_value_msat,
1527 log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1528 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1530 macro_rules! add_entry {
1531 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1532 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1533 // since that value has to be transferred over this channel.
1534 // Returns whether this channel caused an update to `targets`.
1535 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1536 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1537 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1538 // We "return" whether we updated the path at the end, and how much we can route via
1539 // this channel, via this:
1540 let mut did_add_update_path_to_src_node = None;
1541 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1542 // practice these cases should be caught earlier:
1543 // - for regular channels at channel announcement (TODO)
1544 // - for first and last hops early in get_route
1545 if $src_node_id != $dest_node_id {
1546 let short_channel_id = $candidate.short_channel_id();
1547 let effective_capacity = $candidate.effective_capacity();
1548 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1550 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1551 // It may be misleading because we might later choose to reduce the value transferred
1552 // over these channels, and the channel which was insufficient might become sufficient.
1553 // Worst case: we drop a good channel here because it can't cover the high following
1554 // fees caused by one expensive channel, but then this channel could have been used
1555 // if the amount being transferred over this path is lower.
1556 // We do this for now, but this is a subject for removal.
1557 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1558 let used_liquidity_msat = used_channel_liquidities
1559 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1560 .map_or(0, |used_liquidity_msat| {
1561 available_value_contribution_msat = available_value_contribution_msat
1562 .saturating_sub(*used_liquidity_msat);
1563 *used_liquidity_msat
1566 // Verify the liquidity offered by this channel complies to the minimal contribution.
1567 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1568 // Do not consider candidate hops that would exceed the maximum path length.
1569 let path_length_to_node = $next_hops_path_length + 1;
1570 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1572 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1573 // In order to already account for some of the privacy enhancing random CLTV
1574 // expiry delta offset we add on top later, we subtract a rough estimate
1575 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1576 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1577 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1578 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1579 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1580 .saturating_add($candidate.cltv_expiry_delta());
1581 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1583 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1584 // Includes paying fees for the use of the following channels.
1585 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1586 Some(result) => result,
1587 // Can't overflow due to how the values were computed right above.
1588 None => unreachable!(),
1590 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1591 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1592 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1594 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1595 let may_overpay_to_meet_path_minimum_msat =
1596 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1597 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1598 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1599 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1601 let payment_failed_on_this_channel =
1602 payment_params.previously_failed_channels.contains(&short_channel_id);
1604 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1605 // bother considering this channel. If retrying with recommended_value_msat may
1606 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1607 // around again with a higher amount.
1608 if !contributes_sufficient_value || exceeds_max_path_length ||
1609 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1610 // Path isn't useful, ignore it and move on.
1611 } else if may_overpay_to_meet_path_minimum_msat {
1612 hit_minimum_limit = true;
1613 } else if over_path_minimum_msat {
1614 // Note that low contribution here (limited by available_liquidity_msat)
1615 // might violate htlc_minimum_msat on the hops which are next along the
1616 // payment path (upstream to the payee). To avoid that, we recompute
1617 // path fees knowing the final path contribution after constructing it.
1618 let path_htlc_minimum_msat = cmp::max(
1619 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1620 .saturating_add($next_hops_path_htlc_minimum_msat),
1621 $candidate.htlc_minimum_msat());
1622 let hm_entry = dist.entry($src_node_id);
1623 let old_entry = hm_entry.or_insert_with(|| {
1624 // If there was previously no known way to access the source node
1625 // (recall it goes payee-to-payer) of short_channel_id, first add a
1626 // semi-dummy record just to compute the fees to reach the source node.
1627 // This will affect our decision on selecting short_channel_id
1628 // as a way to reach the $dest_node_id.
1630 node_id: $dest_node_id.clone(),
1631 candidate: $candidate.clone(),
1633 next_hops_fee_msat: u64::max_value(),
1634 hop_use_fee_msat: u64::max_value(),
1635 total_fee_msat: u64::max_value(),
1636 path_htlc_minimum_msat,
1637 path_penalty_msat: u64::max_value(),
1638 was_processed: false,
1639 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1640 value_contribution_msat,
1644 #[allow(unused_mut)] // We only use the mut in cfg(test)
1645 let mut should_process = !old_entry.was_processed;
1646 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1648 // In test/fuzzing builds, we do extra checks to make sure the skipping
1649 // of already-seen nodes only happens in cases we expect (see below).
1650 if !should_process { should_process = true; }
1654 let mut hop_use_fee_msat = 0;
1655 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1657 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1658 // will have the same effective-fee
1659 if $src_node_id != our_node_id {
1660 // Note that `u64::max_value` means we'll always fail the
1661 // `old_entry.total_fee_msat > total_fee_msat` check below
1662 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1663 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1666 let channel_usage = ChannelUsage {
1667 amount_msat: amount_to_transfer_over_msat,
1668 inflight_htlc_msat: used_liquidity_msat,
1671 let channel_penalty_msat = scorer.channel_penalty_msat(
1672 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage, score_params
1674 let path_penalty_msat = $next_hops_path_penalty_msat
1675 .saturating_add(channel_penalty_msat);
1676 let new_graph_node = RouteGraphNode {
1677 node_id: $src_node_id,
1678 lowest_fee_to_node: total_fee_msat,
1679 total_cltv_delta: hop_total_cltv_delta,
1680 value_contribution_msat,
1681 path_htlc_minimum_msat,
1683 path_length_to_node,
1686 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1687 // if this way is cheaper than the already known
1688 // (considering the cost to "reach" this channel from the route destination,
1689 // the cost of using this channel,
1690 // and the cost of routing to the source node of this channel).
1691 // Also, consider that htlc_minimum_msat_difference, because we might end up
1692 // paying it. Consider the following exploit:
1693 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1694 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1695 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1696 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1698 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1699 // but it may require additional tracking - we don't want to double-count
1700 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1701 // can't use something that may decrease on future hops.
1702 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1703 .saturating_add(old_entry.path_penalty_msat);
1704 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1705 .saturating_add(path_penalty_msat);
1707 if !old_entry.was_processed && new_cost < old_cost {
1708 targets.push(new_graph_node);
1709 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1710 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1711 old_entry.total_fee_msat = total_fee_msat;
1712 old_entry.node_id = $dest_node_id.clone();
1713 old_entry.candidate = $candidate.clone();
1714 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1715 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1716 old_entry.path_penalty_msat = path_penalty_msat;
1717 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1719 old_entry.value_contribution_msat = value_contribution_msat;
1721 did_add_update_path_to_src_node = Some(value_contribution_msat);
1722 } else if old_entry.was_processed && new_cost < old_cost {
1723 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1725 // If we're skipping processing a node which was previously
1726 // processed even though we found another path to it with a
1727 // cheaper fee, check that it was because the second path we
1728 // found (which we are processing now) has a lower value
1729 // contribution due to an HTLC minimum limit.
1731 // e.g. take a graph with two paths from node 1 to node 2, one
1732 // through channel A, and one through channel B. Channel A and
1733 // B are both in the to-process heap, with their scores set by
1734 // a higher htlc_minimum than fee.
1735 // Channel A is processed first, and the channels onwards from
1736 // node 1 are added to the to-process heap. Thereafter, we pop
1737 // Channel B off of the heap, note that it has a much more
1738 // restrictive htlc_maximum_msat, and recalculate the fees for
1739 // all of node 1's channels using the new, reduced, amount.
1741 // This would be bogus - we'd be selecting a higher-fee path
1742 // with a lower htlc_maximum_msat instead of the one we'd
1743 // already decided to use.
1744 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1746 value_contribution_msat + path_penalty_msat <
1747 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1755 did_add_update_path_to_src_node
1759 let default_node_features = default_node_features();
1761 // Find ways (channels with destination) to reach a given node and store them
1762 // in the corresponding data structures (routing graph etc).
1763 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1764 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1765 // This data can later be helpful to optimize routing (pay lower fees).
1766 macro_rules! add_entries_to_cheapest_to_target_node {
1767 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1768 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1769 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1770 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1771 let was_processed = elem.was_processed;
1772 elem.was_processed = true;
1775 // Entries are added to dist in add_entry!() when there is a channel from a node.
1776 // Because there are no channels from payee, it will not have a dist entry at this point.
1777 // If we're processing any other node, it is always be the result of a channel from it.
1778 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1783 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1784 for details in first_channels {
1785 let candidate = CandidateRouteHop::FirstHop { details };
1786 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1787 $next_hops_value_contribution,
1788 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1789 $next_hops_cltv_delta, $next_hops_path_length);
1793 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1796 &default_node_features
1799 if !features.requires_unknown_bits() {
1800 for chan_id in $node.channels.iter() {
1801 let chan = network_channels.get(chan_id).unwrap();
1802 if !chan.features.requires_unknown_bits() {
1803 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1804 if first_hops.is_none() || *source != our_node_id {
1805 if directed_channel.direction().enabled {
1806 let candidate = CandidateRouteHop::PublicHop {
1807 info: directed_channel,
1808 short_channel_id: *chan_id,
1810 add_entry!(candidate, *source, $node_id,
1811 $fee_to_target_msat,
1812 $next_hops_value_contribution,
1813 $next_hops_path_htlc_minimum_msat,
1814 $next_hops_path_penalty_msat,
1815 $next_hops_cltv_delta, $next_hops_path_length);
1826 let mut payment_paths = Vec::<PaymentPath>::new();
1828 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1829 'paths_collection: loop {
1830 // For every new path, start from scratch, except for used_channel_liquidities, which
1831 // helps to avoid reusing previously selected paths in future iterations.
1834 hit_minimum_limit = false;
1836 // If first hop is a private channel and the only way to reach the payee, this is the only
1837 // place where it could be added.
1838 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
1839 for details in first_channels {
1840 let candidate = CandidateRouteHop::FirstHop { details };
1841 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
1842 0, 0u64, 0, 0).is_some();
1843 log_trace!(logger, "{} direct route to payee via SCID {}",
1844 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1848 // Add the payee as a target, so that the payee-to-payer
1849 // search algorithm knows what to start with.
1850 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
1851 // The payee is not in our network graph, so nothing to add here.
1852 // There is still a chance of reaching them via last_hops though,
1853 // so don't yet fail the payment here.
1854 // If not, targets.pop() will not even let us enter the loop in step 2.
1857 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
1862 // If a caller provided us with last hops, add them to routing targets. Since this happens
1863 // earlier than general path finding, they will be somewhat prioritized, although currently
1864 // it matters only if the fees are exactly the same.
1865 let route_hints = match &payment_params.payee {
1866 Payee::Clear { route_hints, .. } => route_hints,
1867 _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1869 for route in route_hints.iter().filter(|route| !route.0.is_empty()) {
1870 let first_hop_in_route = &(route.0)[0];
1871 let have_hop_src_in_graph =
1872 // Only add the hops in this route to our candidate set if either
1873 // we have a direct channel to the first hop or the first hop is
1874 // in the regular network graph.
1875 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1876 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1877 if have_hop_src_in_graph {
1878 // We start building the path from reverse, i.e., from payee
1879 // to the first RouteHintHop in the path.
1880 let hop_iter = route.0.iter().rev();
1881 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
1882 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1883 let mut hop_used = true;
1884 let mut aggregate_next_hops_fee_msat: u64 = 0;
1885 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1886 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1887 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1888 let mut aggregate_next_hops_path_length: u8 = 0;
1889 let mut aggregate_path_contribution_msat = path_value_msat;
1891 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1892 let source = NodeId::from_pubkey(&hop.src_node_id);
1893 let target = NodeId::from_pubkey(&prev_hop_id);
1894 let candidate = network_channels
1895 .get(&hop.short_channel_id)
1896 .and_then(|channel| channel.as_directed_to(&target))
1897 .map(|(info, _)| CandidateRouteHop::PublicHop {
1899 short_channel_id: hop.short_channel_id,
1901 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1903 if let Some(hop_used_msat) = add_entry!(candidate, source, target,
1904 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
1905 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
1906 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
1908 aggregate_path_contribution_msat = hop_used_msat;
1910 // If this hop was not used then there is no use checking the preceding
1911 // hops in the RouteHint. We can break by just searching for a direct
1912 // channel between last checked hop and first_hop_targets.
1916 let used_liquidity_msat = used_channel_liquidities
1917 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1918 let channel_usage = ChannelUsage {
1919 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1920 inflight_htlc_msat: used_liquidity_msat,
1921 effective_capacity: candidate.effective_capacity(),
1923 let channel_penalty_msat = scorer.channel_penalty_msat(
1924 hop.short_channel_id, &source, &target, channel_usage, score_params
1926 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1927 .saturating_add(channel_penalty_msat);
1929 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1930 .saturating_add(hop.cltv_expiry_delta as u32);
1932 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1935 // Searching for a direct channel between last checked hop and first_hop_targets
1936 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
1937 sort_first_hop_channels(first_channels, &used_channel_liquidities,
1938 recommended_value_msat, our_node_pubkey);
1939 for details in first_channels {
1940 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
1941 add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1942 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
1943 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
1944 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
1952 // In the next values of the iterator, the aggregate fees already reflects
1953 // the sum of value sent from payer (final_value_msat) and routing fees
1954 // for the last node in the RouteHint. We need to just add the fees to
1955 // route through the current node so that the preceding node (next iteration)
1957 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1958 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1959 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1961 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1962 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1963 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1964 .checked_add(hop_htlc_minimum_msat_inc);
1965 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1967 if idx == route.0.len() - 1 {
1968 // The last hop in this iterator is the first hop in
1969 // overall RouteHint.
1970 // If this hop connects to a node with which we have a direct channel,
1971 // ignore the network graph and, if the last hop was added, add our
1972 // direct channel to the candidate set.
1974 // Note that we *must* check if the last hop was added as `add_entry`
1975 // always assumes that the third argument is a node to which we have a
1977 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
1978 sort_first_hop_channels(first_channels, &used_channel_liquidities,
1979 recommended_value_msat, our_node_pubkey);
1980 for details in first_channels {
1981 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
1982 add_entry!(first_hop_candidate, our_node_id,
1983 NodeId::from_pubkey(&hop.src_node_id),
1984 aggregate_next_hops_fee_msat,
1985 aggregate_path_contribution_msat,
1986 aggregate_next_hops_path_htlc_minimum_msat,
1987 aggregate_next_hops_path_penalty_msat,
1988 aggregate_next_hops_cltv_delta,
1989 aggregate_next_hops_path_length);
1997 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1999 // At this point, targets are filled with the data from first and
2000 // last hops communicated by the caller, and the payment receiver.
2001 let mut found_new_path = false;
2004 // If this loop terminates due the exhaustion of targets, two situations are possible:
2005 // - not enough outgoing liquidity:
2006 // 0 < already_collected_value_msat < final_value_msat
2007 // - enough outgoing liquidity:
2008 // final_value_msat <= already_collected_value_msat < recommended_value_msat
2009 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2010 // paths_collection will be stopped because found_new_path==false.
2011 // This is not necessarily a routing failure.
2012 '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() {
2014 // Since we're going payee-to-payer, hitting our node as a target means we should stop
2015 // traversing the graph and arrange the path out of what we found.
2016 if node_id == our_node_id {
2017 let mut new_entry = dist.remove(&our_node_id).unwrap();
2018 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2021 let mut features_set = false;
2022 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2023 for details in first_channels {
2024 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2025 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2026 features_set = true;
2032 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2033 if let Some(node_info) = node.announcement_info.as_ref() {
2034 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2036 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2039 // We can fill in features for everything except hops which were
2040 // provided via the invoice we're paying. We could guess based on the
2041 // recipient's features but for now we simply avoid guessing at all.
2045 // Means we succesfully traversed from the payer to the payee, now
2046 // save this path for the payment route. Also, update the liquidity
2047 // remaining on the used hops, so that we take them into account
2048 // while looking for more paths.
2049 if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2053 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2054 Some(payment_hop) => payment_hop,
2055 // We can't arrive at None because, if we ever add an entry to targets,
2056 // we also fill in the entry in dist (see add_entry!).
2057 None => unreachable!(),
2059 // We "propagate" the fees one hop backward (topologically) here,
2060 // so that fees paid for a HTLC forwarding on the current channel are
2061 // associated with the previous channel (where they will be subtracted).
2062 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2063 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2065 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2066 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2068 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2069 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2071 let mut payment_path = PaymentPath {hops: ordered_hops};
2073 // We could have possibly constructed a slightly inconsistent path: since we reduce
2074 // value being transferred along the way, we could have violated htlc_minimum_msat
2075 // on some channels we already passed (assuming dest->source direction). Here, we
2076 // recompute the fees again, so that if that's the case, we match the currently
2077 // underpaid htlc_minimum_msat with fees.
2078 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2079 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2080 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2082 // Since a path allows to transfer as much value as
2083 // the smallest channel it has ("bottleneck"), we should recompute
2084 // the fees so sender HTLC don't overpay fees when traversing
2085 // larger channels than the bottleneck. This may happen because
2086 // when we were selecting those channels we were not aware how much value
2087 // this path will transfer, and the relative fee for them
2088 // might have been computed considering a larger value.
2089 // Remember that we used these channels so that we don't rely
2090 // on the same liquidity in future paths.
2091 let mut prevented_redundant_path_selection = false;
2092 let prev_hop_iter = core::iter::once(&our_node_id)
2093 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2094 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2095 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2096 let used_liquidity_msat = used_channel_liquidities
2097 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
2098 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2099 .or_insert(spent_on_hop_msat);
2100 let hop_capacity = hop.candidate.effective_capacity();
2101 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2102 if *used_liquidity_msat == hop_max_msat {
2103 // If this path used all of this channel's available liquidity, we know
2104 // this path will not be selected again in the next loop iteration.
2105 prevented_redundant_path_selection = true;
2107 debug_assert!(*used_liquidity_msat <= hop_max_msat);
2109 if !prevented_redundant_path_selection {
2110 // If we weren't capped by hitting a liquidity limit on a channel in the path,
2111 // we'll probably end up picking the same path again on the next iteration.
2112 // Decrease the available liquidity of a hop in the middle of the path.
2113 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
2114 let exhausted = u64::max_value();
2115 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
2116 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
2117 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
2120 // Track the total amount all our collected paths allow to send so that we know
2121 // when to stop looking for more paths
2122 already_collected_value_msat += value_contribution_msat;
2124 payment_paths.push(payment_path);
2125 found_new_path = true;
2126 break 'path_construction;
2129 // If we found a path back to the payee, we shouldn't try to process it again. This is
2130 // the equivalent of the `elem.was_processed` check in
2131 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2132 if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2134 // Otherwise, since the current target node is not us,
2135 // keep "unrolling" the payment graph from payee to payer by
2136 // finding a way to reach the current target from the payer side.
2137 match network_nodes.get(&node_id) {
2140 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2141 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2142 total_cltv_delta, path_length_to_node);
2148 if !found_new_path && channel_saturation_pow_half != 0 {
2149 channel_saturation_pow_half = 0;
2150 continue 'paths_collection;
2152 // If we don't support MPP, no use trying to gather more value ever.
2153 break 'paths_collection;
2157 // Stop either when the recommended value is reached or if no new path was found in this
2159 // In the latter case, making another path finding attempt won't help,
2160 // because we deterministically terminated the search due to low liquidity.
2161 if !found_new_path && channel_saturation_pow_half != 0 {
2162 channel_saturation_pow_half = 0;
2163 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2164 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2165 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2166 break 'paths_collection;
2167 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2168 // Further, if this was our first walk of the graph, and we weren't limited by an
2169 // htlc_minimum_msat, return immediately because this path should suffice. If we were
2170 // limited by an htlc_minimum_msat value, find another path with a higher value,
2171 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2172 // still keeping a lower total fee than this path.
2173 if !hit_minimum_limit {
2174 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2175 break 'paths_collection;
2177 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2178 path_value_msat = recommended_value_msat;
2183 if payment_paths.len() == 0 {
2184 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2187 if already_collected_value_msat < final_value_msat {
2188 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2192 let mut selected_route = payment_paths;
2194 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2195 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2197 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2198 // the value they contribute towards the payment amount.
2199 // We sort in descending order as we will remove from the front in `retain`, next.
2200 selected_route.sort_unstable_by(|a, b|
2201 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2202 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2205 // We should make sure that at least 1 path left.
2206 let mut paths_left = selected_route.len();
2207 selected_route.retain(|path| {
2208 if paths_left == 1 {
2211 let path_value_msat = path.get_value_msat();
2212 if path_value_msat <= overpaid_value_msat {
2213 overpaid_value_msat -= path_value_msat;
2219 debug_assert!(selected_route.len() > 0);
2221 if overpaid_value_msat != 0 {
2223 // Now, subtract the remaining overpaid value from the most-expensive path.
2224 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2225 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2226 selected_route.sort_unstable_by(|a, b| {
2227 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2228 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2229 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2231 let expensive_payment_path = selected_route.first_mut().unwrap();
2233 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2234 // can't go negative.
2235 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2236 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2240 // Sort by the path itself and combine redundant paths.
2241 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2242 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2244 selected_route.sort_unstable_by_key(|path| {
2245 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
2246 debug_assert!(path.hops.len() <= key.len());
2247 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
2252 for idx in 0..(selected_route.len() - 1) {
2253 if idx + 1 >= selected_route.len() { break; }
2254 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
2255 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
2256 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2257 selected_route[idx].update_value_and_recompute_fees(new_value);
2258 selected_route.remove(idx + 1);
2262 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
2263 for payment_path in selected_route {
2264 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
2266 pubkey: PublicKey::from_slice(payment_hop.node_id.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &payment_hop.node_id), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2267 node_features: node_features.clone(),
2268 short_channel_id: payment_hop.candidate.short_channel_id(),
2269 channel_features: payment_hop.candidate.features(),
2270 fee_msat: payment_hop.fee_msat,
2271 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
2273 }).collect::<Vec<_>>();
2274 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2275 // applicable for the previous hop.
2276 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
2277 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
2279 selected_paths.push(path);
2281 // Make sure we would never create a route with more paths than we allow.
2282 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
2284 if let Some(node_features) = payment_params.payee.node_features() {
2285 for path in selected_paths.iter_mut() {
2286 if let Ok(route_hop) = path.last_mut().unwrap() {
2287 route_hop.node_features = node_features.clone();
2292 let mut paths: Vec<Path> = Vec::new();
2293 for results_vec in selected_paths {
2294 let mut hops = Vec::with_capacity(results_vec.len());
2295 for res in results_vec { hops.push(res?); }
2296 paths.push(Path { hops, blinded_tail: None });
2300 payment_params: Some(payment_params.clone()),
2302 log_info!(logger, "Got route: {}", log_route!(route));
2306 // When an adversarial intermediary node observes a payment, it may be able to infer its
2307 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2308 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2309 // payment path by adding a randomized 'shadow route' offset to the final hop.
2310 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2311 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2313 let network_channels = network_graph.channels();
2314 let network_nodes = network_graph.nodes();
2316 for path in route.paths.iter_mut() {
2317 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2319 // Remember the last three nodes of the random walk and avoid looping back on them.
2320 // Init with the last three nodes from the actual path, if possible.
2321 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2322 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2323 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2325 // Choose the last publicly known node as the starting point for the random walk.
2326 let mut cur_hop: Option<NodeId> = None;
2327 let mut path_nonce = [0u8; 12];
2328 if let Some(starting_hop) = path.hops.iter().rev()
2329 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2330 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2331 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2334 // Init PRNG with the path-dependant nonce, which is static for private paths.
2335 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2336 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2338 // Pick a random path length in [1 .. 3]
2339 prng.process_in_place(&mut random_path_bytes);
2340 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2342 for random_hop in 0..random_walk_length {
2343 // If we don't find a suitable offset in the public network graph, we default to
2344 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2345 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2347 if let Some(cur_node_id) = cur_hop {
2348 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2349 // Randomly choose the next unvisited hop.
2350 prng.process_in_place(&mut random_path_bytes);
2351 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2352 .checked_rem(cur_node.channels.len())
2353 .and_then(|index| cur_node.channels.get(index))
2354 .and_then(|id| network_channels.get(id)) {
2355 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2356 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2357 nodes_to_avoid[random_hop] = *next_id;
2358 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2359 cur_hop = Some(*next_id);
2366 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2367 .checked_add(random_hop_offset)
2368 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2371 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2372 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2373 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2375 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2376 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2377 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2378 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2379 max_path_offset = cmp::max(
2380 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2381 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2382 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2384 // Add 'shadow' CLTV offset to the final hop
2385 if let Some(tail) = path.blinded_tail.as_mut() {
2386 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2387 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2389 if let Some(last_hop) = path.hops.last_mut() {
2390 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2391 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2396 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2397 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2399 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2400 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2401 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2402 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2403 ) -> Result<Route, LightningError>
2404 where L::Target: Logger, GL::Target: Logger {
2405 let graph_lock = network_graph.read_only();
2406 let mut route = build_route_from_hops_internal(
2407 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2408 route_params.final_value_msat, logger, random_seed_bytes)?;
2409 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2413 fn build_route_from_hops_internal<L: Deref>(
2414 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2415 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, logger: L,
2416 random_seed_bytes: &[u8; 32]
2417 ) -> Result<Route, LightningError> where L::Target: Logger {
2420 our_node_id: NodeId,
2421 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2424 impl Score for HopScorer {
2425 type ScoreParams = ();
2426 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2427 _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2429 let mut cur_id = self.our_node_id;
2430 for i in 0..self.hop_ids.len() {
2431 if let Some(next_id) = self.hop_ids[i] {
2432 if cur_id == *source && next_id == *target {
2443 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2445 fn payment_path_successful(&mut self, _path: &Path) {}
2447 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2449 fn probe_successful(&mut self, _path: &Path) {}
2452 impl<'a> Writeable for HopScorer {
2454 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2459 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2460 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2463 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2464 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2465 for i in 0..hops.len() {
2466 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2469 let scorer = HopScorer { our_node_id, hop_ids };
2471 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2472 logger, &scorer, &(), random_seed_bytes)
2477 use crate::blinded_path::{BlindedHop, BlindedPath};
2478 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2479 use crate::routing::utxo::UtxoResult;
2480 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2481 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2482 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2483 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2484 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2485 use crate::chain::transaction::OutPoint;
2486 use crate::sign::EntropySource;
2487 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2488 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2489 use crate::ln::channelmanager;
2490 use crate::util::config::UserConfig;
2491 use crate::util::test_utils as ln_test_utils;
2492 use crate::util::chacha20::ChaCha20;
2493 use crate::util::ser::{Readable, Writeable};
2495 use crate::util::ser::Writer;
2497 use bitcoin::hashes::Hash;
2498 use bitcoin::network::constants::Network;
2499 use bitcoin::blockdata::constants::genesis_block;
2500 use bitcoin::blockdata::script::Builder;
2501 use bitcoin::blockdata::opcodes;
2502 use bitcoin::blockdata::transaction::TxOut;
2506 use bitcoin::secp256k1::{PublicKey,SecretKey};
2507 use bitcoin::secp256k1::Secp256k1;
2509 use crate::io::Cursor;
2510 use crate::prelude::*;
2511 use crate::sync::Arc;
2513 use core::convert::TryInto;
2515 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2516 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2517 channelmanager::ChannelDetails {
2518 channel_id: [0; 32],
2519 counterparty: channelmanager::ChannelCounterparty {
2522 unspendable_punishment_reserve: 0,
2523 forwarding_info: None,
2524 outbound_htlc_minimum_msat: None,
2525 outbound_htlc_maximum_msat: None,
2527 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2530 outbound_scid_alias: None,
2531 inbound_scid_alias: None,
2532 channel_value_satoshis: 0,
2535 outbound_capacity_msat,
2536 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2537 next_outbound_htlc_minimum_msat: 0,
2538 inbound_capacity_msat: 42,
2539 unspendable_punishment_reserve: None,
2540 confirmations_required: None,
2541 confirmations: None,
2542 force_close_spend_delay: None,
2543 is_outbound: true, is_channel_ready: true,
2544 is_usable: true, is_public: true,
2545 inbound_htlc_minimum_msat: None,
2546 inbound_htlc_maximum_msat: None,
2548 feerate_sat_per_1000_weight: None
2553 fn simple_route_test() {
2554 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2555 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2556 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2557 let scorer = ln_test_utils::TestScorer::new();
2558 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2559 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2561 // Simple route to 2 via 1
2563 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 0, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2564 assert_eq!(err, "Cannot send a payment of 0 msat");
2565 } else { panic!(); }
2567 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2568 assert_eq!(route.paths[0].hops.len(), 2);
2570 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2571 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2572 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2573 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2574 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2575 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2577 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2578 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2579 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2580 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2581 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2582 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2586 fn invalid_first_hop_test() {
2587 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2588 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2589 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2590 let scorer = ln_test_utils::TestScorer::new();
2591 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2592 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2594 // Simple route to 2 via 1
2596 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2598 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2599 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2600 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2601 } else { panic!(); }
2603 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2604 assert_eq!(route.paths[0].hops.len(), 2);
2608 fn htlc_minimum_test() {
2609 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2610 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2611 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2612 let scorer = ln_test_utils::TestScorer::new();
2613 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2614 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2616 // Simple route to 2 via 1
2618 // Disable other paths
2619 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2620 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2621 short_channel_id: 12,
2623 flags: 2, // to disable
2624 cltv_expiry_delta: 0,
2625 htlc_minimum_msat: 0,
2626 htlc_maximum_msat: MAX_VALUE_MSAT,
2628 fee_proportional_millionths: 0,
2629 excess_data: Vec::new()
2631 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2632 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2633 short_channel_id: 3,
2635 flags: 2, // to disable
2636 cltv_expiry_delta: 0,
2637 htlc_minimum_msat: 0,
2638 htlc_maximum_msat: MAX_VALUE_MSAT,
2640 fee_proportional_millionths: 0,
2641 excess_data: Vec::new()
2643 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2644 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2645 short_channel_id: 13,
2647 flags: 2, // to disable
2648 cltv_expiry_delta: 0,
2649 htlc_minimum_msat: 0,
2650 htlc_maximum_msat: MAX_VALUE_MSAT,
2652 fee_proportional_millionths: 0,
2653 excess_data: Vec::new()
2655 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2657 short_channel_id: 6,
2659 flags: 2, // to disable
2660 cltv_expiry_delta: 0,
2661 htlc_minimum_msat: 0,
2662 htlc_maximum_msat: MAX_VALUE_MSAT,
2664 fee_proportional_millionths: 0,
2665 excess_data: Vec::new()
2667 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2669 short_channel_id: 7,
2671 flags: 2, // to disable
2672 cltv_expiry_delta: 0,
2673 htlc_minimum_msat: 0,
2674 htlc_maximum_msat: MAX_VALUE_MSAT,
2676 fee_proportional_millionths: 0,
2677 excess_data: Vec::new()
2680 // Check against amount_to_transfer_over_msat.
2681 // Set minimal HTLC of 200_000_000 msat.
2682 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2684 short_channel_id: 2,
2687 cltv_expiry_delta: 0,
2688 htlc_minimum_msat: 200_000_000,
2689 htlc_maximum_msat: MAX_VALUE_MSAT,
2691 fee_proportional_millionths: 0,
2692 excess_data: Vec::new()
2695 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2697 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2698 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2699 short_channel_id: 4,
2702 cltv_expiry_delta: 0,
2703 htlc_minimum_msat: 0,
2704 htlc_maximum_msat: 199_999_999,
2706 fee_proportional_millionths: 0,
2707 excess_data: Vec::new()
2710 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2711 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2712 assert_eq!(err, "Failed to find a path to the given destination");
2713 } else { panic!(); }
2715 // Lift the restriction on the first hop.
2716 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2718 short_channel_id: 2,
2721 cltv_expiry_delta: 0,
2722 htlc_minimum_msat: 0,
2723 htlc_maximum_msat: MAX_VALUE_MSAT,
2725 fee_proportional_millionths: 0,
2726 excess_data: Vec::new()
2729 // A payment above the minimum should pass
2730 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2731 assert_eq!(route.paths[0].hops.len(), 2);
2735 fn htlc_minimum_overpay_test() {
2736 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2737 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2738 let config = UserConfig::default();
2739 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2740 let scorer = ln_test_utils::TestScorer::new();
2741 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2742 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2744 // A route to node#2 via two paths.
2745 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2746 // Thus, they can't send 60 without overpaying.
2747 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2749 short_channel_id: 2,
2752 cltv_expiry_delta: 0,
2753 htlc_minimum_msat: 35_000,
2754 htlc_maximum_msat: 40_000,
2756 fee_proportional_millionths: 0,
2757 excess_data: Vec::new()
2759 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2761 short_channel_id: 12,
2764 cltv_expiry_delta: 0,
2765 htlc_minimum_msat: 35_000,
2766 htlc_maximum_msat: 40_000,
2768 fee_proportional_millionths: 0,
2769 excess_data: Vec::new()
2773 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2775 short_channel_id: 13,
2778 cltv_expiry_delta: 0,
2779 htlc_minimum_msat: 0,
2780 htlc_maximum_msat: MAX_VALUE_MSAT,
2782 fee_proportional_millionths: 0,
2783 excess_data: Vec::new()
2785 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2787 short_channel_id: 4,
2790 cltv_expiry_delta: 0,
2791 htlc_minimum_msat: 0,
2792 htlc_maximum_msat: MAX_VALUE_MSAT,
2794 fee_proportional_millionths: 0,
2795 excess_data: Vec::new()
2798 // Disable other paths
2799 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2801 short_channel_id: 1,
2803 flags: 2, // to disable
2804 cltv_expiry_delta: 0,
2805 htlc_minimum_msat: 0,
2806 htlc_maximum_msat: MAX_VALUE_MSAT,
2808 fee_proportional_millionths: 0,
2809 excess_data: Vec::new()
2812 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2813 // Overpay fees to hit htlc_minimum_msat.
2814 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2815 // TODO: this could be better balanced to overpay 10k and not 15k.
2816 assert_eq!(overpaid_fees, 15_000);
2818 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2819 // while taking even more fee to match htlc_minimum_msat.
2820 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2822 short_channel_id: 12,
2825 cltv_expiry_delta: 0,
2826 htlc_minimum_msat: 65_000,
2827 htlc_maximum_msat: 80_000,
2829 fee_proportional_millionths: 0,
2830 excess_data: Vec::new()
2832 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2833 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2834 short_channel_id: 2,
2837 cltv_expiry_delta: 0,
2838 htlc_minimum_msat: 0,
2839 htlc_maximum_msat: MAX_VALUE_MSAT,
2841 fee_proportional_millionths: 0,
2842 excess_data: Vec::new()
2844 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2845 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2846 short_channel_id: 4,
2849 cltv_expiry_delta: 0,
2850 htlc_minimum_msat: 0,
2851 htlc_maximum_msat: MAX_VALUE_MSAT,
2853 fee_proportional_millionths: 100_000,
2854 excess_data: Vec::new()
2857 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2858 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2859 assert_eq!(route.paths.len(), 1);
2860 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
2861 let fees = route.paths[0].hops[0].fee_msat;
2862 assert_eq!(fees, 5_000);
2864 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2865 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2866 // the other channel.
2867 assert_eq!(route.paths.len(), 1);
2868 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2869 let fees = route.paths[0].hops[0].fee_msat;
2870 assert_eq!(fees, 5_000);
2874 fn disable_channels_test() {
2875 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2876 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2877 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2878 let scorer = ln_test_utils::TestScorer::new();
2879 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2880 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2882 // // Disable channels 4 and 12 by flags=2
2883 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2885 short_channel_id: 4,
2887 flags: 2, // to disable
2888 cltv_expiry_delta: 0,
2889 htlc_minimum_msat: 0,
2890 htlc_maximum_msat: MAX_VALUE_MSAT,
2892 fee_proportional_millionths: 0,
2893 excess_data: Vec::new()
2895 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2897 short_channel_id: 12,
2899 flags: 2, // to disable
2900 cltv_expiry_delta: 0,
2901 htlc_minimum_msat: 0,
2902 htlc_maximum_msat: MAX_VALUE_MSAT,
2904 fee_proportional_millionths: 0,
2905 excess_data: Vec::new()
2908 // If all the channels require some features we don't understand, route should fail
2909 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2910 assert_eq!(err, "Failed to find a path to the given destination");
2911 } else { panic!(); }
2913 // If we specify a channel to node7, that overrides our local channel view and that gets used
2914 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2915 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2916 assert_eq!(route.paths[0].hops.len(), 2);
2918 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
2919 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
2920 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2921 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
2922 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2923 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2925 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2926 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
2927 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2928 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2929 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2930 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
2934 fn disable_node_test() {
2935 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2936 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2937 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2938 let scorer = ln_test_utils::TestScorer::new();
2939 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2940 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2942 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2943 let mut unknown_features = NodeFeatures::empty();
2944 unknown_features.set_unknown_feature_required();
2945 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2946 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2947 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2949 // If all nodes require some features we don't understand, route should fail
2950 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2951 assert_eq!(err, "Failed to find a path to the given destination");
2952 } else { panic!(); }
2954 // If we specify a channel to node7, that overrides our local channel view and that gets used
2955 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2956 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2957 assert_eq!(route.paths[0].hops.len(), 2);
2959 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
2960 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
2961 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2962 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
2963 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2964 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2966 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2967 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
2968 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2969 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2970 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2971 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
2973 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2974 // naively) assume that the user checked the feature bits on the invoice, which override
2975 // the node_announcement.
2979 fn our_chans_test() {
2980 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2981 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2982 let scorer = ln_test_utils::TestScorer::new();
2983 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2984 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2986 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2987 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
2988 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2989 assert_eq!(route.paths[0].hops.len(), 3);
2991 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2992 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2993 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2994 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2995 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2996 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2998 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2999 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3000 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3001 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3002 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3003 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3005 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3006 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3007 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3008 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3009 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3010 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3012 // If we specify a channel to node7, that overrides our local channel view and that gets used
3013 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3014 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3015 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3016 assert_eq!(route.paths[0].hops.len(), 2);
3018 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3019 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3020 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3021 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3022 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3023 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3025 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3026 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3027 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3028 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3029 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3030 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3033 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3034 let zero_fees = RoutingFees {
3036 proportional_millionths: 0,
3038 vec![RouteHint(vec![RouteHintHop {
3039 src_node_id: nodes[3],
3040 short_channel_id: 8,
3042 cltv_expiry_delta: (8 << 4) | 1,
3043 htlc_minimum_msat: None,
3044 htlc_maximum_msat: None,
3046 ]), RouteHint(vec![RouteHintHop {
3047 src_node_id: nodes[4],
3048 short_channel_id: 9,
3051 proportional_millionths: 0,
3053 cltv_expiry_delta: (9 << 4) | 1,
3054 htlc_minimum_msat: None,
3055 htlc_maximum_msat: None,
3056 }]), RouteHint(vec![RouteHintHop {
3057 src_node_id: nodes[5],
3058 short_channel_id: 10,
3060 cltv_expiry_delta: (10 << 4) | 1,
3061 htlc_minimum_msat: None,
3062 htlc_maximum_msat: None,
3066 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3067 let zero_fees = RoutingFees {
3069 proportional_millionths: 0,
3071 vec![RouteHint(vec![RouteHintHop {
3072 src_node_id: nodes[2],
3073 short_channel_id: 5,
3076 proportional_millionths: 0,
3078 cltv_expiry_delta: (5 << 4) | 1,
3079 htlc_minimum_msat: None,
3080 htlc_maximum_msat: None,
3082 src_node_id: nodes[3],
3083 short_channel_id: 8,
3085 cltv_expiry_delta: (8 << 4) | 1,
3086 htlc_minimum_msat: None,
3087 htlc_maximum_msat: None,
3089 ]), RouteHint(vec![RouteHintHop {
3090 src_node_id: nodes[4],
3091 short_channel_id: 9,
3094 proportional_millionths: 0,
3096 cltv_expiry_delta: (9 << 4) | 1,
3097 htlc_minimum_msat: None,
3098 htlc_maximum_msat: None,
3099 }]), RouteHint(vec![RouteHintHop {
3100 src_node_id: nodes[5],
3101 short_channel_id: 10,
3103 cltv_expiry_delta: (10 << 4) | 1,
3104 htlc_minimum_msat: None,
3105 htlc_maximum_msat: None,
3110 fn partial_route_hint_test() {
3111 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3112 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3113 let scorer = ln_test_utils::TestScorer::new();
3114 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3115 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3117 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3118 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3119 // RouteHint may be partially used by the algo to build the best path.
3121 // First check that last hop can't have its source as the payee.
3122 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3123 src_node_id: nodes[6],
3124 short_channel_id: 8,
3127 proportional_millionths: 0,
3129 cltv_expiry_delta: (8 << 4) | 1,
3130 htlc_minimum_msat: None,
3131 htlc_maximum_msat: None,
3134 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3135 invalid_last_hops.push(invalid_last_hop);
3137 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3138 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3139 assert_eq!(err, "Route hint cannot have the payee as the source.");
3140 } else { panic!(); }
3143 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3144 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3145 assert_eq!(route.paths[0].hops.len(), 5);
3147 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3148 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3149 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3150 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3151 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3152 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3154 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3155 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3156 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3157 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3158 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3159 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3161 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3162 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3163 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3164 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3165 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3166 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3168 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3169 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3170 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3171 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3172 // If we have a peer in the node map, we'll use their features here since we don't have
3173 // a way of figuring out their features from the invoice:
3174 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3175 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3177 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3178 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3179 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3180 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3181 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3182 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3185 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3186 let zero_fees = RoutingFees {
3188 proportional_millionths: 0,
3190 vec![RouteHint(vec![RouteHintHop {
3191 src_node_id: nodes[3],
3192 short_channel_id: 8,
3194 cltv_expiry_delta: (8 << 4) | 1,
3195 htlc_minimum_msat: None,
3196 htlc_maximum_msat: None,
3197 }]), RouteHint(vec![
3199 ]), RouteHint(vec![RouteHintHop {
3200 src_node_id: nodes[5],
3201 short_channel_id: 10,
3203 cltv_expiry_delta: (10 << 4) | 1,
3204 htlc_minimum_msat: None,
3205 htlc_maximum_msat: None,
3210 fn ignores_empty_last_hops_test() {
3211 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3212 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3213 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3214 let scorer = ln_test_utils::TestScorer::new();
3215 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3216 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3218 // Test handling of an empty RouteHint passed in Invoice.
3220 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3221 assert_eq!(route.paths[0].hops.len(), 5);
3223 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3224 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3225 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3226 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3227 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3228 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3230 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3231 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3232 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3233 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3234 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3235 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3237 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3238 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3239 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3240 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3241 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3242 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3244 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3245 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3246 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3247 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3248 // If we have a peer in the node map, we'll use their features here since we don't have
3249 // a way of figuring out their features from the invoice:
3250 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3251 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3253 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3254 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3255 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3256 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3257 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3258 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3261 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3263 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3264 let zero_fees = RoutingFees {
3266 proportional_millionths: 0,
3268 vec![RouteHint(vec![RouteHintHop {
3269 src_node_id: hint_hops[0],
3270 short_channel_id: 0xff00,
3273 proportional_millionths: 0,
3275 cltv_expiry_delta: (5 << 4) | 1,
3276 htlc_minimum_msat: None,
3277 htlc_maximum_msat: None,
3279 src_node_id: hint_hops[1],
3280 short_channel_id: 0xff01,
3282 cltv_expiry_delta: (8 << 4) | 1,
3283 htlc_minimum_msat: None,
3284 htlc_maximum_msat: None,
3289 fn multi_hint_last_hops_test() {
3290 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3291 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3292 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3293 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3294 let scorer = ln_test_utils::TestScorer::new();
3295 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3296 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3297 // Test through channels 2, 3, 0xff00, 0xff01.
3298 // Test shows that multiple hop hints are considered.
3300 // Disabling channels 6 & 7 by flags=2
3301 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3302 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3303 short_channel_id: 6,
3305 flags: 2, // to disable
3306 cltv_expiry_delta: 0,
3307 htlc_minimum_msat: 0,
3308 htlc_maximum_msat: MAX_VALUE_MSAT,
3310 fee_proportional_millionths: 0,
3311 excess_data: Vec::new()
3313 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3314 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3315 short_channel_id: 7,
3317 flags: 2, // to disable
3318 cltv_expiry_delta: 0,
3319 htlc_minimum_msat: 0,
3320 htlc_maximum_msat: MAX_VALUE_MSAT,
3322 fee_proportional_millionths: 0,
3323 excess_data: Vec::new()
3326 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3327 assert_eq!(route.paths[0].hops.len(), 4);
3329 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3330 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3331 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3332 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3333 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3334 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3336 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3337 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3338 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3339 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3340 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3341 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3343 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3344 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3345 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3346 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3347 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3348 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3350 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3351 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3352 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3353 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3354 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3355 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3359 fn private_multi_hint_last_hops_test() {
3360 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3361 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3363 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3364 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3366 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3367 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3368 let scorer = ln_test_utils::TestScorer::new();
3369 // Test through channels 2, 3, 0xff00, 0xff01.
3370 // Test shows that multiple hop hints are considered.
3372 // Disabling channels 6 & 7 by flags=2
3373 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3374 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3375 short_channel_id: 6,
3377 flags: 2, // to disable
3378 cltv_expiry_delta: 0,
3379 htlc_minimum_msat: 0,
3380 htlc_maximum_msat: MAX_VALUE_MSAT,
3382 fee_proportional_millionths: 0,
3383 excess_data: Vec::new()
3385 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3387 short_channel_id: 7,
3389 flags: 2, // to disable
3390 cltv_expiry_delta: 0,
3391 htlc_minimum_msat: 0,
3392 htlc_maximum_msat: MAX_VALUE_MSAT,
3394 fee_proportional_millionths: 0,
3395 excess_data: Vec::new()
3398 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3399 assert_eq!(route.paths[0].hops.len(), 4);
3401 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3402 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3403 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3404 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3405 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3406 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3408 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3409 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3410 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3411 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3412 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3413 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3415 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3416 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3417 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3418 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3419 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3420 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3422 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3423 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3424 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3425 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3426 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3427 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3430 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3431 let zero_fees = RoutingFees {
3433 proportional_millionths: 0,
3435 vec![RouteHint(vec![RouteHintHop {
3436 src_node_id: nodes[4],
3437 short_channel_id: 11,
3439 cltv_expiry_delta: (11 << 4) | 1,
3440 htlc_minimum_msat: None,
3441 htlc_maximum_msat: None,
3443 src_node_id: nodes[3],
3444 short_channel_id: 8,
3446 cltv_expiry_delta: (8 << 4) | 1,
3447 htlc_minimum_msat: None,
3448 htlc_maximum_msat: None,
3449 }]), RouteHint(vec![RouteHintHop {
3450 src_node_id: nodes[4],
3451 short_channel_id: 9,
3454 proportional_millionths: 0,
3456 cltv_expiry_delta: (9 << 4) | 1,
3457 htlc_minimum_msat: None,
3458 htlc_maximum_msat: None,
3459 }]), RouteHint(vec![RouteHintHop {
3460 src_node_id: nodes[5],
3461 short_channel_id: 10,
3463 cltv_expiry_delta: (10 << 4) | 1,
3464 htlc_minimum_msat: None,
3465 htlc_maximum_msat: None,
3470 fn last_hops_with_public_channel_test() {
3471 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3472 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3473 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3474 let scorer = ln_test_utils::TestScorer::new();
3475 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3476 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3477 // This test shows that public routes can be present in the invoice
3478 // which would be handled in the same manner.
3480 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3481 assert_eq!(route.paths[0].hops.len(), 5);
3483 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3484 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3485 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3486 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3487 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3488 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3490 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3491 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3492 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3493 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3494 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3495 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3497 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3498 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3499 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3500 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3501 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3502 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3504 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3505 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3506 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3507 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3508 // If we have a peer in the node map, we'll use their features here since we don't have
3509 // a way of figuring out their features from the invoice:
3510 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3511 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3513 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3514 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3515 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3516 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3517 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3518 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3522 fn our_chans_last_hop_connect_test() {
3523 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3524 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3525 let scorer = ln_test_utils::TestScorer::new();
3526 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3527 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3529 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3530 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3531 let mut last_hops = last_hops(&nodes);
3532 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3533 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3534 assert_eq!(route.paths[0].hops.len(), 2);
3536 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3537 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3538 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3539 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3540 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3541 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3543 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3544 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3545 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3546 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3547 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3548 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3550 last_hops[0].0[0].fees.base_msat = 1000;
3552 // Revert to via 6 as the fee on 8 goes up
3553 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3554 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3555 assert_eq!(route.paths[0].hops.len(), 4);
3557 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3558 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3559 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3560 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3561 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3562 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3564 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3565 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3566 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3567 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3568 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3569 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3571 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3572 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3573 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3574 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3575 // If we have a peer in the node map, we'll use their features here since we don't have
3576 // a way of figuring out their features from the invoice:
3577 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3578 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3580 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3581 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3582 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3583 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3584 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3585 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3587 // ...but still use 8 for larger payments as 6 has a variable feerate
3588 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3589 assert_eq!(route.paths[0].hops.len(), 5);
3591 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3592 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3593 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3594 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3595 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3596 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3598 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3599 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3600 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3601 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3602 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3603 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3605 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3606 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3607 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3608 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3609 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3610 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3612 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3613 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3614 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3615 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3616 // If we have a peer in the node map, we'll use their features here since we don't have
3617 // a way of figuring out their features from the invoice:
3618 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3619 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3621 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3622 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3623 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3624 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3625 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3626 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3629 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> {
3630 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3631 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3632 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3634 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3635 let last_hops = RouteHint(vec![RouteHintHop {
3636 src_node_id: middle_node_id,
3637 short_channel_id: 8,
3640 proportional_millionths: last_hop_fee_prop,
3642 cltv_expiry_delta: (8 << 4) | 1,
3643 htlc_minimum_msat: None,
3644 htlc_maximum_msat: last_hop_htlc_max,
3646 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3647 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3648 let scorer = ln_test_utils::TestScorer::new();
3649 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3650 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3651 let logger = ln_test_utils::TestLogger::new();
3652 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3653 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3654 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3659 fn unannounced_path_test() {
3660 // We should be able to send a payment to a destination without any help of a routing graph
3661 // if we have a channel with a common counterparty that appears in the first and last hop
3663 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3665 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3666 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3667 assert_eq!(route.paths[0].hops.len(), 2);
3669 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3670 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3671 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3672 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3673 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3674 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3676 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3677 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3678 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3679 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3680 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3681 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3685 fn overflow_unannounced_path_test_liquidity_underflow() {
3686 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3687 // the last-hop had a fee which overflowed a u64, we'd panic.
3688 // This was due to us adding the first-hop from us unconditionally, causing us to think
3689 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3690 // In this test, we previously hit a subtraction underflow due to having less available
3691 // liquidity at the last hop than 0.
3692 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());
3696 fn overflow_unannounced_path_test_feerate_overflow() {
3697 // This tests for the same case as above, except instead of hitting a subtraction
3698 // underflow, we hit a case where the fee charged at a hop overflowed.
3699 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());
3703 fn available_amount_while_routing_test() {
3704 // Tests whether we choose the correct available channel amount while routing.
3706 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3707 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3708 let scorer = ln_test_utils::TestScorer::new();
3709 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3710 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3711 let config = UserConfig::default();
3712 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3714 // We will use a simple single-path route from
3715 // our node to node2 via node0: channels {1, 3}.
3717 // First disable all other paths.
3718 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3719 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3720 short_channel_id: 2,
3723 cltv_expiry_delta: 0,
3724 htlc_minimum_msat: 0,
3725 htlc_maximum_msat: 100_000,
3727 fee_proportional_millionths: 0,
3728 excess_data: Vec::new()
3730 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3731 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3732 short_channel_id: 12,
3735 cltv_expiry_delta: 0,
3736 htlc_minimum_msat: 0,
3737 htlc_maximum_msat: 100_000,
3739 fee_proportional_millionths: 0,
3740 excess_data: Vec::new()
3743 // Make the first channel (#1) very permissive,
3744 // and we will be testing all limits on the second channel.
3745 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3747 short_channel_id: 1,
3750 cltv_expiry_delta: 0,
3751 htlc_minimum_msat: 0,
3752 htlc_maximum_msat: 1_000_000_000,
3754 fee_proportional_millionths: 0,
3755 excess_data: Vec::new()
3758 // First, let's see if routing works if we have absolutely no idea about the available amount.
3759 // In this case, it should be set to 250_000 sats.
3760 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3762 short_channel_id: 3,
3765 cltv_expiry_delta: 0,
3766 htlc_minimum_msat: 0,
3767 htlc_maximum_msat: 250_000_000,
3769 fee_proportional_millionths: 0,
3770 excess_data: Vec::new()
3774 // Attempt to route more than available results in a failure.
3775 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3776 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3777 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3778 } else { panic!(); }
3782 // Now, attempt to route an exact amount we have should be fine.
3783 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3784 assert_eq!(route.paths.len(), 1);
3785 let path = route.paths.last().unwrap();
3786 assert_eq!(path.hops.len(), 2);
3787 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3788 assert_eq!(path.final_value_msat(), 250_000_000);
3791 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3792 // Disable channel #1 and use another first hop.
3793 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3795 short_channel_id: 1,
3798 cltv_expiry_delta: 0,
3799 htlc_minimum_msat: 0,
3800 htlc_maximum_msat: 1_000_000_000,
3802 fee_proportional_millionths: 0,
3803 excess_data: Vec::new()
3806 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3807 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3810 // Attempt to route more than available results in a failure.
3811 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3812 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3813 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3814 } else { panic!(); }
3818 // Now, attempt to route an exact amount we have should be fine.
3819 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3820 assert_eq!(route.paths.len(), 1);
3821 let path = route.paths.last().unwrap();
3822 assert_eq!(path.hops.len(), 2);
3823 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3824 assert_eq!(path.final_value_msat(), 200_000_000);
3827 // Enable channel #1 back.
3828 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3829 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3830 short_channel_id: 1,
3833 cltv_expiry_delta: 0,
3834 htlc_minimum_msat: 0,
3835 htlc_maximum_msat: 1_000_000_000,
3837 fee_proportional_millionths: 0,
3838 excess_data: Vec::new()
3842 // Now let's see if routing works if we know only htlc_maximum_msat.
3843 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3844 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3845 short_channel_id: 3,
3848 cltv_expiry_delta: 0,
3849 htlc_minimum_msat: 0,
3850 htlc_maximum_msat: 15_000,
3852 fee_proportional_millionths: 0,
3853 excess_data: Vec::new()
3857 // Attempt to route more than available results in a failure.
3858 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3859 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3860 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3861 } else { panic!(); }
3865 // Now, attempt to route an exact amount we have should be fine.
3866 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3867 assert_eq!(route.paths.len(), 1);
3868 let path = route.paths.last().unwrap();
3869 assert_eq!(path.hops.len(), 2);
3870 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3871 assert_eq!(path.final_value_msat(), 15_000);
3874 // Now let's see if routing works if we know only capacity from the UTXO.
3876 // We can't change UTXO capacity on the fly, so we'll disable
3877 // the existing channel and add another one with the capacity we need.
3878 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3879 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3880 short_channel_id: 3,
3883 cltv_expiry_delta: 0,
3884 htlc_minimum_msat: 0,
3885 htlc_maximum_msat: MAX_VALUE_MSAT,
3887 fee_proportional_millionths: 0,
3888 excess_data: Vec::new()
3891 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3892 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3893 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3894 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3895 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3897 *chain_monitor.utxo_ret.lock().unwrap() =
3898 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
3899 gossip_sync.add_utxo_lookup(Some(chain_monitor));
3901 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3902 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3904 short_channel_id: 333,
3907 cltv_expiry_delta: (3 << 4) | 1,
3908 htlc_minimum_msat: 0,
3909 htlc_maximum_msat: 15_000,
3911 fee_proportional_millionths: 0,
3912 excess_data: Vec::new()
3914 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3916 short_channel_id: 333,
3919 cltv_expiry_delta: (3 << 4) | 2,
3920 htlc_minimum_msat: 0,
3921 htlc_maximum_msat: 15_000,
3923 fee_proportional_millionths: 0,
3924 excess_data: Vec::new()
3928 // Attempt to route more than available results in a failure.
3929 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3930 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3931 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3932 } else { panic!(); }
3936 // Now, attempt to route an exact amount we have should be fine.
3937 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3938 assert_eq!(route.paths.len(), 1);
3939 let path = route.paths.last().unwrap();
3940 assert_eq!(path.hops.len(), 2);
3941 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3942 assert_eq!(path.final_value_msat(), 15_000);
3945 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3946 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3947 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3948 short_channel_id: 333,
3951 cltv_expiry_delta: 0,
3952 htlc_minimum_msat: 0,
3953 htlc_maximum_msat: 10_000,
3955 fee_proportional_millionths: 0,
3956 excess_data: Vec::new()
3960 // Attempt to route more than available results in a failure.
3961 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3962 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3963 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3964 } else { panic!(); }
3968 // Now, attempt to route an exact amount we have should be fine.
3969 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3970 assert_eq!(route.paths.len(), 1);
3971 let path = route.paths.last().unwrap();
3972 assert_eq!(path.hops.len(), 2);
3973 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3974 assert_eq!(path.final_value_msat(), 10_000);
3979 fn available_liquidity_last_hop_test() {
3980 // Check that available liquidity properly limits the path even when only
3981 // one of the latter hops is limited.
3982 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3983 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3984 let scorer = ln_test_utils::TestScorer::new();
3985 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3986 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3987 let config = UserConfig::default();
3988 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3990 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3991 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3992 // Total capacity: 50 sats.
3994 // Disable other potential paths.
3995 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3996 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3997 short_channel_id: 2,
4000 cltv_expiry_delta: 0,
4001 htlc_minimum_msat: 0,
4002 htlc_maximum_msat: 100_000,
4004 fee_proportional_millionths: 0,
4005 excess_data: Vec::new()
4007 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4009 short_channel_id: 7,
4012 cltv_expiry_delta: 0,
4013 htlc_minimum_msat: 0,
4014 htlc_maximum_msat: 100_000,
4016 fee_proportional_millionths: 0,
4017 excess_data: Vec::new()
4022 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4024 short_channel_id: 12,
4027 cltv_expiry_delta: 0,
4028 htlc_minimum_msat: 0,
4029 htlc_maximum_msat: 100_000,
4031 fee_proportional_millionths: 0,
4032 excess_data: Vec::new()
4034 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4036 short_channel_id: 13,
4039 cltv_expiry_delta: 0,
4040 htlc_minimum_msat: 0,
4041 htlc_maximum_msat: 100_000,
4043 fee_proportional_millionths: 0,
4044 excess_data: Vec::new()
4047 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4048 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4049 short_channel_id: 6,
4052 cltv_expiry_delta: 0,
4053 htlc_minimum_msat: 0,
4054 htlc_maximum_msat: 50_000,
4056 fee_proportional_millionths: 0,
4057 excess_data: Vec::new()
4059 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4061 short_channel_id: 11,
4064 cltv_expiry_delta: 0,
4065 htlc_minimum_msat: 0,
4066 htlc_maximum_msat: 100_000,
4068 fee_proportional_millionths: 0,
4069 excess_data: Vec::new()
4072 // Attempt to route more than available results in a failure.
4073 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4074 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4075 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4076 } else { panic!(); }
4080 // Now, attempt to route 49 sats (just a bit below the capacity).
4081 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4082 assert_eq!(route.paths.len(), 1);
4083 let mut total_amount_paid_msat = 0;
4084 for path in &route.paths {
4085 assert_eq!(path.hops.len(), 4);
4086 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4087 total_amount_paid_msat += path.final_value_msat();
4089 assert_eq!(total_amount_paid_msat, 49_000);
4093 // Attempt to route an exact amount is also fine
4094 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4095 assert_eq!(route.paths.len(), 1);
4096 let mut total_amount_paid_msat = 0;
4097 for path in &route.paths {
4098 assert_eq!(path.hops.len(), 4);
4099 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4100 total_amount_paid_msat += path.final_value_msat();
4102 assert_eq!(total_amount_paid_msat, 50_000);
4107 fn ignore_fee_first_hop_test() {
4108 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4109 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4110 let scorer = ln_test_utils::TestScorer::new();
4111 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4112 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4113 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4115 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4116 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4118 short_channel_id: 1,
4121 cltv_expiry_delta: 0,
4122 htlc_minimum_msat: 0,
4123 htlc_maximum_msat: 100_000,
4124 fee_base_msat: 1_000_000,
4125 fee_proportional_millionths: 0,
4126 excess_data: Vec::new()
4128 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4129 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4130 short_channel_id: 3,
4133 cltv_expiry_delta: 0,
4134 htlc_minimum_msat: 0,
4135 htlc_maximum_msat: 50_000,
4137 fee_proportional_millionths: 0,
4138 excess_data: Vec::new()
4142 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4143 assert_eq!(route.paths.len(), 1);
4144 let mut total_amount_paid_msat = 0;
4145 for path in &route.paths {
4146 assert_eq!(path.hops.len(), 2);
4147 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4148 total_amount_paid_msat += path.final_value_msat();
4150 assert_eq!(total_amount_paid_msat, 50_000);
4155 fn simple_mpp_route_test() {
4156 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4157 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4158 let scorer = ln_test_utils::TestScorer::new();
4159 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4160 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4161 let config = UserConfig::default();
4162 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4163 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4165 // We need a route consisting of 3 paths:
4166 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4167 // To achieve this, the amount being transferred should be around
4168 // the total capacity of these 3 paths.
4170 // First, we set limits on these (previously unlimited) channels.
4171 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4173 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4174 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4176 short_channel_id: 1,
4179 cltv_expiry_delta: 0,
4180 htlc_minimum_msat: 0,
4181 htlc_maximum_msat: 100_000,
4183 fee_proportional_millionths: 0,
4184 excess_data: Vec::new()
4186 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4188 short_channel_id: 3,
4191 cltv_expiry_delta: 0,
4192 htlc_minimum_msat: 0,
4193 htlc_maximum_msat: 50_000,
4195 fee_proportional_millionths: 0,
4196 excess_data: Vec::new()
4199 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4200 // (total limit 60).
4201 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4202 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4203 short_channel_id: 12,
4206 cltv_expiry_delta: 0,
4207 htlc_minimum_msat: 0,
4208 htlc_maximum_msat: 60_000,
4210 fee_proportional_millionths: 0,
4211 excess_data: Vec::new()
4213 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4214 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4215 short_channel_id: 13,
4218 cltv_expiry_delta: 0,
4219 htlc_minimum_msat: 0,
4220 htlc_maximum_msat: 60_000,
4222 fee_proportional_millionths: 0,
4223 excess_data: Vec::new()
4226 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4227 // (total capacity 180 sats).
4228 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4229 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4230 short_channel_id: 2,
4233 cltv_expiry_delta: 0,
4234 htlc_minimum_msat: 0,
4235 htlc_maximum_msat: 200_000,
4237 fee_proportional_millionths: 0,
4238 excess_data: Vec::new()
4240 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4241 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4242 short_channel_id: 4,
4245 cltv_expiry_delta: 0,
4246 htlc_minimum_msat: 0,
4247 htlc_maximum_msat: 180_000,
4249 fee_proportional_millionths: 0,
4250 excess_data: Vec::new()
4254 // Attempt to route more than available results in a failure.
4255 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4256 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4257 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4258 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4259 } else { panic!(); }
4263 // Attempt to route while setting max_path_count to 0 results in a failure.
4264 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4265 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4266 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4267 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4268 assert_eq!(err, "Can't find a route with no paths allowed.");
4269 } else { panic!(); }
4273 // Attempt to route while setting max_path_count to 3 results in a failure.
4274 // This is the case because the minimal_value_contribution_msat would require each path
4275 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4276 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4277 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4278 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4279 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4280 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4281 } else { panic!(); }
4285 // Now, attempt to route 250 sats (just a bit below the capacity).
4286 // Our algorithm should provide us with these 3 paths.
4287 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4288 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4289 assert_eq!(route.paths.len(), 3);
4290 let mut total_amount_paid_msat = 0;
4291 for path in &route.paths {
4292 assert_eq!(path.hops.len(), 2);
4293 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4294 total_amount_paid_msat += path.final_value_msat();
4296 assert_eq!(total_amount_paid_msat, 250_000);
4300 // Attempt to route an exact amount is also fine
4301 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4302 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4303 assert_eq!(route.paths.len(), 3);
4304 let mut total_amount_paid_msat = 0;
4305 for path in &route.paths {
4306 assert_eq!(path.hops.len(), 2);
4307 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4308 total_amount_paid_msat += path.final_value_msat();
4310 assert_eq!(total_amount_paid_msat, 290_000);
4315 fn long_mpp_route_test() {
4316 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4317 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4318 let scorer = ln_test_utils::TestScorer::new();
4319 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4320 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4321 let config = UserConfig::default();
4322 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4324 // We need a route consisting of 3 paths:
4325 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4326 // Note that these paths overlap (channels 5, 12, 13).
4327 // We will route 300 sats.
4328 // Each path will have 100 sats capacity, those channels which
4329 // are used twice will have 200 sats capacity.
4331 // Disable other potential paths.
4332 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4334 short_channel_id: 2,
4337 cltv_expiry_delta: 0,
4338 htlc_minimum_msat: 0,
4339 htlc_maximum_msat: 100_000,
4341 fee_proportional_millionths: 0,
4342 excess_data: Vec::new()
4344 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4346 short_channel_id: 7,
4349 cltv_expiry_delta: 0,
4350 htlc_minimum_msat: 0,
4351 htlc_maximum_msat: 100_000,
4353 fee_proportional_millionths: 0,
4354 excess_data: Vec::new()
4357 // Path via {node0, node2} is channels {1, 3, 5}.
4358 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4359 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4360 short_channel_id: 1,
4363 cltv_expiry_delta: 0,
4364 htlc_minimum_msat: 0,
4365 htlc_maximum_msat: 100_000,
4367 fee_proportional_millionths: 0,
4368 excess_data: Vec::new()
4370 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4372 short_channel_id: 3,
4375 cltv_expiry_delta: 0,
4376 htlc_minimum_msat: 0,
4377 htlc_maximum_msat: 100_000,
4379 fee_proportional_millionths: 0,
4380 excess_data: Vec::new()
4383 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4384 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4385 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4387 short_channel_id: 5,
4390 cltv_expiry_delta: 0,
4391 htlc_minimum_msat: 0,
4392 htlc_maximum_msat: 200_000,
4394 fee_proportional_millionths: 0,
4395 excess_data: Vec::new()
4398 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4399 // Add 100 sats to the capacities of {12, 13}, because these channels
4400 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4401 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4402 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4403 short_channel_id: 12,
4406 cltv_expiry_delta: 0,
4407 htlc_minimum_msat: 0,
4408 htlc_maximum_msat: 200_000,
4410 fee_proportional_millionths: 0,
4411 excess_data: Vec::new()
4413 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4415 short_channel_id: 13,
4418 cltv_expiry_delta: 0,
4419 htlc_minimum_msat: 0,
4420 htlc_maximum_msat: 200_000,
4422 fee_proportional_millionths: 0,
4423 excess_data: Vec::new()
4426 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4428 short_channel_id: 6,
4431 cltv_expiry_delta: 0,
4432 htlc_minimum_msat: 0,
4433 htlc_maximum_msat: 100_000,
4435 fee_proportional_millionths: 0,
4436 excess_data: Vec::new()
4438 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4439 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4440 short_channel_id: 11,
4443 cltv_expiry_delta: 0,
4444 htlc_minimum_msat: 0,
4445 htlc_maximum_msat: 100_000,
4447 fee_proportional_millionths: 0,
4448 excess_data: Vec::new()
4451 // Path via {node7, node2} is channels {12, 13, 5}.
4452 // We already limited them to 200 sats (they are used twice for 100 sats).
4453 // Nothing to do here.
4456 // Attempt to route more than available results in a failure.
4457 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4458 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4459 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4460 } else { panic!(); }
4464 // Now, attempt to route 300 sats (exact amount we can route).
4465 // Our algorithm should provide us with these 3 paths, 100 sats each.
4466 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4467 assert_eq!(route.paths.len(), 3);
4469 let mut total_amount_paid_msat = 0;
4470 for path in &route.paths {
4471 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4472 total_amount_paid_msat += path.final_value_msat();
4474 assert_eq!(total_amount_paid_msat, 300_000);
4480 fn mpp_cheaper_route_test() {
4481 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4482 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4483 let scorer = ln_test_utils::TestScorer::new();
4484 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4485 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4486 let config = UserConfig::default();
4487 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4489 // This test checks that if we have two cheaper paths and one more expensive path,
4490 // so that liquidity-wise any 2 of 3 combination is sufficient,
4491 // two cheaper paths will be taken.
4492 // These paths have equal available liquidity.
4494 // We need a combination of 3 paths:
4495 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4496 // Note that these paths overlap (channels 5, 12, 13).
4497 // Each path will have 100 sats capacity, those channels which
4498 // are used twice will have 200 sats capacity.
4500 // Disable other potential paths.
4501 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4503 short_channel_id: 2,
4506 cltv_expiry_delta: 0,
4507 htlc_minimum_msat: 0,
4508 htlc_maximum_msat: 100_000,
4510 fee_proportional_millionths: 0,
4511 excess_data: Vec::new()
4513 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4515 short_channel_id: 7,
4518 cltv_expiry_delta: 0,
4519 htlc_minimum_msat: 0,
4520 htlc_maximum_msat: 100_000,
4522 fee_proportional_millionths: 0,
4523 excess_data: Vec::new()
4526 // Path via {node0, node2} is channels {1, 3, 5}.
4527 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4529 short_channel_id: 1,
4532 cltv_expiry_delta: 0,
4533 htlc_minimum_msat: 0,
4534 htlc_maximum_msat: 100_000,
4536 fee_proportional_millionths: 0,
4537 excess_data: Vec::new()
4539 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4541 short_channel_id: 3,
4544 cltv_expiry_delta: 0,
4545 htlc_minimum_msat: 0,
4546 htlc_maximum_msat: 100_000,
4548 fee_proportional_millionths: 0,
4549 excess_data: Vec::new()
4552 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4553 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4554 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4556 short_channel_id: 5,
4559 cltv_expiry_delta: 0,
4560 htlc_minimum_msat: 0,
4561 htlc_maximum_msat: 200_000,
4563 fee_proportional_millionths: 0,
4564 excess_data: Vec::new()
4567 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4568 // Add 100 sats to the capacities of {12, 13}, because these channels
4569 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4570 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4572 short_channel_id: 12,
4575 cltv_expiry_delta: 0,
4576 htlc_minimum_msat: 0,
4577 htlc_maximum_msat: 200_000,
4579 fee_proportional_millionths: 0,
4580 excess_data: Vec::new()
4582 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4583 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4584 short_channel_id: 13,
4587 cltv_expiry_delta: 0,
4588 htlc_minimum_msat: 0,
4589 htlc_maximum_msat: 200_000,
4591 fee_proportional_millionths: 0,
4592 excess_data: Vec::new()
4595 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4597 short_channel_id: 6,
4600 cltv_expiry_delta: 0,
4601 htlc_minimum_msat: 0,
4602 htlc_maximum_msat: 100_000,
4603 fee_base_msat: 1_000,
4604 fee_proportional_millionths: 0,
4605 excess_data: Vec::new()
4607 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4608 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4609 short_channel_id: 11,
4612 cltv_expiry_delta: 0,
4613 htlc_minimum_msat: 0,
4614 htlc_maximum_msat: 100_000,
4616 fee_proportional_millionths: 0,
4617 excess_data: Vec::new()
4620 // Path via {node7, node2} is channels {12, 13, 5}.
4621 // We already limited them to 200 sats (they are used twice for 100 sats).
4622 // Nothing to do here.
4625 // Now, attempt to route 180 sats.
4626 // Our algorithm should provide us with these 2 paths.
4627 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4628 assert_eq!(route.paths.len(), 2);
4630 let mut total_value_transferred_msat = 0;
4631 let mut total_paid_msat = 0;
4632 for path in &route.paths {
4633 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4634 total_value_transferred_msat += path.final_value_msat();
4635 for hop in &path.hops {
4636 total_paid_msat += hop.fee_msat;
4639 // If we paid fee, this would be higher.
4640 assert_eq!(total_value_transferred_msat, 180_000);
4641 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4642 assert_eq!(total_fees_paid, 0);
4647 fn fees_on_mpp_route_test() {
4648 // This test makes sure that MPP algorithm properly takes into account
4649 // fees charged on the channels, by making the fees impactful:
4650 // if the fee is not properly accounted for, the behavior is different.
4651 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4652 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4653 let scorer = ln_test_utils::TestScorer::new();
4654 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4655 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4656 let config = UserConfig::default();
4657 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4659 // We need a route consisting of 2 paths:
4660 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4661 // We will route 200 sats, Each path will have 100 sats capacity.
4663 // This test is not particularly stable: e.g.,
4664 // there's a way to route via {node0, node2, node4}.
4665 // It works while pathfinding is deterministic, but can be broken otherwise.
4666 // It's fine to ignore this concern for now.
4668 // Disable other potential paths.
4669 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4671 short_channel_id: 2,
4674 cltv_expiry_delta: 0,
4675 htlc_minimum_msat: 0,
4676 htlc_maximum_msat: 100_000,
4678 fee_proportional_millionths: 0,
4679 excess_data: Vec::new()
4682 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4684 short_channel_id: 7,
4687 cltv_expiry_delta: 0,
4688 htlc_minimum_msat: 0,
4689 htlc_maximum_msat: 100_000,
4691 fee_proportional_millionths: 0,
4692 excess_data: Vec::new()
4695 // Path via {node0, node2} is channels {1, 3, 5}.
4696 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4698 short_channel_id: 1,
4701 cltv_expiry_delta: 0,
4702 htlc_minimum_msat: 0,
4703 htlc_maximum_msat: 100_000,
4705 fee_proportional_millionths: 0,
4706 excess_data: Vec::new()
4708 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4709 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4710 short_channel_id: 3,
4713 cltv_expiry_delta: 0,
4714 htlc_minimum_msat: 0,
4715 htlc_maximum_msat: 100_000,
4717 fee_proportional_millionths: 0,
4718 excess_data: Vec::new()
4721 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4722 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4724 short_channel_id: 5,
4727 cltv_expiry_delta: 0,
4728 htlc_minimum_msat: 0,
4729 htlc_maximum_msat: 100_000,
4731 fee_proportional_millionths: 0,
4732 excess_data: Vec::new()
4735 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4736 // All channels should be 100 sats capacity. But for the fee experiment,
4737 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4738 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4739 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4740 // so no matter how large are other channels,
4741 // the whole path will be limited by 100 sats with just these 2 conditions:
4742 // - channel 12 capacity is 250 sats
4743 // - fee for channel 6 is 150 sats
4744 // Let's test this by enforcing these 2 conditions and removing other limits.
4745 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4746 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4747 short_channel_id: 12,
4750 cltv_expiry_delta: 0,
4751 htlc_minimum_msat: 0,
4752 htlc_maximum_msat: 250_000,
4754 fee_proportional_millionths: 0,
4755 excess_data: Vec::new()
4757 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4758 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4759 short_channel_id: 13,
4762 cltv_expiry_delta: 0,
4763 htlc_minimum_msat: 0,
4764 htlc_maximum_msat: MAX_VALUE_MSAT,
4766 fee_proportional_millionths: 0,
4767 excess_data: Vec::new()
4770 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4772 short_channel_id: 6,
4775 cltv_expiry_delta: 0,
4776 htlc_minimum_msat: 0,
4777 htlc_maximum_msat: MAX_VALUE_MSAT,
4778 fee_base_msat: 150_000,
4779 fee_proportional_millionths: 0,
4780 excess_data: Vec::new()
4782 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4784 short_channel_id: 11,
4787 cltv_expiry_delta: 0,
4788 htlc_minimum_msat: 0,
4789 htlc_maximum_msat: MAX_VALUE_MSAT,
4791 fee_proportional_millionths: 0,
4792 excess_data: Vec::new()
4796 // Attempt to route more than available results in a failure.
4797 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4798 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4799 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4800 } else { panic!(); }
4804 // Now, attempt to route 200 sats (exact amount we can route).
4805 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4806 assert_eq!(route.paths.len(), 2);
4808 let mut total_amount_paid_msat = 0;
4809 for path in &route.paths {
4810 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4811 total_amount_paid_msat += path.final_value_msat();
4813 assert_eq!(total_amount_paid_msat, 200_000);
4814 assert_eq!(route.get_total_fees(), 150_000);
4819 fn mpp_with_last_hops() {
4820 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4821 // via a single last-hop route hint, we'd fail to route if we first collected routes
4822 // totaling close but not quite enough to fund the full payment.
4824 // This was because we considered last-hop hints to have exactly the sought payment amount
4825 // instead of the amount we were trying to collect, needlessly limiting our path searching
4826 // at the very first hop.
4828 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4829 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4830 // to only have the remaining to-collect amount in available liquidity.
4832 // This bug appeared in production in some specific channel configurations.
4833 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4834 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4835 let scorer = ln_test_utils::TestScorer::new();
4836 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4837 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4838 let config = UserConfig::default();
4839 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
4840 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4841 src_node_id: nodes[2],
4842 short_channel_id: 42,
4843 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4844 cltv_expiry_delta: 42,
4845 htlc_minimum_msat: None,
4846 htlc_maximum_msat: None,
4847 }])]).unwrap().with_max_channel_saturation_power_of_half(0);
4849 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4850 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4851 // would first use the no-fee route and then fail to find a path along the second route as
4852 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4853 // under 5% of our payment amount.
4854 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4856 short_channel_id: 1,
4859 cltv_expiry_delta: (5 << 4) | 5,
4860 htlc_minimum_msat: 0,
4861 htlc_maximum_msat: 99_000,
4862 fee_base_msat: u32::max_value(),
4863 fee_proportional_millionths: u32::max_value(),
4864 excess_data: Vec::new()
4866 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4868 short_channel_id: 2,
4871 cltv_expiry_delta: (5 << 4) | 3,
4872 htlc_minimum_msat: 0,
4873 htlc_maximum_msat: 99_000,
4874 fee_base_msat: u32::max_value(),
4875 fee_proportional_millionths: u32::max_value(),
4876 excess_data: Vec::new()
4878 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4879 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4880 short_channel_id: 4,
4883 cltv_expiry_delta: (4 << 4) | 1,
4884 htlc_minimum_msat: 0,
4885 htlc_maximum_msat: MAX_VALUE_MSAT,
4887 fee_proportional_millionths: 0,
4888 excess_data: Vec::new()
4890 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4892 short_channel_id: 13,
4894 flags: 0|2, // Channel disabled
4895 cltv_expiry_delta: (13 << 4) | 1,
4896 htlc_minimum_msat: 0,
4897 htlc_maximum_msat: MAX_VALUE_MSAT,
4899 fee_proportional_millionths: 2000000,
4900 excess_data: Vec::new()
4903 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4905 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4906 assert_eq!(route.paths.len(), 2);
4907 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
4908 // Paths are manually ordered ordered by SCID, so:
4909 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4910 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4911 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
4912 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4913 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
4914 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
4915 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
4916 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
4917 assert_eq!(route.get_total_fees(), 1);
4918 assert_eq!(route.get_total_amount(), 100_000);
4922 fn drop_lowest_channel_mpp_route_test() {
4923 // This test checks that low-capacity channel is dropped when after
4924 // path finding we realize that we found more capacity than we need.
4925 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4926 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4927 let scorer = ln_test_utils::TestScorer::new();
4928 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4929 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4930 let config = UserConfig::default();
4931 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
4932 .with_max_channel_saturation_power_of_half(0);
4934 // We need a route consisting of 3 paths:
4935 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4937 // The first and the second paths should be sufficient, but the third should be
4938 // cheaper, so that we select it but drop later.
4940 // First, we set limits on these (previously unlimited) channels.
4941 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4943 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4944 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4946 short_channel_id: 1,
4949 cltv_expiry_delta: 0,
4950 htlc_minimum_msat: 0,
4951 htlc_maximum_msat: 100_000,
4953 fee_proportional_millionths: 0,
4954 excess_data: Vec::new()
4956 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4958 short_channel_id: 3,
4961 cltv_expiry_delta: 0,
4962 htlc_minimum_msat: 0,
4963 htlc_maximum_msat: 50_000,
4965 fee_proportional_millionths: 0,
4966 excess_data: Vec::new()
4969 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4970 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4971 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4972 short_channel_id: 12,
4975 cltv_expiry_delta: 0,
4976 htlc_minimum_msat: 0,
4977 htlc_maximum_msat: 60_000,
4979 fee_proportional_millionths: 0,
4980 excess_data: Vec::new()
4982 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4984 short_channel_id: 13,
4987 cltv_expiry_delta: 0,
4988 htlc_minimum_msat: 0,
4989 htlc_maximum_msat: 60_000,
4991 fee_proportional_millionths: 0,
4992 excess_data: Vec::new()
4995 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4996 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4998 short_channel_id: 2,
5001 cltv_expiry_delta: 0,
5002 htlc_minimum_msat: 0,
5003 htlc_maximum_msat: 20_000,
5005 fee_proportional_millionths: 0,
5006 excess_data: Vec::new()
5008 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5009 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5010 short_channel_id: 4,
5013 cltv_expiry_delta: 0,
5014 htlc_minimum_msat: 0,
5015 htlc_maximum_msat: 20_000,
5017 fee_proportional_millionths: 0,
5018 excess_data: Vec::new()
5022 // Attempt to route more than available results in a failure.
5023 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5024 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5025 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5026 } else { panic!(); }
5030 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5031 // Our algorithm should provide us with these 3 paths.
5032 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5033 assert_eq!(route.paths.len(), 3);
5034 let mut total_amount_paid_msat = 0;
5035 for path in &route.paths {
5036 assert_eq!(path.hops.len(), 2);
5037 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5038 total_amount_paid_msat += path.final_value_msat();
5040 assert_eq!(total_amount_paid_msat, 125_000);
5044 // Attempt to route without the last small cheap channel
5045 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5046 assert_eq!(route.paths.len(), 2);
5047 let mut total_amount_paid_msat = 0;
5048 for path in &route.paths {
5049 assert_eq!(path.hops.len(), 2);
5050 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5051 total_amount_paid_msat += path.final_value_msat();
5053 assert_eq!(total_amount_paid_msat, 90_000);
5058 fn min_criteria_consistency() {
5059 // Test that we don't use an inconsistent metric between updating and walking nodes during
5060 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5061 // was updated with a different criterion from the heap sorting, resulting in loops in
5062 // calculated paths. We test for that specific case here.
5064 // We construct a network that looks like this:
5066 // node2 -1(3)2- node3
5070 // node1 -1(5)2- node4 -1(1)2- node6
5076 // We create a loop on the side of our real path - our destination is node 6, with a
5077 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5078 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5079 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5080 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5081 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5082 // "previous hop" being set to node 3, creating a loop in the path.
5083 let secp_ctx = Secp256k1::new();
5084 let logger = Arc::new(ln_test_utils::TestLogger::new());
5085 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5086 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5087 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5088 let scorer = ln_test_utils::TestScorer::new();
5089 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5090 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5091 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5093 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5094 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5095 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5096 short_channel_id: 6,
5099 cltv_expiry_delta: (6 << 4) | 0,
5100 htlc_minimum_msat: 0,
5101 htlc_maximum_msat: MAX_VALUE_MSAT,
5103 fee_proportional_millionths: 0,
5104 excess_data: Vec::new()
5106 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5108 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5109 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5110 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5111 short_channel_id: 5,
5114 cltv_expiry_delta: (5 << 4) | 0,
5115 htlc_minimum_msat: 0,
5116 htlc_maximum_msat: MAX_VALUE_MSAT,
5118 fee_proportional_millionths: 0,
5119 excess_data: Vec::new()
5121 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5123 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5124 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5125 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5126 short_channel_id: 4,
5129 cltv_expiry_delta: (4 << 4) | 0,
5130 htlc_minimum_msat: 0,
5131 htlc_maximum_msat: MAX_VALUE_MSAT,
5133 fee_proportional_millionths: 0,
5134 excess_data: Vec::new()
5136 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5138 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5139 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5140 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5141 short_channel_id: 3,
5144 cltv_expiry_delta: (3 << 4) | 0,
5145 htlc_minimum_msat: 0,
5146 htlc_maximum_msat: MAX_VALUE_MSAT,
5148 fee_proportional_millionths: 0,
5149 excess_data: Vec::new()
5151 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5153 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5154 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5155 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5156 short_channel_id: 2,
5159 cltv_expiry_delta: (2 << 4) | 0,
5160 htlc_minimum_msat: 0,
5161 htlc_maximum_msat: MAX_VALUE_MSAT,
5163 fee_proportional_millionths: 0,
5164 excess_data: Vec::new()
5167 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5168 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5170 short_channel_id: 1,
5173 cltv_expiry_delta: (1 << 4) | 0,
5174 htlc_minimum_msat: 100,
5175 htlc_maximum_msat: MAX_VALUE_MSAT,
5177 fee_proportional_millionths: 0,
5178 excess_data: Vec::new()
5180 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5183 // Now ensure the route flows simply over nodes 1 and 4 to 6.
5184 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5185 assert_eq!(route.paths.len(), 1);
5186 assert_eq!(route.paths[0].hops.len(), 3);
5188 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5189 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5190 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5191 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5192 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5193 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5195 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5196 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5197 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5198 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5199 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5200 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5202 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5203 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5204 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5205 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5206 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5207 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5213 fn exact_fee_liquidity_limit() {
5214 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5215 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5216 // we calculated fees on a higher value, resulting in us ignoring such paths.
5217 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5218 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5219 let scorer = ln_test_utils::TestScorer::new();
5220 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5221 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5222 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5224 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5226 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5227 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5228 short_channel_id: 2,
5231 cltv_expiry_delta: 0,
5232 htlc_minimum_msat: 0,
5233 htlc_maximum_msat: 85_000,
5235 fee_proportional_millionths: 0,
5236 excess_data: Vec::new()
5239 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5240 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5241 short_channel_id: 12,
5244 cltv_expiry_delta: (4 << 4) | 1,
5245 htlc_minimum_msat: 0,
5246 htlc_maximum_msat: 270_000,
5248 fee_proportional_millionths: 1000000,
5249 excess_data: Vec::new()
5253 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5254 // 200% fee charged channel 13 in the 1-to-2 direction.
5255 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5256 assert_eq!(route.paths.len(), 1);
5257 assert_eq!(route.paths[0].hops.len(), 2);
5259 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5260 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5261 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5262 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5263 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5264 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5266 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5267 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5268 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5269 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5270 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5271 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5276 fn htlc_max_reduction_below_min() {
5277 // Test that if, while walking the graph, we reduce the value being sent to meet an
5278 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5279 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5280 // resulting in us thinking there is no possible path, even if other paths exist.
5281 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5282 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5283 let scorer = ln_test_utils::TestScorer::new();
5284 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5285 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5286 let config = UserConfig::default();
5287 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5289 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5290 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5291 // then try to send 90_000.
5292 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5294 short_channel_id: 2,
5297 cltv_expiry_delta: 0,
5298 htlc_minimum_msat: 0,
5299 htlc_maximum_msat: 80_000,
5301 fee_proportional_millionths: 0,
5302 excess_data: Vec::new()
5304 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5305 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5306 short_channel_id: 4,
5309 cltv_expiry_delta: (4 << 4) | 1,
5310 htlc_minimum_msat: 90_000,
5311 htlc_maximum_msat: MAX_VALUE_MSAT,
5313 fee_proportional_millionths: 0,
5314 excess_data: Vec::new()
5318 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5319 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5320 // expensive) channels 12-13 path.
5321 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5322 assert_eq!(route.paths.len(), 1);
5323 assert_eq!(route.paths[0].hops.len(), 2);
5325 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5326 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5327 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5328 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5329 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5330 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5332 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5333 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5334 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5335 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5336 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5337 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5342 fn multiple_direct_first_hops() {
5343 // Previously we'd only ever considered one first hop path per counterparty.
5344 // However, as we don't restrict users to one channel per peer, we really need to support
5345 // looking at all first hop paths.
5346 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5347 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5348 // route over multiple channels with the same first hop.
5349 let secp_ctx = Secp256k1::new();
5350 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5351 let logger = Arc::new(ln_test_utils::TestLogger::new());
5352 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5353 let scorer = ln_test_utils::TestScorer::new();
5354 let config = UserConfig::default();
5355 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5356 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5357 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5360 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5361 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5362 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5363 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5364 assert_eq!(route.paths.len(), 1);
5365 assert_eq!(route.paths[0].hops.len(), 1);
5367 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5368 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5369 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5372 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5373 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5374 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5375 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5376 assert_eq!(route.paths.len(), 2);
5377 assert_eq!(route.paths[0].hops.len(), 1);
5378 assert_eq!(route.paths[1].hops.len(), 1);
5380 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5381 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5383 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5384 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5386 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5387 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5391 // If we have a bunch of outbound channels to the same node, where most are not
5392 // sufficient to pay the full payment, but one is, we should default to just using the
5393 // one single channel that has sufficient balance, avoiding MPP.
5395 // If we have several options above the 3xpayment value threshold, we should pick the
5396 // smallest of them, avoiding further fragmenting our available outbound balance to
5398 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5399 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5400 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5401 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5402 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5403 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5404 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5405 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5406 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5407 ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5408 assert_eq!(route.paths.len(), 1);
5409 assert_eq!(route.paths[0].hops.len(), 1);
5411 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5412 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5413 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5418 fn prefers_shorter_route_with_higher_fees() {
5419 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5420 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5421 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5423 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5424 let scorer = ln_test_utils::TestScorer::new();
5425 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5426 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5427 let route = get_route(
5428 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5429 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5431 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5433 assert_eq!(route.get_total_fees(), 100);
5434 assert_eq!(route.get_total_amount(), 100);
5435 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5437 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5438 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5439 let scorer = FixedPenaltyScorer::with_penalty(100);
5440 let route = get_route(
5441 &our_id, &payment_params, &network_graph.read_only(), None, 100,
5442 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5444 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5446 assert_eq!(route.get_total_fees(), 300);
5447 assert_eq!(route.get_total_amount(), 100);
5448 assert_eq!(path, vec![2, 4, 7, 10]);
5451 struct BadChannelScorer {
5452 short_channel_id: u64,
5456 impl Writeable for BadChannelScorer {
5457 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5459 impl Score for BadChannelScorer {
5460 type ScoreParams = ();
5461 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5462 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5465 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5466 fn payment_path_successful(&mut self, _path: &Path) {}
5467 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5468 fn probe_successful(&mut self, _path: &Path) {}
5471 struct BadNodeScorer {
5476 impl Writeable for BadNodeScorer {
5477 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5480 impl Score for BadNodeScorer {
5481 type ScoreParams = ();
5482 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5483 if *target == self.node_id { u64::max_value() } else { 0 }
5486 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5487 fn payment_path_successful(&mut self, _path: &Path) {}
5488 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5489 fn probe_successful(&mut self, _path: &Path) {}
5493 fn avoids_routing_through_bad_channels_and_nodes() {
5494 let (secp_ctx, network, _, _, logger) = build_graph();
5495 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5496 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5497 let network_graph = network.read_only();
5499 // A path to nodes[6] exists when no penalties are applied to any channel.
5500 let scorer = ln_test_utils::TestScorer::new();
5501 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5502 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5503 let route = get_route(
5504 &our_id, &payment_params, &network_graph, None, 100,
5505 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5507 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5509 assert_eq!(route.get_total_fees(), 100);
5510 assert_eq!(route.get_total_amount(), 100);
5511 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5513 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5514 let scorer = BadChannelScorer { short_channel_id: 6 };
5515 let route = get_route(
5516 &our_id, &payment_params, &network_graph, None, 100,
5517 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5519 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5521 assert_eq!(route.get_total_fees(), 300);
5522 assert_eq!(route.get_total_amount(), 100);
5523 assert_eq!(path, vec![2, 4, 7, 10]);
5525 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5526 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5528 &our_id, &payment_params, &network_graph, None, 100,
5529 Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5531 Err(LightningError { err, .. } ) => {
5532 assert_eq!(err, "Failed to find a path to the given destination");
5534 Ok(_) => panic!("Expected error"),
5539 fn total_fees_single_path() {
5541 paths: vec![Path { hops: vec![
5543 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5544 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5545 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5548 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5549 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5550 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5553 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5554 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5555 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5557 ], blinded_tail: None }],
5558 payment_params: None,
5561 assert_eq!(route.get_total_fees(), 250);
5562 assert_eq!(route.get_total_amount(), 225);
5566 fn total_fees_multi_path() {
5568 paths: vec![Path { hops: vec![
5570 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5571 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5572 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5575 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5576 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5577 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5579 ], blinded_tail: None }, Path { hops: vec![
5581 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5582 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5583 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5586 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5587 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5588 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5590 ], blinded_tail: None }],
5591 payment_params: None,
5594 assert_eq!(route.get_total_fees(), 200);
5595 assert_eq!(route.get_total_amount(), 300);
5599 fn total_empty_route_no_panic() {
5600 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5601 // would both panic if the route was completely empty. We test to ensure they return 0
5602 // here, even though its somewhat nonsensical as a route.
5603 let route = Route { paths: Vec::new(), payment_params: None };
5605 assert_eq!(route.get_total_fees(), 0);
5606 assert_eq!(route.get_total_amount(), 0);
5610 fn limits_total_cltv_delta() {
5611 let (secp_ctx, network, _, _, logger) = build_graph();
5612 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5613 let network_graph = network.read_only();
5615 let scorer = ln_test_utils::TestScorer::new();
5617 // Make sure that generally there is at least one route available
5618 let feasible_max_total_cltv_delta = 1008;
5619 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5620 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5621 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5622 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5623 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5624 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5625 assert_ne!(path.len(), 0);
5627 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5628 let fail_max_total_cltv_delta = 23;
5629 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5630 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5631 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5633 Err(LightningError { err, .. } ) => {
5634 assert_eq!(err, "Failed to find a path to the given destination");
5636 Ok(_) => panic!("Expected error"),
5641 fn avoids_recently_failed_paths() {
5642 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5643 // randomly inserting channels into it until we can't find a route anymore.
5644 let (secp_ctx, network, _, _, logger) = build_graph();
5645 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5646 let network_graph = network.read_only();
5648 let scorer = ln_test_utils::TestScorer::new();
5649 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5650 .with_max_path_count(1);
5651 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5652 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5654 // We should be able to find a route initially, and then after we fail a few random
5655 // channels eventually we won't be able to any longer.
5656 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5658 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5659 for chan in route.paths[0].hops.iter() {
5660 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5662 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5663 % route.paths[0].hops.len();
5664 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5670 fn limits_path_length() {
5671 let (secp_ctx, network, _, _, logger) = build_line_graph();
5672 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5673 let network_graph = network.read_only();
5675 let scorer = ln_test_utils::TestScorer::new();
5676 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5677 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5679 // First check we can actually create a long route on this graph.
5680 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5681 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5682 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5683 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5684 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5686 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5687 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5688 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5689 Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5691 Err(LightningError { err, .. } ) => {
5692 assert_eq!(err, "Failed to find a path to the given destination");
5694 Ok(_) => panic!("Expected error"),
5699 fn adds_and_limits_cltv_offset() {
5700 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5701 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5703 let scorer = ln_test_utils::TestScorer::new();
5705 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5706 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5707 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5708 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5709 assert_eq!(route.paths.len(), 1);
5711 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5713 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5714 let mut route_default = route.clone();
5715 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5716 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5717 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5718 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5719 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5721 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5722 let mut route_limited = route.clone();
5723 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5724 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5725 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5726 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5727 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5731 fn adds_plausible_cltv_offset() {
5732 let (secp_ctx, network, _, _, logger) = build_graph();
5733 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5734 let network_graph = network.read_only();
5735 let network_nodes = network_graph.nodes();
5736 let network_channels = network_graph.channels();
5737 let scorer = ln_test_utils::TestScorer::new();
5738 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5739 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5740 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5742 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
5743 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5744 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5746 let mut path_plausibility = vec![];
5748 for p in route.paths {
5749 // 1. Select random observation point
5750 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5751 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5753 prng.process_in_place(&mut random_bytes);
5754 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5755 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5757 // 2. Calculate what CLTV expiry delta we would observe there
5758 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5760 // 3. Starting from the observation point, find candidate paths
5761 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5762 candidates.push_back((observation_point, vec![]));
5764 let mut found_plausible_candidate = false;
5766 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5767 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5768 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5769 found_plausible_candidate = true;
5770 break 'candidate_loop;
5774 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5775 for channel_id in &cur_node.channels {
5776 if let Some(channel_info) = network_channels.get(&channel_id) {
5777 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5778 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5779 if cur_path_cltv_deltas.iter().sum::<u32>()
5780 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5781 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5782 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5783 candidates.push_back((*next_id, new_path_cltv_deltas));
5791 path_plausibility.push(found_plausible_candidate);
5793 assert!(path_plausibility.iter().all(|x| *x));
5797 fn builds_correct_path_from_hops() {
5798 let (secp_ctx, network, _, _, logger) = build_graph();
5799 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5800 let network_graph = network.read_only();
5802 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5803 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5805 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5806 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5807 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5808 &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
5809 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5810 assert_eq!(hops.len(), route.paths[0].hops.len());
5811 for (idx, hop_pubkey) in hops.iter().enumerate() {
5812 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5817 fn avoids_saturating_channels() {
5818 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5819 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5820 let decay_params = ProbabilisticScoringDecayParameters::default();
5821 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
5823 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5824 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5825 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5826 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5827 short_channel_id: 4,
5830 cltv_expiry_delta: (4 << 4) | 1,
5831 htlc_minimum_msat: 0,
5832 htlc_maximum_msat: 250_000_000,
5834 fee_proportional_millionths: 0,
5835 excess_data: Vec::new()
5837 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5838 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5839 short_channel_id: 13,
5842 cltv_expiry_delta: (13 << 4) | 1,
5843 htlc_minimum_msat: 0,
5844 htlc_maximum_msat: 250_000_000,
5846 fee_proportional_millionths: 0,
5847 excess_data: Vec::new()
5850 let config = UserConfig::default();
5851 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5852 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5853 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5854 // 100,000 sats is less than the available liquidity on each channel, set above.
5855 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000_000, Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
5856 assert_eq!(route.paths.len(), 2);
5857 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
5858 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
5861 #[cfg(not(feature = "no-std"))]
5862 pub(super) fn random_init_seed() -> u64 {
5863 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5864 use core::hash::{BuildHasher, Hasher};
5865 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5866 println!("Using seed of {}", seed);
5871 #[cfg(not(feature = "no-std"))]
5872 fn generate_routes() {
5873 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
5875 let logger = ln_test_utils::TestLogger::new();
5876 let graph = match super::bench_utils::read_network_graph(&logger) {
5884 let params = ProbabilisticScoringFeeParameters::default();
5885 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
5886 let features = super::InvoiceFeatures::empty();
5888 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
5892 #[cfg(not(feature = "no-std"))]
5893 fn generate_routes_mpp() {
5894 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
5896 let logger = ln_test_utils::TestLogger::new();
5897 let graph = match super::bench_utils::read_network_graph(&logger) {
5905 let params = ProbabilisticScoringFeeParameters::default();
5906 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
5907 let features = channelmanager::provided_invoice_features(&UserConfig::default());
5909 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 0, 2);
5913 #[cfg(not(feature = "no-std"))]
5914 fn generate_large_mpp_routes() {
5915 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
5917 let logger = ln_test_utils::TestLogger::new();
5918 let graph = match super::bench_utils::read_network_graph(&logger) {
5926 let params = ProbabilisticScoringFeeParameters::default();
5927 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
5928 let features = channelmanager::provided_invoice_features(&UserConfig::default());
5930 super::bench_utils::generate_test_routes(&graph, &mut scorer, ¶ms, features, random_init_seed(), 1_000_000, 2);
5934 fn honors_manual_penalties() {
5935 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5936 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5938 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5939 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5941 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
5942 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
5944 // First check set manual penalties are returned by the scorer.
5945 let usage = ChannelUsage {
5947 inflight_htlc_msat: 0,
5948 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5950 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5951 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5952 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
5954 // Then check we can get a normal route
5955 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
5956 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
5957 assert!(route.is_ok());
5959 // Then check that we can't get a route if we ban an intermediate node.
5960 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
5961 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
5962 assert!(route.is_err());
5964 // Finally make sure we can route again, when we remove the ban.
5965 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5966 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
5967 assert!(route.is_ok());
5971 fn abide_by_route_hint_max_htlc() {
5972 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
5973 // params in the final route.
5974 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5975 let netgraph = network_graph.read_only();
5976 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5977 let scorer = ln_test_utils::TestScorer::new();
5978 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5979 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5980 let config = UserConfig::default();
5982 let max_htlc_msat = 50_000;
5983 let route_hint_1 = RouteHint(vec![RouteHintHop {
5984 src_node_id: nodes[2],
5985 short_channel_id: 42,
5988 proportional_millionths: 0,
5990 cltv_expiry_delta: 10,
5991 htlc_minimum_msat: None,
5992 htlc_maximum_msat: Some(max_htlc_msat),
5994 let dest_node_id = ln_test_utils::pubkey(42);
5995 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
5996 .with_route_hints(vec![route_hint_1.clone()]).unwrap()
5997 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5999 // Make sure we'll error if our route hints don't have enough liquidity according to their
6000 // htlc_maximum_msat.
6001 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6002 &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6005 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6006 } else { panic!(); }
6008 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6009 let mut route_hint_2 = route_hint_1.clone();
6010 route_hint_2.0[0].short_channel_id = 43;
6011 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6012 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6013 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6014 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6015 Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6016 assert_eq!(route.paths.len(), 2);
6017 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6018 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6022 fn direct_channel_to_hints_with_max_htlc() {
6023 // Check that if we have a first hop channel peer that's connected to multiple provided route
6024 // hints, that we properly split the payment between the route hints if needed.
6025 let logger = Arc::new(ln_test_utils::TestLogger::new());
6026 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6027 let scorer = ln_test_utils::TestScorer::new();
6028 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6029 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6030 let config = UserConfig::default();
6032 let our_node_id = ln_test_utils::pubkey(42);
6033 let intermed_node_id = ln_test_utils::pubkey(43);
6034 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6036 let amt_msat = 900_000;
6037 let max_htlc_msat = 500_000;
6038 let route_hint_1 = RouteHint(vec![RouteHintHop {
6039 src_node_id: intermed_node_id,
6040 short_channel_id: 44,
6043 proportional_millionths: 0,
6045 cltv_expiry_delta: 10,
6046 htlc_minimum_msat: None,
6047 htlc_maximum_msat: Some(max_htlc_msat),
6049 src_node_id: intermed_node_id,
6050 short_channel_id: 45,
6053 proportional_millionths: 0,
6055 cltv_expiry_delta: 10,
6056 htlc_minimum_msat: None,
6057 // Check that later route hint max htlcs don't override earlier ones
6058 htlc_maximum_msat: Some(max_htlc_msat - 50),
6060 let mut route_hint_2 = route_hint_1.clone();
6061 route_hint_2.0[0].short_channel_id = 46;
6062 route_hint_2.0[1].short_channel_id = 47;
6063 let dest_node_id = ln_test_utils::pubkey(44);
6064 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6065 .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6066 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6068 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6069 Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6070 &random_seed_bytes).unwrap();
6071 assert_eq!(route.paths.len(), 2);
6072 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6073 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6074 assert_eq!(route.get_total_amount(), amt_msat);
6076 // Re-run but with two first hop channels connected to the same route hint peers that must be
6078 let first_hops = vec![
6079 get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6080 get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6082 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6083 Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6084 &random_seed_bytes).unwrap();
6085 assert_eq!(route.paths.len(), 2);
6086 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6087 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6088 assert_eq!(route.get_total_amount(), amt_msat);
6092 fn blinded_route_ser() {
6093 let blinded_path_1 = BlindedPath {
6094 introduction_node_id: ln_test_utils::pubkey(42),
6095 blinding_point: ln_test_utils::pubkey(43),
6097 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6098 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6101 let blinded_path_2 = BlindedPath {
6102 introduction_node_id: ln_test_utils::pubkey(46),
6103 blinding_point: ln_test_utils::pubkey(47),
6105 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6106 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6109 // (De)serialize a Route with 1 blinded path out of two total paths.
6110 let mut route = Route { paths: vec![Path {
6111 hops: vec![RouteHop {
6112 pubkey: ln_test_utils::pubkey(50),
6113 node_features: NodeFeatures::empty(),
6114 short_channel_id: 42,
6115 channel_features: ChannelFeatures::empty(),
6117 cltv_expiry_delta: 0,
6119 blinded_tail: Some(BlindedTail {
6120 hops: blinded_path_1.blinded_hops,
6121 blinding_point: blinded_path_1.blinding_point,
6122 excess_final_cltv_expiry_delta: 40,
6123 final_value_msat: 100,
6125 hops: vec![RouteHop {
6126 pubkey: ln_test_utils::pubkey(51),
6127 node_features: NodeFeatures::empty(),
6128 short_channel_id: 43,
6129 channel_features: ChannelFeatures::empty(),
6131 cltv_expiry_delta: 0,
6132 }], blinded_tail: None }],
6133 payment_params: None,
6135 let encoded_route = route.encode();
6136 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6137 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6138 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6140 // (De)serialize a Route with two paths, each containing a blinded tail.
6141 route.paths[1].blinded_tail = Some(BlindedTail {
6142 hops: blinded_path_2.blinded_hops,
6143 blinding_point: blinded_path_2.blinding_point,
6144 excess_final_cltv_expiry_delta: 41,
6145 final_value_msat: 101,
6147 let encoded_route = route.encode();
6148 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6149 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6150 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6154 fn blinded_path_inflight_processing() {
6155 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6156 // account for the blinded tail's final amount_msat.
6157 let mut inflight_htlcs = InFlightHtlcs::new();
6158 let blinded_path = BlindedPath {
6159 introduction_node_id: ln_test_utils::pubkey(43),
6160 blinding_point: ln_test_utils::pubkey(48),
6161 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6164 hops: vec![RouteHop {
6165 pubkey: ln_test_utils::pubkey(42),
6166 node_features: NodeFeatures::empty(),
6167 short_channel_id: 42,
6168 channel_features: ChannelFeatures::empty(),
6170 cltv_expiry_delta: 0,
6173 pubkey: blinded_path.introduction_node_id,
6174 node_features: NodeFeatures::empty(),
6175 short_channel_id: 43,
6176 channel_features: ChannelFeatures::empty(),
6178 cltv_expiry_delta: 0,
6180 blinded_tail: Some(BlindedTail {
6181 hops: blinded_path.blinded_hops,
6182 blinding_point: blinded_path.blinding_point,
6183 excess_final_cltv_expiry_delta: 0,
6184 final_value_msat: 200,
6187 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6188 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6189 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6193 fn blinded_path_cltv_shadow_offset() {
6194 // Make sure we add a shadow offset when sending to blinded paths.
6195 let blinded_path = BlindedPath {
6196 introduction_node_id: ln_test_utils::pubkey(43),
6197 blinding_point: ln_test_utils::pubkey(44),
6199 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6200 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6203 let mut route = Route { paths: vec![Path {
6204 hops: vec![RouteHop {
6205 pubkey: ln_test_utils::pubkey(42),
6206 node_features: NodeFeatures::empty(),
6207 short_channel_id: 42,
6208 channel_features: ChannelFeatures::empty(),
6210 cltv_expiry_delta: 0,
6213 pubkey: blinded_path.introduction_node_id,
6214 node_features: NodeFeatures::empty(),
6215 short_channel_id: 43,
6216 channel_features: ChannelFeatures::empty(),
6218 cltv_expiry_delta: 0,
6221 blinded_tail: Some(BlindedTail {
6222 hops: blinded_path.blinded_hops,
6223 blinding_point: blinded_path.blinding_point,
6224 excess_final_cltv_expiry_delta: 0,
6225 final_value_msat: 200,
6227 }], payment_params: None};
6229 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6230 let (_, network_graph, _, _, _) = build_line_graph();
6231 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6232 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6233 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6237 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6238 pub(crate) mod bench_utils {
6242 use bitcoin::hashes::Hash;
6243 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6245 use crate::chain::transaction::OutPoint;
6246 use crate::sign::{EntropySource, KeysManager};
6247 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6248 use crate::ln::features::InvoiceFeatures;
6249 use crate::routing::gossip::NetworkGraph;
6250 use crate::util::config::UserConfig;
6251 use crate::util::ser::ReadableArgs;
6252 use crate::util::test_utils::TestLogger;
6254 /// Tries to open a network graph file, or panics with a URL to fetch it.
6255 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6256 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6257 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6258 .or_else(|_| { // Fall back to guessing based on the binary location
6259 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6260 let mut path = std::env::current_exe().unwrap();
6261 path.pop(); // lightning-...
6263 path.pop(); // debug
6264 path.pop(); // target
6265 path.push("lightning");
6266 path.push("net_graph-2023-01-18.bin");
6269 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6270 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6271 let mut path = std::env::current_exe().unwrap();
6272 path.pop(); // bench...
6274 path.pop(); // debug
6275 path.pop(); // target
6276 path.pop(); // bench
6277 path.push("lightning");
6278 path.push("net_graph-2023-01-18.bin");
6281 .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");
6282 #[cfg(require_route_graph_test)]
6283 return Ok(res.unwrap());
6284 #[cfg(not(require_route_graph_test))]
6288 pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6289 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6292 pub(crate) fn payer_pubkey() -> PublicKey {
6293 let secp_ctx = Secp256k1::new();
6294 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6298 pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6300 channel_id: [0; 32],
6301 counterparty: ChannelCounterparty {
6302 features: channelmanager::provided_init_features(&UserConfig::default()),
6304 unspendable_punishment_reserve: 0,
6305 forwarding_info: None,
6306 outbound_htlc_minimum_msat: None,
6307 outbound_htlc_maximum_msat: None,
6309 funding_txo: Some(OutPoint {
6310 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6313 short_channel_id: Some(1),
6314 inbound_scid_alias: None,
6315 outbound_scid_alias: None,
6316 channel_value_satoshis: 10_000_000_000,
6318 balance_msat: 10_000_000_000,
6319 outbound_capacity_msat: 10_000_000_000,
6320 next_outbound_htlc_minimum_msat: 0,
6321 next_outbound_htlc_limit_msat: 10_000_000_000,
6322 inbound_capacity_msat: 0,
6323 unspendable_punishment_reserve: None,
6324 confirmations_required: None,
6325 confirmations: None,
6326 force_close_spend_delay: None,
6328 is_channel_ready: true,
6331 inbound_htlc_minimum_msat: None,
6332 inbound_htlc_maximum_msat: None,
6334 feerate_sat_per_1000_weight: None,
6338 pub(crate) fn generate_test_routes<S: Score>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6339 score_params: &S::ScoreParams, features: InvoiceFeatures, mut seed: u64,
6340 starting_amount: u64, route_count: usize,
6341 ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6342 let payer = payer_pubkey();
6343 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6344 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6346 let nodes = graph.read_only().nodes().clone();
6347 let mut route_endpoints = Vec::new();
6348 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6349 // with some routes we picked being un-routable.
6350 for _ in 0..route_count * 3 / 2 {
6352 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6353 let src = PublicKey::from_slice(nodes.unordered_keys()
6354 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6355 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6356 let dst = PublicKey::from_slice(nodes.unordered_keys()
6357 .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6358 let params = PaymentParameters::from_node_id(dst, 42)
6359 .with_bolt11_features(features.clone()).unwrap();
6360 let first_hop = first_hop(src);
6361 let amt = starting_amount + seed % 1_000_000;
6363 get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]),
6364 amt, &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok();
6366 // ...and seed the scorer with success and failure data...
6367 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6368 let mut score_amt = seed % 1_000_000_000;
6370 // Generate fail/success paths for a wider range of potential amounts with
6371 // MPP enabled to give us a chance to apply penalties for more potential
6373 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6374 let params = PaymentParameters::from_node_id(dst, 42)
6375 .with_bolt11_features(mpp_features).unwrap();
6377 let route_res = get_route(&payer, ¶ms, &graph.read_only(),
6378 Some(&[&first_hop]), score_amt, &TestLogger::new(), &scorer,
6379 score_params, &random_seed_bytes);
6380 if let Ok(route) = route_res {
6381 for path in route.paths {
6382 if seed & 0x80 == 0 {
6383 scorer.payment_path_successful(&path);
6385 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6386 scorer.payment_path_failed(&path, short_channel_id);
6388 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6392 // If we couldn't find a path with a higer amount, reduce and try again.
6396 route_endpoints.push((first_hop, params, amt));
6402 // Because we've changed channel scores, it's possible we'll take different routes to the
6403 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
6404 // requires a too-high CLTV delta.
6405 route_endpoints.retain(|(first_hop, params, amt)| {
6406 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6407 &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok()
6409 route_endpoints.truncate(route_count);
6410 assert_eq!(route_endpoints.len(), route_count);
6418 use crate::sign::{EntropySource, KeysManager};
6419 use crate::ln::channelmanager;
6420 use crate::ln::features::InvoiceFeatures;
6421 use crate::routing::gossip::NetworkGraph;
6422 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
6423 use crate::util::config::UserConfig;
6424 use crate::util::logger::{Logger, Record};
6425 use crate::util::test_utils::TestLogger;
6427 use criterion::Criterion;
6429 struct DummyLogger {}
6430 impl Logger for DummyLogger {
6431 fn log(&self, _record: &Record) {}
6434 pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6435 let logger = TestLogger::new();
6436 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6437 let scorer = FixedPenaltyScorer::with_penalty(0);
6438 generate_routes(bench, &network_graph, scorer, &(), InvoiceFeatures::empty(), 0,
6439 "generate_routes_with_zero_penalty_scorer");
6442 pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6443 let logger = TestLogger::new();
6444 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6445 let scorer = FixedPenaltyScorer::with_penalty(0);
6446 generate_routes(bench, &network_graph, scorer, &(),
6447 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6448 "generate_mpp_routes_with_zero_penalty_scorer");
6451 pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6452 let logger = TestLogger::new();
6453 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6454 let params = ProbabilisticScoringFeeParameters::default();
6455 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6456 generate_routes(bench, &network_graph, scorer, ¶ms, InvoiceFeatures::empty(), 0,
6457 "generate_routes_with_probabilistic_scorer");
6460 pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6461 let logger = TestLogger::new();
6462 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6463 let params = ProbabilisticScoringFeeParameters::default();
6464 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6465 generate_routes(bench, &network_graph, scorer, ¶ms,
6466 channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6467 "generate_mpp_routes_with_probabilistic_scorer");
6470 pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6471 let logger = TestLogger::new();
6472 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6473 let params = ProbabilisticScoringFeeParameters::default();
6474 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6475 generate_routes(bench, &network_graph, scorer, ¶ms,
6476 channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
6477 "generate_large_mpp_routes_with_probabilistic_scorer");
6480 fn generate_routes<S: Score>(
6481 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
6482 score_params: &S::ScoreParams, features: InvoiceFeatures, starting_amount: u64,
6483 bench_name: &'static str,
6485 let payer = bench_utils::payer_pubkey();
6486 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6487 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6489 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
6490 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
6492 // ...then benchmark finding paths between the nodes we learned.
6494 bench.bench_function(bench_name, |b| b.iter(|| {
6495 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
6496 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6497 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());