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::ln::PaymentHash;
17 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
18 use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
21 use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
22 use crate::util::ser::{Writeable, Readable, Writer};
23 use crate::util::logger::{Level, Logger};
24 use crate::util::chacha20::ChaCha20;
27 use crate::prelude::*;
28 use crate::sync::Mutex;
29 use alloc::collections::BinaryHeap;
33 /// A [`Router`] implemented using [`find_route`].
34 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> where
36 S::Target: for <'a> LockableScore<'a>,
40 random_seed_bytes: Mutex<[u8; 32]>,
44 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> DefaultRouter<G, L, S> where
46 S::Target: for <'a> LockableScore<'a>,
48 /// Creates a new router.
49 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S) -> Self {
50 let random_seed_bytes = Mutex::new(random_seed_bytes);
51 Self { network_graph, logger, random_seed_bytes, scorer }
55 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> Router for DefaultRouter<G, L, S> where
57 S::Target: for <'a> LockableScore<'a>,
60 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
61 inflight_htlcs: &InFlightHtlcs
62 ) -> Result<Route, LightningError> {
63 let random_seed_bytes = {
64 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
65 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
66 *locked_random_seed_bytes
70 payer, params, &self.network_graph, first_hops, &*self.logger,
71 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock(), inflight_htlcs),
76 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
77 self.scorer.lock().payment_path_failed(path, short_channel_id);
80 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
81 self.scorer.lock().payment_path_successful(path);
84 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
85 self.scorer.lock().probe_successful(path);
88 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
89 self.scorer.lock().probe_failed(path, short_channel_id);
93 /// A trait defining behavior for routing a payment.
95 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
97 &self, payer: &PublicKey, route_params: &RouteParameters,
98 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
99 ) -> Result<Route, LightningError>;
100 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
101 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
102 fn find_route_with_id(
103 &self, payer: &PublicKey, route_params: &RouteParameters,
104 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
105 _payment_hash: PaymentHash, _payment_id: PaymentId
106 ) -> Result<Route, LightningError> {
107 self.find_route(payer, route_params, first_hops, inflight_htlcs)
109 /// Lets the router know that payment through a specific path has failed.
110 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
111 /// Lets the router know that payment through a specific path was successful.
112 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
113 /// Lets the router know that a payment probe was successful.
114 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
115 /// Lets the router know that a payment probe failed.
116 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
119 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
121 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
124 /// [`Score`]: crate::routing::scoring::Score
125 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score> {
127 // Maps a channel's short channel id and its direction to the liquidity used up.
128 inflight_htlcs: &'a InFlightHtlcs,
131 impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> {
132 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
133 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
134 ScorerAccountingForInFlightHtlcs {
142 impl<'a, S: Score> Writeable for ScorerAccountingForInFlightHtlcs<'a, S> {
143 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
146 impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> {
147 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage) -> u64 {
148 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
149 source, target, short_channel_id
151 let usage = ChannelUsage {
152 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
156 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
158 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
162 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
163 self.scorer.payment_path_failed(path, short_channel_id)
166 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
167 self.scorer.payment_path_successful(path)
170 fn probe_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
171 self.scorer.probe_failed(path, short_channel_id)
174 fn probe_successful(&mut self, path: &[&RouteHop]) {
175 self.scorer.probe_successful(path)
179 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
180 /// in-use channel liquidity.
182 pub struct InFlightHtlcs(
183 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
184 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
185 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
187 HashMap<(u64, bool), u64>
191 /// Constructs an empty `InFlightHtlcs`.
192 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
194 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
195 pub fn process_path(&mut self, path: &[RouteHop], payer_node_id: PublicKey) {
196 if path.is_empty() { return };
197 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
198 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
199 // the router excludes the payer node. In the following lines, the payer's information is
200 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
201 // in our sliding window of two.
202 let reversed_hops_with_payer = path.iter().rev().skip(1)
203 .map(|hop| hop.pubkey)
204 .chain(core::iter::once(payer_node_id));
205 let mut cumulative_msat = 0;
207 // Taking the reversed vector from above, we zip it with just the reversed hops list to
208 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
209 // the total amount sent.
210 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
211 cumulative_msat += next_hop.fee_msat;
213 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
214 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
215 .or_insert(cumulative_msat);
219 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
221 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
222 self.0.get(&(channel_scid, source < target)).map(|v| *v)
226 impl Writeable for InFlightHtlcs {
227 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
230 impl Readable for InFlightHtlcs {
231 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
232 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
233 Ok(Self(infight_map))
238 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
239 pub struct RouteHop {
240 /// The node_id of the node at this hop.
241 pub pubkey: PublicKey,
242 /// The node_announcement features of the node at this hop. For the last hop, these may be
243 /// amended to match the features present in the invoice this node generated.
244 pub node_features: NodeFeatures,
245 /// The channel that should be used from the previous hop to reach this node.
246 pub short_channel_id: u64,
247 /// The channel_announcement features of the channel that should be used from the previous hop
248 /// to reach this node.
249 pub channel_features: ChannelFeatures,
250 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
251 /// For the last hop, this should be the full value of the payment (might be more than
252 /// requested if we had to match htlc_minimum_msat).
254 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
255 /// expected at the destination, in excess of the current block height.
256 pub cltv_expiry_delta: u32,
259 impl_writeable_tlv_based!(RouteHop, {
260 (0, pubkey, required),
261 (2, node_features, required),
262 (4, short_channel_id, required),
263 (6, channel_features, required),
264 (8, fee_msat, required),
265 (10, cltv_expiry_delta, required),
268 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
269 /// it can take multiple paths. Each path is composed of one or more hops through the network.
270 #[derive(Clone, Hash, PartialEq, Eq)]
272 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
273 /// last RouteHop in each path must be the same. Each entry represents a list of hops, NOT
274 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
275 /// least length one. While the maximum length of any given path is variable, keeping the length
276 /// of any path less or equal to 19 should currently ensure it is viable.
277 pub paths: Vec<Vec<RouteHop>>,
278 /// The `payment_params` parameter passed to [`find_route`].
279 /// This is used by `ChannelManager` to track information which may be required for retries,
280 /// provided back to you via [`Event::PaymentPathFailed`].
282 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
283 pub payment_params: Option<PaymentParameters>,
286 pub(crate) trait RoutePath {
287 /// Gets the fees for a given path, excluding any excess paid to the recipient.
288 fn get_path_fees(&self) -> u64;
290 impl RoutePath for Vec<RouteHop> {
291 fn get_path_fees(&self) -> u64 {
292 // Do not count last hop of each path since that's the full value of the payment
293 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
294 .iter().map(|hop| &hop.fee_msat)
300 /// Returns the total amount of fees paid on this [`Route`].
302 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
303 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
304 pub fn get_total_fees(&self) -> u64 {
305 self.paths.iter().map(|path| path.get_path_fees()).sum()
308 /// Returns the total amount paid on this [`Route`], excluding the fees.
309 pub fn get_total_amount(&self) -> u64 {
310 return self.paths.iter()
311 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
316 const SERIALIZATION_VERSION: u8 = 1;
317 const MIN_SERIALIZATION_VERSION: u8 = 1;
319 impl Writeable for Route {
320 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
321 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
322 (self.paths.len() as u64).write(writer)?;
323 for hops in self.paths.iter() {
324 (hops.len() as u8).write(writer)?;
325 for hop in hops.iter() {
329 write_tlv_fields!(writer, {
330 (1, self.payment_params, option),
336 impl Readable for Route {
337 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
338 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
339 let path_count: u64 = Readable::read(reader)?;
340 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
341 for _ in 0..path_count {
342 let hop_count: u8 = Readable::read(reader)?;
343 let mut hops = Vec::with_capacity(hop_count as usize);
344 for _ in 0..hop_count {
345 hops.push(Readable::read(reader)?);
349 let mut payment_params = None;
350 read_tlv_fields!(reader, {
351 (1, payment_params, option),
353 Ok(Route { paths, payment_params })
357 /// Parameters needed to find a [`Route`].
359 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
360 /// [`Event::PaymentPathFailed`] for retrying a failed payment path.
362 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
363 #[derive(Clone, Debug, PartialEq, Eq)]
364 pub struct RouteParameters {
365 /// The parameters of the failed payment path.
366 pub payment_params: PaymentParameters,
368 /// The amount in msats sent on the failed payment path.
369 pub final_value_msat: u64,
371 /// The CLTV on the final hop of the failed payment path.
373 /// This field is deprecated, [`PaymentParameters::final_cltv_expiry_delta`] should be used
374 /// instead, if available.
375 pub final_cltv_expiry_delta: u32,
378 impl_writeable_tlv_based!(RouteParameters, {
379 (0, payment_params, required),
380 (2, final_value_msat, required),
381 (4, final_cltv_expiry_delta, required),
384 /// Maximum total CTLV difference we allow for a full payment path.
385 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
387 /// Maximum number of paths we allow an (MPP) payment to have.
388 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
389 // limits, but for now more than 10 paths likely carries too much one-path failure.
390 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
392 // The median hop CLTV expiry delta currently seen in the network.
393 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
395 // During routing, we only consider paths shorter than our maximum length estimate.
396 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
397 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
398 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
400 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
401 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
402 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
403 // (payment_secret and total_msat) = 93 bytes for the final hop.
404 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
405 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
406 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
408 /// The recipient of a payment.
409 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
410 pub struct PaymentParameters {
411 /// The node id of the payee.
412 pub payee_pubkey: PublicKey,
414 /// Features supported by the payee.
416 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
417 /// does not contain any features.
419 /// [`for_keysend`]: Self::for_keysend
420 pub features: Option<InvoiceFeatures>,
422 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
423 pub route_hints: Vec<RouteHint>,
425 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
426 pub expiry_time: Option<u64>,
428 /// The maximum total CLTV delta we accept for the route.
429 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
430 pub max_total_cltv_expiry_delta: u32,
432 /// The maximum number of paths that may be used by (MPP) payments.
433 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
434 pub max_path_count: u8,
436 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
437 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
438 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
439 /// increasing failure probability for those paths.
441 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
442 /// restriction have been found. While paths which meet this criteria will be searched for, it
443 /// is ultimately up to the scorer to select them over other paths.
445 /// A value of 0 will allow payments up to and including a channel's total announced usable
446 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
449 pub max_channel_saturation_power_of_half: u8,
451 /// A list of SCIDs which this payment was previously attempted over and which caused the
452 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
454 pub previously_failed_channels: Vec<u64>,
456 /// The minimum CLTV delta at the end of the route.
458 /// This field should always be set to `Some` and may be required in a future release.
459 pub final_cltv_expiry_delta: Option<u32>,
462 impl_writeable_tlv_based!(PaymentParameters, {
463 (0, payee_pubkey, required),
464 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
465 (2, features, option),
466 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
467 (4, route_hints, vec_type),
468 (5, max_channel_saturation_power_of_half, (default_value, 2)),
469 (6, expiry_time, option),
470 (7, previously_failed_channels, vec_type),
471 (9, final_cltv_expiry_delta, option),
474 impl PaymentParameters {
475 /// Creates a payee with the node id of the given `pubkey`.
477 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
479 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
485 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
486 max_path_count: DEFAULT_MAX_PATH_COUNT,
487 max_channel_saturation_power_of_half: 2,
488 previously_failed_channels: Vec::new(),
489 final_cltv_expiry_delta: Some(final_cltv_expiry_delta),
493 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
495 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
497 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
498 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta).with_features(InvoiceFeatures::for_keysend())
501 /// Includes the payee's features.
503 /// (C-not exported) since bindings don't support move semantics
504 pub fn with_features(self, features: InvoiceFeatures) -> Self {
505 Self { features: Some(features), ..self }
508 /// Includes hints for routing to the payee.
510 /// (C-not exported) since bindings don't support move semantics
511 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
512 Self { route_hints, ..self }
515 /// Includes a payment expiration in seconds relative to the UNIX epoch.
517 /// (C-not exported) since bindings don't support move semantics
518 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
519 Self { expiry_time: Some(expiry_time), ..self }
522 /// Includes a limit for the total CLTV expiry delta which is considered during routing
524 /// (C-not exported) since bindings don't support move semantics
525 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
526 Self { max_total_cltv_expiry_delta, ..self }
529 /// Includes a limit for the maximum number of payment paths that may be used.
531 /// (C-not exported) since bindings don't support move semantics
532 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
533 Self { max_path_count, ..self }
536 /// Includes a limit for the maximum number of payment paths that may be used.
538 /// (C-not exported) since bindings don't support move semantics
539 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
540 Self { max_channel_saturation_power_of_half, ..self }
544 /// A list of hops along a payment path terminating with a channel to the recipient.
545 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
546 pub struct RouteHint(pub Vec<RouteHintHop>);
548 impl Writeable for RouteHint {
549 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
550 (self.0.len() as u64).write(writer)?;
551 for hop in self.0.iter() {
558 impl Readable for RouteHint {
559 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
560 let hop_count: u64 = Readable::read(reader)?;
561 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
562 for _ in 0..hop_count {
563 hops.push(Readable::read(reader)?);
569 /// A channel descriptor for a hop along a payment path.
570 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
571 pub struct RouteHintHop {
572 /// The node_id of the non-target end of the route
573 pub src_node_id: PublicKey,
574 /// The short_channel_id of this channel
575 pub short_channel_id: u64,
576 /// The fees which must be paid to use this channel
577 pub fees: RoutingFees,
578 /// The difference in CLTV values between this node and the next node.
579 pub cltv_expiry_delta: u16,
580 /// The minimum value, in msat, which must be relayed to the next hop.
581 pub htlc_minimum_msat: Option<u64>,
582 /// The maximum value in msat available for routing with a single HTLC.
583 pub htlc_maximum_msat: Option<u64>,
586 impl_writeable_tlv_based!(RouteHintHop, {
587 (0, src_node_id, required),
588 (1, htlc_minimum_msat, option),
589 (2, short_channel_id, required),
590 (3, htlc_maximum_msat, option),
592 (6, cltv_expiry_delta, required),
595 #[derive(Eq, PartialEq)]
596 struct RouteGraphNode {
598 lowest_fee_to_node: u64,
599 total_cltv_delta: u32,
600 // The maximum value a yet-to-be-constructed payment path might flow through this node.
601 // This value is upper-bounded by us by:
602 // - how much is needed for a path being constructed
603 // - how much value can channels following this node (up to the destination) can contribute,
604 // considering their capacity and fees
605 value_contribution_msat: u64,
606 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
607 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
608 path_htlc_minimum_msat: u64,
609 /// All penalties incurred from this hop on the way to the destination, as calculated using
611 path_penalty_msat: u64,
612 /// The number of hops walked up to this node.
613 path_length_to_node: u8,
616 impl cmp::Ord for RouteGraphNode {
617 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
618 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
619 .saturating_add(other.path_penalty_msat);
620 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
621 .saturating_add(self.path_penalty_msat);
622 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
626 impl cmp::PartialOrd for RouteGraphNode {
627 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
628 Some(self.cmp(other))
632 /// A wrapper around the various hop representations.
634 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
635 #[derive(Clone, Debug)]
636 enum CandidateRouteHop<'a> {
637 /// A hop from the payer, where the outbound liquidity is known.
639 details: &'a ChannelDetails,
641 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
643 info: DirectedChannelInfo<'a>,
644 short_channel_id: u64,
646 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
648 hint: &'a RouteHintHop,
652 impl<'a> CandidateRouteHop<'a> {
653 fn short_channel_id(&self) -> u64 {
655 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
656 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
657 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
661 // NOTE: This may alloc memory so avoid calling it in a hot code path.
662 fn features(&self) -> ChannelFeatures {
664 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
665 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
666 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
670 fn cltv_expiry_delta(&self) -> u32 {
672 CandidateRouteHop::FirstHop { .. } => 0,
673 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
674 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
678 fn htlc_minimum_msat(&self) -> u64 {
680 CandidateRouteHop::FirstHop { .. } => 0,
681 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
682 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
686 fn fees(&self) -> RoutingFees {
688 CandidateRouteHop::FirstHop { .. } => RoutingFees {
689 base_msat: 0, proportional_millionths: 0,
691 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
692 CandidateRouteHop::PrivateHop { hint } => hint.fees,
696 fn effective_capacity(&self) -> EffectiveCapacity {
698 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
699 liquidity_msat: details.next_outbound_htlc_limit_msat,
701 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
702 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
708 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
709 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
711 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
712 EffectiveCapacity::Infinite => u64::max_value(),
713 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
714 EffectiveCapacity::MaximumHTLC { amount_msat } =>
715 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
716 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
717 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
721 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
722 -> bool where I1::Item: PartialEq<I2::Item> {
724 let a = iter_a.next();
725 let b = iter_b.next();
726 if a.is_none() && b.is_none() { return true; }
727 if a.is_none() || b.is_none() { return false; }
728 if a.unwrap().ne(&b.unwrap()) { return false; }
732 /// It's useful to keep track of the hops associated with the fees required to use them,
733 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
734 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
735 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
737 struct PathBuildingHop<'a> {
738 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
739 // is a larger refactor and will require careful performance analysis.
741 candidate: CandidateRouteHop<'a>,
744 /// All the fees paid *after* this channel on the way to the destination
745 next_hops_fee_msat: u64,
746 /// Fee paid for the use of the current channel (see candidate.fees()).
747 /// The value will be actually deducted from the counterparty balance on the previous link.
748 hop_use_fee_msat: u64,
749 /// Used to compare channels when choosing the for routing.
750 /// Includes paying for the use of a hop and the following hops, as well as
751 /// an estimated cost of reaching this hop.
752 /// Might get stale when fees are recomputed. Primarily for internal use.
754 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
755 /// walk and may be invalid thereafter.
756 path_htlc_minimum_msat: u64,
757 /// All penalties incurred from this channel on the way to the destination, as calculated using
759 path_penalty_msat: u64,
760 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
761 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
762 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
763 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
764 /// avoid processing them again.
766 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
767 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
768 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
769 // value_contribution_msat, which requires tracking it here. See comments below where it is
770 // used for more info.
771 value_contribution_msat: u64,
774 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
775 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
776 let mut debug_struct = f.debug_struct("PathBuildingHop");
778 .field("node_id", &self.node_id)
779 .field("short_channel_id", &self.candidate.short_channel_id())
780 .field("total_fee_msat", &self.total_fee_msat)
781 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
782 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
783 .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)))
784 .field("path_penalty_msat", &self.path_penalty_msat)
785 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
786 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
787 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
788 let debug_struct = debug_struct
789 .field("value_contribution_msat", &self.value_contribution_msat);
790 debug_struct.finish()
794 // Instantiated with a list of hops with correct data in them collected during path finding,
795 // an instance of this struct should be further modified only via given methods.
797 struct PaymentPath<'a> {
798 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
801 impl<'a> PaymentPath<'a> {
802 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
803 fn get_value_msat(&self) -> u64 {
804 self.hops.last().unwrap().0.fee_msat
807 fn get_path_penalty_msat(&self) -> u64 {
808 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
811 fn get_total_fee_paid_msat(&self) -> u64 {
812 if self.hops.len() < 1 {
816 // Can't use next_hops_fee_msat because it gets outdated.
817 for (i, (hop, _)) in self.hops.iter().enumerate() {
818 if i != self.hops.len() - 1 {
819 result += hop.fee_msat;
825 fn get_cost_msat(&self) -> u64 {
826 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
829 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
830 // to change fees may result in an inconsistency.
832 // Sometimes we call this function right after constructing a path which is inconsistent in
833 // that it the value being transferred has decreased while we were doing path finding, leading
834 // to the fees being paid not lining up with the actual limits.
836 // Note that this function is not aware of the available_liquidity limit, and thus does not
837 // support increasing the value being transferred beyond what was selected during the initial
839 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
840 let mut total_fee_paid_msat = 0 as u64;
841 for i in (0..self.hops.len()).rev() {
842 let last_hop = i == self.hops.len() - 1;
844 // For non-last-hop, this value will represent the fees paid on the current hop. It
845 // will consist of the fees for the use of the next hop, and extra fees to match
846 // htlc_minimum_msat of the current channel. Last hop is handled separately.
847 let mut cur_hop_fees_msat = 0;
849 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
852 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
853 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
854 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
855 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
856 // set it too high just to maliciously take more fees by exploiting this
857 // match htlc_minimum_msat logic.
858 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
859 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
860 // Note that there is a risk that *previous hops* (those closer to us, as we go
861 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
863 // This might make us end up with a broken route, although this should be super-rare
864 // in practice, both because of how healthy channels look like, and how we pick
865 // channels in add_entry.
866 // Also, this can't be exploited more heavily than *announce a free path and fail
868 cur_hop_transferred_amount_msat += extra_fees_msat;
869 total_fee_paid_msat += extra_fees_msat;
870 cur_hop_fees_msat += extra_fees_msat;
874 // Final hop is a special case: it usually has just value_msat (by design), but also
875 // it still could overpay for the htlc_minimum_msat.
876 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
878 // Propagate updated fees for the use of the channels to one hop back, where they
879 // will be actually paid (fee_msat). The last hop is handled above separately.
880 cur_hop.fee_msat = cur_hop_fees_msat;
883 // Fee for the use of the current hop which will be deducted on the previous hop.
884 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
885 // this channel is free for us.
887 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
888 cur_hop.hop_use_fee_msat = new_fee;
889 total_fee_paid_msat += new_fee;
891 // It should not be possible because this function is called only to reduce the
892 // value. In that case, compute_fee was already called with the same fees for
893 // larger amount and there was no overflow.
902 /// Calculate the fees required to route the given amount over a channel with the given fees.
903 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
904 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
905 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
909 /// Calculate the fees required to route the given amount over a channel with the given fees,
910 /// saturating to [`u64::max_value`].
911 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
912 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
913 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
914 .saturating_add(channel_fees.base_msat as u64)
917 /// The default `features` we assume for a node in a route, when no `features` are known about that
920 /// Default features are:
921 /// * variable_length_onion_optional
922 fn default_node_features() -> NodeFeatures {
923 let mut features = NodeFeatures::empty();
924 features.set_variable_length_onion_optional();
928 /// Finds a route from us (payer) to the given target node (payee).
930 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
931 /// Without this, MPP will only be used if the payee's features are available in the network graph.
933 /// Private routing paths between a public node and the target may be included in `params.payee`.
935 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
936 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
937 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
939 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
940 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
941 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
945 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
946 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
951 /// Panics if first_hops contains channels without short_channel_ids;
952 /// [`ChannelManager::list_usable_channels`] will never include such channels.
954 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
955 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
956 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
957 pub fn find_route<L: Deref, GL: Deref, S: Score>(
958 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
959 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
960 scorer: &S, random_seed_bytes: &[u8; 32]
961 ) -> Result<Route, LightningError>
962 where L::Target: Logger, GL::Target: Logger {
963 let graph_lock = network_graph.read_only();
964 let final_cltv_expiry_delta =
965 if let Some(delta) = route_params.payment_params.final_cltv_expiry_delta { delta }
966 else { route_params.final_cltv_expiry_delta };
967 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
968 route_params.final_value_msat, final_cltv_expiry_delta, logger, scorer,
970 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
974 pub(crate) fn get_route<L: Deref, S: Score>(
975 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
976 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
977 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
978 ) -> Result<Route, LightningError>
979 where L::Target: Logger {
980 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
981 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
983 if payee_node_id == our_node_id {
984 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
987 if final_value_msat > MAX_VALUE_MSAT {
988 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
991 if final_value_msat == 0 {
992 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
995 for route in payment_params.route_hints.iter() {
996 for hop in &route.0 {
997 if hop.src_node_id == payment_params.payee_pubkey {
998 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1002 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1003 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});
1005 if let Some(delta) = payment_params.final_cltv_expiry_delta {
1006 debug_assert_eq!(delta, final_cltv_expiry_delta);
1009 // The general routing idea is the following:
1010 // 1. Fill first/last hops communicated by the caller.
1011 // 2. Attempt to construct a path from payer to payee for transferring
1012 // any ~sufficient (described later) value.
1013 // If succeed, remember which channels were used and how much liquidity they have available,
1014 // so that future paths don't rely on the same liquidity.
1015 // 3. Proceed to the next step if:
1016 // - we hit the recommended target value;
1017 // - OR if we could not construct a new path. Any next attempt will fail too.
1018 // Otherwise, repeat step 2.
1019 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1020 // (not recommended value).
1021 // 5. If yes, proceed. If not, fail routing.
1022 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1023 // transferred up to the transfer target value.
1024 // 7. Reduce the value of the last path until we are sending only the target value.
1025 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1026 // them so that we're not sending two HTLCs along the same path.
1028 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1029 // distance from the payee
1031 // We are not a faithful Dijkstra's implementation because we can change values which impact
1032 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1033 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1034 // the value we are currently attempting to send over a path, we simply reduce the value being
1035 // sent along the path for any hops after that channel. This may imply that later fees (which
1036 // we've already tabulated) are lower because a smaller value is passing through the channels
1037 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1038 // channels which were selected earlier (and which may still be used for other paths without a
1039 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1042 // One potentially problematic case for this algorithm would be if there are many
1043 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1044 // graph walking), we may never find a path which is not liquidity-limited and has lower
1045 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1046 // Because we only consider paths with at least 5% of the total value being sent, the damage
1047 // from such a case should be limited, however this could be further reduced in the future by
1048 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1049 // limits for the purposes of fee calculation.
1051 // Alternatively, we could store more detailed path information in the heap (targets, below)
1052 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1053 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1054 // and practically (as we would need to store dynamically-allocated path information in heap
1055 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1056 // results of such an algorithm would likely be biased towards lower-value paths.
1058 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1059 // outside of our current search value, running a path search more times to gather candidate
1060 // paths at different values. While this may be acceptable, further path searches may increase
1061 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1062 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1063 // the same time, remaining generic across different payment values.
1065 let network_channels = network_graph.channels();
1066 let network_nodes = network_graph.nodes();
1068 if payment_params.max_path_count == 0 {
1069 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1072 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1073 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1075 let allow_mpp = if payment_params.max_path_count == 1 {
1077 } else if let Some(features) = &payment_params.features {
1078 features.supports_basic_mpp()
1079 } else if let Some(node) = network_nodes.get(&payee_node_id) {
1080 if let Some(node_info) = node.announcement_info.as_ref() {
1081 node_info.features.supports_basic_mpp()
1085 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1086 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
1087 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1090 // Prepare the data we'll use for payee-to-payer search by
1091 // inserting first hops suggested by the caller as targets.
1092 // Our search will then attempt to reach them while traversing from the payee node.
1093 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1094 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1095 if let Some(hops) = first_hops {
1097 if chan.get_outbound_payment_scid().is_none() {
1098 panic!("first_hops should be filled in with usable channels, not pending ones");
1100 if chan.counterparty.node_id == *our_node_pubkey {
1101 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1104 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1105 .or_insert(Vec::new())
1108 if first_hop_targets.is_empty() {
1109 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1113 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1114 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1115 // adding duplicate entries when we find a better path to a given node.
1116 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1118 // Map from node_id to information about the best current path to that node, including feerate
1120 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1122 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1123 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1124 // htlc_minimum with extra fees while still finding a cheaper path.
1125 let mut hit_minimum_limit;
1127 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1128 // We start with a path_value of the exact amount we want, and if that generates a route we may
1129 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1130 // amount we want in total across paths, selecting the best subset at the end.
1131 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1132 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1133 let mut path_value_msat = final_value_msat;
1135 // Routing Fragmentation Mitigation heuristic:
1137 // Routing fragmentation across many payment paths increases the overall routing
1138 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1139 // Taking too many smaller paths also increases the chance of payment failure.
1140 // Thus to avoid this effect, we require from our collected links to provide
1141 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1142 // This requirement is currently set to be 1/max_path_count of the payment
1143 // value to ensure we only ever return routes that do not violate this limit.
1144 let minimal_value_contribution_msat: u64 = if allow_mpp {
1145 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1150 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1151 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1152 // drop the requirement by setting this to 0.
1153 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1155 // Keep track of how much liquidity has been used in selected channels. Used to determine
1156 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1157 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1158 // liquidity used in one direction will not offset any used in the opposite direction.
1159 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1160 HashMap::with_capacity(network_nodes.len());
1162 // Keeping track of how much value we already collected across other paths. Helps to decide
1163 // when we want to stop looking for new paths.
1164 let mut already_collected_value_msat = 0;
1166 for (_, channels) in first_hop_targets.iter_mut() {
1167 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1168 // most like to use.
1170 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1171 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1174 // Second, because simply always sorting in descending order would always use our largest
1175 // available outbound capacity, needlessly fragmenting our available channel capacities,
1176 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1177 // which have enough, but not too much, capacity for the payment.
1178 channels.sort_unstable_by(|chan_a, chan_b| {
1179 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1180 // Sort in descending order
1181 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1183 // Sort in ascending order
1184 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1189 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1191 macro_rules! add_entry {
1192 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1193 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1194 // since that value has to be transferred over this channel.
1195 // Returns whether this channel caused an update to `targets`.
1196 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1197 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1198 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1199 // We "return" whether we updated the path at the end, via this:
1200 let mut did_add_update_path_to_src_node = false;
1201 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1202 // practice these cases should be caught earlier:
1203 // - for regular channels at channel announcement (TODO)
1204 // - for first and last hops early in get_route
1205 if $src_node_id != $dest_node_id {
1206 let short_channel_id = $candidate.short_channel_id();
1207 let effective_capacity = $candidate.effective_capacity();
1208 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1210 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1211 // It may be misleading because we might later choose to reduce the value transferred
1212 // over these channels, and the channel which was insufficient might become sufficient.
1213 // Worst case: we drop a good channel here because it can't cover the high following
1214 // fees caused by one expensive channel, but then this channel could have been used
1215 // if the amount being transferred over this path is lower.
1216 // We do this for now, but this is a subject for removal.
1217 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1218 let used_liquidity_msat = used_channel_liquidities
1219 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1220 .map_or(0, |used_liquidity_msat| {
1221 available_value_contribution_msat = available_value_contribution_msat
1222 .saturating_sub(*used_liquidity_msat);
1223 *used_liquidity_msat
1226 // Verify the liquidity offered by this channel complies to the minimal contribution.
1227 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1228 // Do not consider candidate hops that would exceed the maximum path length.
1229 let path_length_to_node = $next_hops_path_length + 1;
1230 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1232 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1233 // In order to already account for some of the privacy enhancing random CLTV
1234 // expiry delta offset we add on top later, we subtract a rough estimate
1235 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1236 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1237 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1238 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1239 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1240 .saturating_add($candidate.cltv_expiry_delta());
1241 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1243 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1244 // Includes paying fees for the use of the following channels.
1245 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1246 Some(result) => result,
1247 // Can't overflow due to how the values were computed right above.
1248 None => unreachable!(),
1250 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1251 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1252 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1254 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1255 let may_overpay_to_meet_path_minimum_msat =
1256 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1257 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1258 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1259 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1261 let payment_failed_on_this_channel =
1262 payment_params.previously_failed_channels.contains(&short_channel_id);
1264 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1265 // bother considering this channel. If retrying with recommended_value_msat may
1266 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1267 // around again with a higher amount.
1268 if !contributes_sufficient_value || exceeds_max_path_length ||
1269 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1270 // Path isn't useful, ignore it and move on.
1271 } else if may_overpay_to_meet_path_minimum_msat {
1272 hit_minimum_limit = true;
1273 } else if over_path_minimum_msat {
1274 // Note that low contribution here (limited by available_liquidity_msat)
1275 // might violate htlc_minimum_msat on the hops which are next along the
1276 // payment path (upstream to the payee). To avoid that, we recompute
1277 // path fees knowing the final path contribution after constructing it.
1278 let path_htlc_minimum_msat = cmp::max(
1279 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1280 .saturating_add($next_hops_path_htlc_minimum_msat),
1281 $candidate.htlc_minimum_msat());
1282 let hm_entry = dist.entry($src_node_id);
1283 let old_entry = hm_entry.or_insert_with(|| {
1284 // If there was previously no known way to access the source node
1285 // (recall it goes payee-to-payer) of short_channel_id, first add a
1286 // semi-dummy record just to compute the fees to reach the source node.
1287 // This will affect our decision on selecting short_channel_id
1288 // as a way to reach the $dest_node_id.
1290 node_id: $dest_node_id.clone(),
1291 candidate: $candidate.clone(),
1293 next_hops_fee_msat: u64::max_value(),
1294 hop_use_fee_msat: u64::max_value(),
1295 total_fee_msat: u64::max_value(),
1296 path_htlc_minimum_msat,
1297 path_penalty_msat: u64::max_value(),
1298 was_processed: false,
1299 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1300 value_contribution_msat,
1304 #[allow(unused_mut)] // We only use the mut in cfg(test)
1305 let mut should_process = !old_entry.was_processed;
1306 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1308 // In test/fuzzing builds, we do extra checks to make sure the skipping
1309 // of already-seen nodes only happens in cases we expect (see below).
1310 if !should_process { should_process = true; }
1314 let mut hop_use_fee_msat = 0;
1315 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1317 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1318 // will have the same effective-fee
1319 if $src_node_id != our_node_id {
1320 // Note that `u64::max_value` means we'll always fail the
1321 // `old_entry.total_fee_msat > total_fee_msat` check below
1322 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1323 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1326 let channel_usage = ChannelUsage {
1327 amount_msat: amount_to_transfer_over_msat,
1328 inflight_htlc_msat: used_liquidity_msat,
1331 let channel_penalty_msat = scorer.channel_penalty_msat(
1332 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1334 let path_penalty_msat = $next_hops_path_penalty_msat
1335 .saturating_add(channel_penalty_msat);
1336 let new_graph_node = RouteGraphNode {
1337 node_id: $src_node_id,
1338 lowest_fee_to_node: total_fee_msat,
1339 total_cltv_delta: hop_total_cltv_delta,
1340 value_contribution_msat,
1341 path_htlc_minimum_msat,
1343 path_length_to_node,
1346 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1347 // if this way is cheaper than the already known
1348 // (considering the cost to "reach" this channel from the route destination,
1349 // the cost of using this channel,
1350 // and the cost of routing to the source node of this channel).
1351 // Also, consider that htlc_minimum_msat_difference, because we might end up
1352 // paying it. Consider the following exploit:
1353 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1354 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1355 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1356 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1358 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1359 // but it may require additional tracking - we don't want to double-count
1360 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1361 // can't use something that may decrease on future hops.
1362 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1363 .saturating_add(old_entry.path_penalty_msat);
1364 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1365 .saturating_add(path_penalty_msat);
1367 if !old_entry.was_processed && new_cost < old_cost {
1368 targets.push(new_graph_node);
1369 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1370 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1371 old_entry.total_fee_msat = total_fee_msat;
1372 old_entry.node_id = $dest_node_id.clone();
1373 old_entry.candidate = $candidate.clone();
1374 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1375 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1376 old_entry.path_penalty_msat = path_penalty_msat;
1377 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1379 old_entry.value_contribution_msat = value_contribution_msat;
1381 did_add_update_path_to_src_node = true;
1382 } else if old_entry.was_processed && new_cost < old_cost {
1383 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1385 // If we're skipping processing a node which was previously
1386 // processed even though we found another path to it with a
1387 // cheaper fee, check that it was because the second path we
1388 // found (which we are processing now) has a lower value
1389 // contribution due to an HTLC minimum limit.
1391 // e.g. take a graph with two paths from node 1 to node 2, one
1392 // through channel A, and one through channel B. Channel A and
1393 // B are both in the to-process heap, with their scores set by
1394 // a higher htlc_minimum than fee.
1395 // Channel A is processed first, and the channels onwards from
1396 // node 1 are added to the to-process heap. Thereafter, we pop
1397 // Channel B off of the heap, note that it has a much more
1398 // restrictive htlc_maximum_msat, and recalculate the fees for
1399 // all of node 1's channels using the new, reduced, amount.
1401 // This would be bogus - we'd be selecting a higher-fee path
1402 // with a lower htlc_maximum_msat instead of the one we'd
1403 // already decided to use.
1404 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1406 value_contribution_msat + path_penalty_msat <
1407 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1415 did_add_update_path_to_src_node
1419 let default_node_features = default_node_features();
1421 // Find ways (channels with destination) to reach a given node and store them
1422 // in the corresponding data structures (routing graph etc).
1423 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1424 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1425 // This data can later be helpful to optimize routing (pay lower fees).
1426 macro_rules! add_entries_to_cheapest_to_target_node {
1427 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1428 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1429 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1430 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1431 let was_processed = elem.was_processed;
1432 elem.was_processed = true;
1435 // Entries are added to dist in add_entry!() when there is a channel from a node.
1436 // Because there are no channels from payee, it will not have a dist entry at this point.
1437 // If we're processing any other node, it is always be the result of a channel from it.
1438 assert_eq!($node_id, payee_node_id);
1443 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1444 for details in first_channels {
1445 let candidate = CandidateRouteHop::FirstHop { details };
1446 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1447 $next_hops_value_contribution,
1448 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1449 $next_hops_cltv_delta, $next_hops_path_length);
1453 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1456 &default_node_features
1459 if !features.requires_unknown_bits() {
1460 for chan_id in $node.channels.iter() {
1461 let chan = network_channels.get(chan_id).unwrap();
1462 if !chan.features.requires_unknown_bits() {
1463 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1464 if first_hops.is_none() || *source != our_node_id {
1465 if directed_channel.direction().enabled {
1466 let candidate = CandidateRouteHop::PublicHop {
1467 info: directed_channel,
1468 short_channel_id: *chan_id,
1470 add_entry!(candidate, *source, $node_id,
1471 $fee_to_target_msat,
1472 $next_hops_value_contribution,
1473 $next_hops_path_htlc_minimum_msat,
1474 $next_hops_path_penalty_msat,
1475 $next_hops_cltv_delta, $next_hops_path_length);
1486 let mut payment_paths = Vec::<PaymentPath>::new();
1488 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1489 'paths_collection: loop {
1490 // For every new path, start from scratch, except for used_channel_liquidities, which
1491 // helps to avoid reusing previously selected paths in future iterations.
1494 hit_minimum_limit = false;
1496 // If first hop is a private channel and the only way to reach the payee, this is the only
1497 // place where it could be added.
1498 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1499 for details in first_channels {
1500 let candidate = CandidateRouteHop::FirstHop { details };
1501 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1503 log_trace!(logger, "{} direct route to payee via SCID {}",
1504 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1508 // Add the payee as a target, so that the payee-to-payer
1509 // search algorithm knows what to start with.
1510 match network_nodes.get(&payee_node_id) {
1511 // The payee is not in our network graph, so nothing to add here.
1512 // There is still a chance of reaching them via last_hops though,
1513 // so don't yet fail the payment here.
1514 // If not, targets.pop() will not even let us enter the loop in step 2.
1517 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1522 // If a caller provided us with last hops, add them to routing targets. Since this happens
1523 // earlier than general path finding, they will be somewhat prioritized, although currently
1524 // it matters only if the fees are exactly the same.
1525 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1526 let first_hop_in_route = &(route.0)[0];
1527 let have_hop_src_in_graph =
1528 // Only add the hops in this route to our candidate set if either
1529 // we have a direct channel to the first hop or the first hop is
1530 // in the regular network graph.
1531 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1532 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1533 if have_hop_src_in_graph {
1534 // We start building the path from reverse, i.e., from payee
1535 // to the first RouteHintHop in the path.
1536 let hop_iter = route.0.iter().rev();
1537 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1538 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1539 let mut hop_used = true;
1540 let mut aggregate_next_hops_fee_msat: u64 = 0;
1541 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1542 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1543 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1544 let mut aggregate_next_hops_path_length: u8 = 0;
1546 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1547 let source = NodeId::from_pubkey(&hop.src_node_id);
1548 let target = NodeId::from_pubkey(&prev_hop_id);
1549 let candidate = network_channels
1550 .get(&hop.short_channel_id)
1551 .and_then(|channel| channel.as_directed_to(&target))
1552 .map(|(info, _)| CandidateRouteHop::PublicHop {
1554 short_channel_id: hop.short_channel_id,
1556 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1558 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1559 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1560 aggregate_next_hops_path_penalty_msat,
1561 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1562 // If this hop was not used then there is no use checking the preceding
1563 // hops in the RouteHint. We can break by just searching for a direct
1564 // channel between last checked hop and first_hop_targets.
1568 let used_liquidity_msat = used_channel_liquidities
1569 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1570 let channel_usage = ChannelUsage {
1571 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1572 inflight_htlc_msat: used_liquidity_msat,
1573 effective_capacity: candidate.effective_capacity(),
1575 let channel_penalty_msat = scorer.channel_penalty_msat(
1576 hop.short_channel_id, &source, &target, channel_usage
1578 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1579 .saturating_add(channel_penalty_msat);
1581 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1582 .saturating_add(hop.cltv_expiry_delta as u32);
1584 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1587 // Searching for a direct channel between last checked hop and first_hop_targets
1588 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1589 for details in first_channels {
1590 let candidate = CandidateRouteHop::FirstHop { details };
1591 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1592 aggregate_next_hops_fee_msat, path_value_msat,
1593 aggregate_next_hops_path_htlc_minimum_msat,
1594 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1595 aggregate_next_hops_path_length);
1603 // In the next values of the iterator, the aggregate fees already reflects
1604 // the sum of value sent from payer (final_value_msat) and routing fees
1605 // for the last node in the RouteHint. We need to just add the fees to
1606 // route through the current node so that the preceding node (next iteration)
1608 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1609 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1610 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1612 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1613 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1614 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1615 .checked_add(hop_htlc_minimum_msat_inc);
1616 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1618 if idx == route.0.len() - 1 {
1619 // The last hop in this iterator is the first hop in
1620 // overall RouteHint.
1621 // If this hop connects to a node with which we have a direct channel,
1622 // ignore the network graph and, if the last hop was added, add our
1623 // direct channel to the candidate set.
1625 // Note that we *must* check if the last hop was added as `add_entry`
1626 // always assumes that the third argument is a node to which we have a
1628 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1629 for details in first_channels {
1630 let candidate = CandidateRouteHop::FirstHop { details };
1631 add_entry!(candidate, our_node_id,
1632 NodeId::from_pubkey(&hop.src_node_id),
1633 aggregate_next_hops_fee_msat, path_value_msat,
1634 aggregate_next_hops_path_htlc_minimum_msat,
1635 aggregate_next_hops_path_penalty_msat,
1636 aggregate_next_hops_cltv_delta,
1637 aggregate_next_hops_path_length);
1645 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1647 // At this point, targets are filled with the data from first and
1648 // last hops communicated by the caller, and the payment receiver.
1649 let mut found_new_path = false;
1652 // If this loop terminates due the exhaustion of targets, two situations are possible:
1653 // - not enough outgoing liquidity:
1654 // 0 < already_collected_value_msat < final_value_msat
1655 // - enough outgoing liquidity:
1656 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1657 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1658 // paths_collection will be stopped because found_new_path==false.
1659 // This is not necessarily a routing failure.
1660 '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() {
1662 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1663 // traversing the graph and arrange the path out of what we found.
1664 if node_id == our_node_id {
1665 let mut new_entry = dist.remove(&our_node_id).unwrap();
1666 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1669 let mut features_set = false;
1670 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1671 for details in first_channels {
1672 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1673 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1674 features_set = true;
1680 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1681 if let Some(node_info) = node.announcement_info.as_ref() {
1682 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1684 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1687 // We can fill in features for everything except hops which were
1688 // provided via the invoice we're paying. We could guess based on the
1689 // recipient's features but for now we simply avoid guessing at all.
1693 // Means we succesfully traversed from the payer to the payee, now
1694 // save this path for the payment route. Also, update the liquidity
1695 // remaining on the used hops, so that we take them into account
1696 // while looking for more paths.
1697 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1701 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1702 Some(payment_hop) => payment_hop,
1703 // We can't arrive at None because, if we ever add an entry to targets,
1704 // we also fill in the entry in dist (see add_entry!).
1705 None => unreachable!(),
1707 // We "propagate" the fees one hop backward (topologically) here,
1708 // so that fees paid for a HTLC forwarding on the current channel are
1709 // associated with the previous channel (where they will be subtracted).
1710 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1711 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1713 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1714 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1716 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1717 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1719 let mut payment_path = PaymentPath {hops: ordered_hops};
1721 // We could have possibly constructed a slightly inconsistent path: since we reduce
1722 // value being transferred along the way, we could have violated htlc_minimum_msat
1723 // on some channels we already passed (assuming dest->source direction). Here, we
1724 // recompute the fees again, so that if that's the case, we match the currently
1725 // underpaid htlc_minimum_msat with fees.
1726 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1727 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1728 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1730 // Since a path allows to transfer as much value as
1731 // the smallest channel it has ("bottleneck"), we should recompute
1732 // the fees so sender HTLC don't overpay fees when traversing
1733 // larger channels than the bottleneck. This may happen because
1734 // when we were selecting those channels we were not aware how much value
1735 // this path will transfer, and the relative fee for them
1736 // might have been computed considering a larger value.
1737 // Remember that we used these channels so that we don't rely
1738 // on the same liquidity in future paths.
1739 let mut prevented_redundant_path_selection = false;
1740 let prev_hop_iter = core::iter::once(&our_node_id)
1741 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1742 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1743 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1744 let used_liquidity_msat = used_channel_liquidities
1745 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1746 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1747 .or_insert(spent_on_hop_msat);
1748 let hop_capacity = hop.candidate.effective_capacity();
1749 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1750 if *used_liquidity_msat == hop_max_msat {
1751 // If this path used all of this channel's available liquidity, we know
1752 // this path will not be selected again in the next loop iteration.
1753 prevented_redundant_path_selection = true;
1755 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1757 if !prevented_redundant_path_selection {
1758 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1759 // we'll probably end up picking the same path again on the next iteration.
1760 // Decrease the available liquidity of a hop in the middle of the path.
1761 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1762 let exhausted = u64::max_value();
1763 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1764 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1765 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1768 // Track the total amount all our collected paths allow to send so that we know
1769 // when to stop looking for more paths
1770 already_collected_value_msat += value_contribution_msat;
1772 payment_paths.push(payment_path);
1773 found_new_path = true;
1774 break 'path_construction;
1777 // If we found a path back to the payee, we shouldn't try to process it again. This is
1778 // the equivalent of the `elem.was_processed` check in
1779 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1780 if node_id == payee_node_id { continue 'path_construction; }
1782 // Otherwise, since the current target node is not us,
1783 // keep "unrolling" the payment graph from payee to payer by
1784 // finding a way to reach the current target from the payer side.
1785 match network_nodes.get(&node_id) {
1788 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1789 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1790 total_cltv_delta, path_length_to_node);
1796 if !found_new_path && channel_saturation_pow_half != 0 {
1797 channel_saturation_pow_half = 0;
1798 continue 'paths_collection;
1800 // If we don't support MPP, no use trying to gather more value ever.
1801 break 'paths_collection;
1805 // Stop either when the recommended value is reached or if no new path was found in this
1807 // In the latter case, making another path finding attempt won't help,
1808 // because we deterministically terminated the search due to low liquidity.
1809 if !found_new_path && channel_saturation_pow_half != 0 {
1810 channel_saturation_pow_half = 0;
1811 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1812 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1813 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1814 break 'paths_collection;
1815 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1816 // Further, if this was our first walk of the graph, and we weren't limited by an
1817 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1818 // limited by an htlc_minimum_msat value, find another path with a higher value,
1819 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1820 // still keeping a lower total fee than this path.
1821 if !hit_minimum_limit {
1822 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1823 break 'paths_collection;
1825 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1826 path_value_msat = recommended_value_msat;
1831 if payment_paths.len() == 0 {
1832 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1835 if already_collected_value_msat < final_value_msat {
1836 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1840 let mut selected_route = payment_paths;
1842 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1843 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1845 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1846 // the value they contribute towards the payment amount.
1847 // We sort in descending order as we will remove from the front in `retain`, next.
1848 selected_route.sort_unstable_by(|a, b|
1849 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1850 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1853 // We should make sure that at least 1 path left.
1854 let mut paths_left = selected_route.len();
1855 selected_route.retain(|path| {
1856 if paths_left == 1 {
1859 let path_value_msat = path.get_value_msat();
1860 if path_value_msat <= overpaid_value_msat {
1861 overpaid_value_msat -= path_value_msat;
1867 debug_assert!(selected_route.len() > 0);
1869 if overpaid_value_msat != 0 {
1871 // Now, subtract the remaining overpaid value from the most-expensive path.
1872 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1873 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1874 selected_route.sort_unstable_by(|a, b| {
1875 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1876 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1877 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1879 let expensive_payment_path = selected_route.first_mut().unwrap();
1881 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1882 // can't go negative.
1883 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1884 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1888 // Sort by the path itself and combine redundant paths.
1889 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1890 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1892 selected_route.sort_unstable_by_key(|path| {
1893 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1894 debug_assert!(path.hops.len() <= key.len());
1895 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1900 for idx in 0..(selected_route.len() - 1) {
1901 if idx + 1 >= selected_route.len() { break; }
1902 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1903 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1904 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1905 selected_route[idx].update_value_and_recompute_fees(new_value);
1906 selected_route.remove(idx + 1);
1910 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1911 for payment_path in selected_route {
1912 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1914 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)})?,
1915 node_features: node_features.clone(),
1916 short_channel_id: payment_hop.candidate.short_channel_id(),
1917 channel_features: payment_hop.candidate.features(),
1918 fee_msat: payment_hop.fee_msat,
1919 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1921 }).collect::<Vec<_>>();
1922 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1923 // applicable for the previous hop.
1924 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1925 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1927 selected_paths.push(path);
1929 // Make sure we would never create a route with more paths than we allow.
1930 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1932 if let Some(features) = &payment_params.features {
1933 for path in selected_paths.iter_mut() {
1934 if let Ok(route_hop) = path.last_mut().unwrap() {
1935 route_hop.node_features = features.to_context();
1941 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1942 payment_params: Some(payment_params.clone()),
1944 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1948 // When an adversarial intermediary node observes a payment, it may be able to infer its
1949 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1950 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1951 // payment path by adding a randomized 'shadow route' offset to the final hop.
1952 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1953 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1955 let network_channels = network_graph.channels();
1956 let network_nodes = network_graph.nodes();
1958 for path in route.paths.iter_mut() {
1959 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1961 // Remember the last three nodes of the random walk and avoid looping back on them.
1962 // Init with the last three nodes from the actual path, if possible.
1963 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1964 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1965 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1967 // Choose the last publicly known node as the starting point for the random walk.
1968 let mut cur_hop: Option<NodeId> = None;
1969 let mut path_nonce = [0u8; 12];
1970 if let Some(starting_hop) = path.iter().rev()
1971 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
1972 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
1973 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
1976 // Init PRNG with the path-dependant nonce, which is static for private paths.
1977 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
1978 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
1980 // Pick a random path length in [1 .. 3]
1981 prng.process_in_place(&mut random_path_bytes);
1982 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
1984 for random_hop in 0..random_walk_length {
1985 // If we don't find a suitable offset in the public network graph, we default to
1986 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
1987 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
1989 if let Some(cur_node_id) = cur_hop {
1990 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
1991 // Randomly choose the next unvisited hop.
1992 prng.process_in_place(&mut random_path_bytes);
1993 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
1994 .checked_rem(cur_node.channels.len())
1995 .and_then(|index| cur_node.channels.get(index))
1996 .and_then(|id| network_channels.get(id)) {
1997 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
1998 if !nodes_to_avoid.iter().any(|x| x == next_id) {
1999 nodes_to_avoid[random_hop] = *next_id;
2000 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2001 cur_hop = Some(*next_id);
2008 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2009 .checked_add(random_hop_offset)
2010 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2013 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2014 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2015 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2017 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2018 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2019 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
2020 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2021 max_path_offset = cmp::max(
2022 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2023 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2024 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2026 // Add 'shadow' CLTV offset to the final hop
2027 if let Some(last_hop) = path.last_mut() {
2028 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2029 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2034 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2035 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2037 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2038 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2039 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2040 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2041 ) -> Result<Route, LightningError>
2042 where L::Target: Logger, GL::Target: Logger {
2043 let graph_lock = network_graph.read_only();
2044 let mut route = build_route_from_hops_internal(
2045 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2046 route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, random_seed_bytes)?;
2047 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2051 fn build_route_from_hops_internal<L: Deref>(
2052 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2053 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
2054 logger: L, random_seed_bytes: &[u8; 32]
2055 ) -> Result<Route, LightningError> where L::Target: Logger {
2058 our_node_id: NodeId,
2059 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2062 impl Score for HopScorer {
2063 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2064 _usage: ChannelUsage) -> u64
2066 let mut cur_id = self.our_node_id;
2067 for i in 0..self.hop_ids.len() {
2068 if let Some(next_id) = self.hop_ids[i] {
2069 if cur_id == *source && next_id == *target {
2080 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2082 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
2084 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2086 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
2089 impl<'a> Writeable for HopScorer {
2091 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2096 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2097 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2100 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2101 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2102 for i in 0..hops.len() {
2103 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2106 let scorer = HopScorer { our_node_id, hop_ids };
2108 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2109 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
2114 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2115 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2116 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2117 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2118 use crate::routing::scoring::{ChannelUsage, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
2119 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2120 use crate::chain::transaction::OutPoint;
2121 use crate::chain::keysinterface::EntropySource;
2122 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2123 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2124 use crate::ln::channelmanager;
2125 use crate::util::config::UserConfig;
2126 use crate::util::test_utils as ln_test_utils;
2127 use crate::util::chacha20::ChaCha20;
2129 use crate::util::ser::{Writeable, Writer};
2131 use bitcoin::hashes::Hash;
2132 use bitcoin::network::constants::Network;
2133 use bitcoin::blockdata::constants::genesis_block;
2134 use bitcoin::blockdata::script::Builder;
2135 use bitcoin::blockdata::opcodes;
2136 use bitcoin::blockdata::transaction::TxOut;
2140 use bitcoin::secp256k1::{PublicKey,SecretKey};
2141 use bitcoin::secp256k1::Secp256k1;
2143 use crate::prelude::*;
2144 use crate::sync::Arc;
2146 use core::convert::TryInto;
2148 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2149 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2150 channelmanager::ChannelDetails {
2151 channel_id: [0; 32],
2152 counterparty: channelmanager::ChannelCounterparty {
2155 unspendable_punishment_reserve: 0,
2156 forwarding_info: None,
2157 outbound_htlc_minimum_msat: None,
2158 outbound_htlc_maximum_msat: None,
2160 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2163 outbound_scid_alias: None,
2164 inbound_scid_alias: None,
2165 channel_value_satoshis: 0,
2168 outbound_capacity_msat,
2169 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2170 inbound_capacity_msat: 42,
2171 unspendable_punishment_reserve: None,
2172 confirmations_required: None,
2173 confirmations: None,
2174 force_close_spend_delay: None,
2175 is_outbound: true, is_channel_ready: true,
2176 is_usable: true, is_public: true,
2177 inbound_htlc_minimum_msat: None,
2178 inbound_htlc_maximum_msat: None,
2184 fn simple_route_test() {
2185 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2186 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2187 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2188 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2189 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2190 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2192 // Simple route to 2 via 1
2194 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 0, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2195 assert_eq!(err, "Cannot send a payment of 0 msat");
2196 } else { panic!(); }
2198 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2199 assert_eq!(route.paths[0].len(), 2);
2201 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2202 assert_eq!(route.paths[0][0].short_channel_id, 2);
2203 assert_eq!(route.paths[0][0].fee_msat, 100);
2204 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2205 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2206 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2208 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2209 assert_eq!(route.paths[0][1].short_channel_id, 4);
2210 assert_eq!(route.paths[0][1].fee_msat, 100);
2211 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2212 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2213 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2217 fn invalid_first_hop_test() {
2218 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2219 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2220 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2221 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2222 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2223 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2225 // Simple route to 2 via 1
2227 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2229 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2230 get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2231 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2232 } else { panic!(); }
2234 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2235 assert_eq!(route.paths[0].len(), 2);
2239 fn htlc_minimum_test() {
2240 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2241 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2242 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2243 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2244 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2245 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2247 // Simple route to 2 via 1
2249 // Disable other paths
2250 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2251 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2252 short_channel_id: 12,
2254 flags: 2, // to disable
2255 cltv_expiry_delta: 0,
2256 htlc_minimum_msat: 0,
2257 htlc_maximum_msat: MAX_VALUE_MSAT,
2259 fee_proportional_millionths: 0,
2260 excess_data: Vec::new()
2262 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2263 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2264 short_channel_id: 3,
2266 flags: 2, // to disable
2267 cltv_expiry_delta: 0,
2268 htlc_minimum_msat: 0,
2269 htlc_maximum_msat: MAX_VALUE_MSAT,
2271 fee_proportional_millionths: 0,
2272 excess_data: Vec::new()
2274 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2276 short_channel_id: 13,
2278 flags: 2, // to disable
2279 cltv_expiry_delta: 0,
2280 htlc_minimum_msat: 0,
2281 htlc_maximum_msat: MAX_VALUE_MSAT,
2283 fee_proportional_millionths: 0,
2284 excess_data: Vec::new()
2286 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2288 short_channel_id: 6,
2290 flags: 2, // to disable
2291 cltv_expiry_delta: 0,
2292 htlc_minimum_msat: 0,
2293 htlc_maximum_msat: MAX_VALUE_MSAT,
2295 fee_proportional_millionths: 0,
2296 excess_data: Vec::new()
2298 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2299 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2300 short_channel_id: 7,
2302 flags: 2, // to disable
2303 cltv_expiry_delta: 0,
2304 htlc_minimum_msat: 0,
2305 htlc_maximum_msat: MAX_VALUE_MSAT,
2307 fee_proportional_millionths: 0,
2308 excess_data: Vec::new()
2311 // Check against amount_to_transfer_over_msat.
2312 // Set minimal HTLC of 200_000_000 msat.
2313 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2314 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2315 short_channel_id: 2,
2318 cltv_expiry_delta: 0,
2319 htlc_minimum_msat: 200_000_000,
2320 htlc_maximum_msat: MAX_VALUE_MSAT,
2322 fee_proportional_millionths: 0,
2323 excess_data: Vec::new()
2326 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2328 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2330 short_channel_id: 4,
2333 cltv_expiry_delta: 0,
2334 htlc_minimum_msat: 0,
2335 htlc_maximum_msat: 199_999_999,
2337 fee_proportional_millionths: 0,
2338 excess_data: Vec::new()
2341 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2342 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2343 assert_eq!(err, "Failed to find a path to the given destination");
2344 } else { panic!(); }
2346 // Lift the restriction on the first hop.
2347 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2349 short_channel_id: 2,
2352 cltv_expiry_delta: 0,
2353 htlc_minimum_msat: 0,
2354 htlc_maximum_msat: MAX_VALUE_MSAT,
2356 fee_proportional_millionths: 0,
2357 excess_data: Vec::new()
2360 // A payment above the minimum should pass
2361 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2362 assert_eq!(route.paths[0].len(), 2);
2366 fn htlc_minimum_overpay_test() {
2367 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2368 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2369 let config = UserConfig::default();
2370 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
2371 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2372 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2373 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2375 // A route to node#2 via two paths.
2376 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2377 // Thus, they can't send 60 without overpaying.
2378 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2380 short_channel_id: 2,
2383 cltv_expiry_delta: 0,
2384 htlc_minimum_msat: 35_000,
2385 htlc_maximum_msat: 40_000,
2387 fee_proportional_millionths: 0,
2388 excess_data: Vec::new()
2390 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2391 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2392 short_channel_id: 12,
2395 cltv_expiry_delta: 0,
2396 htlc_minimum_msat: 35_000,
2397 htlc_maximum_msat: 40_000,
2399 fee_proportional_millionths: 0,
2400 excess_data: Vec::new()
2404 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2406 short_channel_id: 13,
2409 cltv_expiry_delta: 0,
2410 htlc_minimum_msat: 0,
2411 htlc_maximum_msat: MAX_VALUE_MSAT,
2413 fee_proportional_millionths: 0,
2414 excess_data: Vec::new()
2416 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2417 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2418 short_channel_id: 4,
2421 cltv_expiry_delta: 0,
2422 htlc_minimum_msat: 0,
2423 htlc_maximum_msat: MAX_VALUE_MSAT,
2425 fee_proportional_millionths: 0,
2426 excess_data: Vec::new()
2429 // Disable other paths
2430 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2432 short_channel_id: 1,
2434 flags: 2, // to disable
2435 cltv_expiry_delta: 0,
2436 htlc_minimum_msat: 0,
2437 htlc_maximum_msat: MAX_VALUE_MSAT,
2439 fee_proportional_millionths: 0,
2440 excess_data: Vec::new()
2443 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2444 // Overpay fees to hit htlc_minimum_msat.
2445 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2446 // TODO: this could be better balanced to overpay 10k and not 15k.
2447 assert_eq!(overpaid_fees, 15_000);
2449 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2450 // while taking even more fee to match htlc_minimum_msat.
2451 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2453 short_channel_id: 12,
2456 cltv_expiry_delta: 0,
2457 htlc_minimum_msat: 65_000,
2458 htlc_maximum_msat: 80_000,
2460 fee_proportional_millionths: 0,
2461 excess_data: Vec::new()
2463 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2465 short_channel_id: 2,
2468 cltv_expiry_delta: 0,
2469 htlc_minimum_msat: 0,
2470 htlc_maximum_msat: MAX_VALUE_MSAT,
2472 fee_proportional_millionths: 0,
2473 excess_data: Vec::new()
2475 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2477 short_channel_id: 4,
2480 cltv_expiry_delta: 0,
2481 htlc_minimum_msat: 0,
2482 htlc_maximum_msat: MAX_VALUE_MSAT,
2484 fee_proportional_millionths: 100_000,
2485 excess_data: Vec::new()
2488 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2489 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2490 assert_eq!(route.paths.len(), 1);
2491 assert_eq!(route.paths[0][0].short_channel_id, 12);
2492 let fees = route.paths[0][0].fee_msat;
2493 assert_eq!(fees, 5_000);
2495 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2496 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2497 // the other channel.
2498 assert_eq!(route.paths.len(), 1);
2499 assert_eq!(route.paths[0][0].short_channel_id, 2);
2500 let fees = route.paths[0][0].fee_msat;
2501 assert_eq!(fees, 5_000);
2505 fn disable_channels_test() {
2506 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2507 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2508 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2509 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2510 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2511 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2513 // // Disable channels 4 and 12 by flags=2
2514 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2516 short_channel_id: 4,
2518 flags: 2, // to disable
2519 cltv_expiry_delta: 0,
2520 htlc_minimum_msat: 0,
2521 htlc_maximum_msat: MAX_VALUE_MSAT,
2523 fee_proportional_millionths: 0,
2524 excess_data: Vec::new()
2526 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2528 short_channel_id: 12,
2530 flags: 2, // to disable
2531 cltv_expiry_delta: 0,
2532 htlc_minimum_msat: 0,
2533 htlc_maximum_msat: MAX_VALUE_MSAT,
2535 fee_proportional_millionths: 0,
2536 excess_data: Vec::new()
2539 // If all the channels require some features we don't understand, route should fail
2540 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2541 assert_eq!(err, "Failed to find a path to the given destination");
2542 } else { panic!(); }
2544 // If we specify a channel to node7, that overrides our local channel view and that gets used
2545 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2546 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2547 assert_eq!(route.paths[0].len(), 2);
2549 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2550 assert_eq!(route.paths[0][0].short_channel_id, 42);
2551 assert_eq!(route.paths[0][0].fee_msat, 200);
2552 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2553 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2554 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2556 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2557 assert_eq!(route.paths[0][1].short_channel_id, 13);
2558 assert_eq!(route.paths[0][1].fee_msat, 100);
2559 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2560 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2561 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2565 fn disable_node_test() {
2566 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2567 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2568 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2569 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2570 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2571 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2573 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2574 let mut unknown_features = NodeFeatures::empty();
2575 unknown_features.set_unknown_feature_required();
2576 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2577 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2578 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2580 // If all nodes require some features we don't understand, route should fail
2581 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2582 assert_eq!(err, "Failed to find a path to the given destination");
2583 } else { panic!(); }
2585 // If we specify a channel to node7, that overrides our local channel view and that gets used
2586 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2587 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2588 assert_eq!(route.paths[0].len(), 2);
2590 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2591 assert_eq!(route.paths[0][0].short_channel_id, 42);
2592 assert_eq!(route.paths[0][0].fee_msat, 200);
2593 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2594 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2595 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2597 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2598 assert_eq!(route.paths[0][1].short_channel_id, 13);
2599 assert_eq!(route.paths[0][1].fee_msat, 100);
2600 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2601 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2602 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2604 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2605 // naively) assume that the user checked the feature bits on the invoice, which override
2606 // the node_announcement.
2610 fn our_chans_test() {
2611 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2612 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2613 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2614 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2615 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2617 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2618 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
2619 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2620 assert_eq!(route.paths[0].len(), 3);
2622 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2623 assert_eq!(route.paths[0][0].short_channel_id, 2);
2624 assert_eq!(route.paths[0][0].fee_msat, 200);
2625 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2626 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2627 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2629 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2630 assert_eq!(route.paths[0][1].short_channel_id, 4);
2631 assert_eq!(route.paths[0][1].fee_msat, 100);
2632 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2633 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2634 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2636 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2637 assert_eq!(route.paths[0][2].short_channel_id, 3);
2638 assert_eq!(route.paths[0][2].fee_msat, 100);
2639 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2640 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2641 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2643 // If we specify a channel to node7, that overrides our local channel view and that gets used
2644 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2645 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2646 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2647 assert_eq!(route.paths[0].len(), 2);
2649 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2650 assert_eq!(route.paths[0][0].short_channel_id, 42);
2651 assert_eq!(route.paths[0][0].fee_msat, 200);
2652 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2653 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2654 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2656 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2657 assert_eq!(route.paths[0][1].short_channel_id, 13);
2658 assert_eq!(route.paths[0][1].fee_msat, 100);
2659 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2660 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2661 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2664 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2665 let zero_fees = RoutingFees {
2667 proportional_millionths: 0,
2669 vec![RouteHint(vec![RouteHintHop {
2670 src_node_id: nodes[3],
2671 short_channel_id: 8,
2673 cltv_expiry_delta: (8 << 4) | 1,
2674 htlc_minimum_msat: None,
2675 htlc_maximum_msat: None,
2677 ]), RouteHint(vec![RouteHintHop {
2678 src_node_id: nodes[4],
2679 short_channel_id: 9,
2682 proportional_millionths: 0,
2684 cltv_expiry_delta: (9 << 4) | 1,
2685 htlc_minimum_msat: None,
2686 htlc_maximum_msat: None,
2687 }]), RouteHint(vec![RouteHintHop {
2688 src_node_id: nodes[5],
2689 short_channel_id: 10,
2691 cltv_expiry_delta: (10 << 4) | 1,
2692 htlc_minimum_msat: None,
2693 htlc_maximum_msat: None,
2697 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2698 let zero_fees = RoutingFees {
2700 proportional_millionths: 0,
2702 vec![RouteHint(vec![RouteHintHop {
2703 src_node_id: nodes[2],
2704 short_channel_id: 5,
2707 proportional_millionths: 0,
2709 cltv_expiry_delta: (5 << 4) | 1,
2710 htlc_minimum_msat: None,
2711 htlc_maximum_msat: None,
2713 src_node_id: nodes[3],
2714 short_channel_id: 8,
2716 cltv_expiry_delta: (8 << 4) | 1,
2717 htlc_minimum_msat: None,
2718 htlc_maximum_msat: None,
2720 ]), RouteHint(vec![RouteHintHop {
2721 src_node_id: nodes[4],
2722 short_channel_id: 9,
2725 proportional_millionths: 0,
2727 cltv_expiry_delta: (9 << 4) | 1,
2728 htlc_minimum_msat: None,
2729 htlc_maximum_msat: None,
2730 }]), RouteHint(vec![RouteHintHop {
2731 src_node_id: nodes[5],
2732 short_channel_id: 10,
2734 cltv_expiry_delta: (10 << 4) | 1,
2735 htlc_minimum_msat: None,
2736 htlc_maximum_msat: None,
2741 fn partial_route_hint_test() {
2742 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2743 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2744 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2745 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2746 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2748 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2749 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2750 // RouteHint may be partially used by the algo to build the best path.
2752 // First check that last hop can't have its source as the payee.
2753 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2754 src_node_id: nodes[6],
2755 short_channel_id: 8,
2758 proportional_millionths: 0,
2760 cltv_expiry_delta: (8 << 4) | 1,
2761 htlc_minimum_msat: None,
2762 htlc_maximum_msat: None,
2765 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2766 invalid_last_hops.push(invalid_last_hop);
2768 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops);
2769 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2770 assert_eq!(err, "Route hint cannot have the payee as the source.");
2771 } else { panic!(); }
2774 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes));
2775 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2776 assert_eq!(route.paths[0].len(), 5);
2778 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2779 assert_eq!(route.paths[0][0].short_channel_id, 2);
2780 assert_eq!(route.paths[0][0].fee_msat, 100);
2781 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2782 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2783 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2785 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2786 assert_eq!(route.paths[0][1].short_channel_id, 4);
2787 assert_eq!(route.paths[0][1].fee_msat, 0);
2788 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2789 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2790 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2792 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2793 assert_eq!(route.paths[0][2].short_channel_id, 6);
2794 assert_eq!(route.paths[0][2].fee_msat, 0);
2795 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2796 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2797 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2799 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2800 assert_eq!(route.paths[0][3].short_channel_id, 11);
2801 assert_eq!(route.paths[0][3].fee_msat, 0);
2802 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2803 // If we have a peer in the node map, we'll use their features here since we don't have
2804 // a way of figuring out their features from the invoice:
2805 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2806 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2808 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2809 assert_eq!(route.paths[0][4].short_channel_id, 8);
2810 assert_eq!(route.paths[0][4].fee_msat, 100);
2811 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2812 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2813 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2816 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2817 let zero_fees = RoutingFees {
2819 proportional_millionths: 0,
2821 vec![RouteHint(vec![RouteHintHop {
2822 src_node_id: nodes[3],
2823 short_channel_id: 8,
2825 cltv_expiry_delta: (8 << 4) | 1,
2826 htlc_minimum_msat: None,
2827 htlc_maximum_msat: None,
2828 }]), RouteHint(vec![
2830 ]), RouteHint(vec![RouteHintHop {
2831 src_node_id: nodes[5],
2832 short_channel_id: 10,
2834 cltv_expiry_delta: (10 << 4) | 1,
2835 htlc_minimum_msat: None,
2836 htlc_maximum_msat: None,
2841 fn ignores_empty_last_hops_test() {
2842 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2843 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2844 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes));
2845 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2846 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2847 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2849 // Test handling of an empty RouteHint passed in Invoice.
2851 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2852 assert_eq!(route.paths[0].len(), 5);
2854 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2855 assert_eq!(route.paths[0][0].short_channel_id, 2);
2856 assert_eq!(route.paths[0][0].fee_msat, 100);
2857 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2858 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2859 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2861 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2862 assert_eq!(route.paths[0][1].short_channel_id, 4);
2863 assert_eq!(route.paths[0][1].fee_msat, 0);
2864 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2865 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2866 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2868 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2869 assert_eq!(route.paths[0][2].short_channel_id, 6);
2870 assert_eq!(route.paths[0][2].fee_msat, 0);
2871 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2872 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2873 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2875 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2876 assert_eq!(route.paths[0][3].short_channel_id, 11);
2877 assert_eq!(route.paths[0][3].fee_msat, 0);
2878 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2879 // If we have a peer in the node map, we'll use their features here since we don't have
2880 // a way of figuring out their features from the invoice:
2881 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2882 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2884 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2885 assert_eq!(route.paths[0][4].short_channel_id, 8);
2886 assert_eq!(route.paths[0][4].fee_msat, 100);
2887 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2888 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2889 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2892 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2894 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2895 let zero_fees = RoutingFees {
2897 proportional_millionths: 0,
2899 vec![RouteHint(vec![RouteHintHop {
2900 src_node_id: hint_hops[0],
2901 short_channel_id: 0xff00,
2904 proportional_millionths: 0,
2906 cltv_expiry_delta: (5 << 4) | 1,
2907 htlc_minimum_msat: None,
2908 htlc_maximum_msat: None,
2910 src_node_id: hint_hops[1],
2911 short_channel_id: 0xff01,
2913 cltv_expiry_delta: (8 << 4) | 1,
2914 htlc_minimum_msat: None,
2915 htlc_maximum_msat: None,
2920 fn multi_hint_last_hops_test() {
2921 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2922 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2923 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2924 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
2925 let scorer = ln_test_utils::TestScorer::with_penalty(0);
2926 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2927 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2928 // Test through channels 2, 3, 0xff00, 0xff01.
2929 // Test shows that multiple hop hints are considered.
2931 // Disabling channels 6 & 7 by flags=2
2932 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2933 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2934 short_channel_id: 6,
2936 flags: 2, // to disable
2937 cltv_expiry_delta: 0,
2938 htlc_minimum_msat: 0,
2939 htlc_maximum_msat: MAX_VALUE_MSAT,
2941 fee_proportional_millionths: 0,
2942 excess_data: Vec::new()
2944 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2946 short_channel_id: 7,
2948 flags: 2, // to disable
2949 cltv_expiry_delta: 0,
2950 htlc_minimum_msat: 0,
2951 htlc_maximum_msat: MAX_VALUE_MSAT,
2953 fee_proportional_millionths: 0,
2954 excess_data: Vec::new()
2957 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2958 assert_eq!(route.paths[0].len(), 4);
2960 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2961 assert_eq!(route.paths[0][0].short_channel_id, 2);
2962 assert_eq!(route.paths[0][0].fee_msat, 200);
2963 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2964 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2965 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2967 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2968 assert_eq!(route.paths[0][1].short_channel_id, 4);
2969 assert_eq!(route.paths[0][1].fee_msat, 100);
2970 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2971 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2972 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2974 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2975 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2976 assert_eq!(route.paths[0][2].fee_msat, 0);
2977 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2978 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2979 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2981 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2982 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2983 assert_eq!(route.paths[0][3].fee_msat, 100);
2984 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2985 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2986 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2990 fn private_multi_hint_last_hops_test() {
2991 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2992 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2994 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2995 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2997 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2998 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
2999 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3000 // Test through channels 2, 3, 0xff00, 0xff01.
3001 // Test shows that multiple hop hints are considered.
3003 // Disabling channels 6 & 7 by flags=2
3004 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3006 short_channel_id: 6,
3008 flags: 2, // to disable
3009 cltv_expiry_delta: 0,
3010 htlc_minimum_msat: 0,
3011 htlc_maximum_msat: MAX_VALUE_MSAT,
3013 fee_proportional_millionths: 0,
3014 excess_data: Vec::new()
3016 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3017 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3018 short_channel_id: 7,
3020 flags: 2, // to disable
3021 cltv_expiry_delta: 0,
3022 htlc_minimum_msat: 0,
3023 htlc_maximum_msat: MAX_VALUE_MSAT,
3025 fee_proportional_millionths: 0,
3026 excess_data: Vec::new()
3029 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3030 assert_eq!(route.paths[0].len(), 4);
3032 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3033 assert_eq!(route.paths[0][0].short_channel_id, 2);
3034 assert_eq!(route.paths[0][0].fee_msat, 200);
3035 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3036 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3037 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3039 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3040 assert_eq!(route.paths[0][1].short_channel_id, 4);
3041 assert_eq!(route.paths[0][1].fee_msat, 100);
3042 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3043 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3044 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3046 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3047 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3048 assert_eq!(route.paths[0][2].fee_msat, 0);
3049 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3050 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3051 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3053 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3054 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3055 assert_eq!(route.paths[0][3].fee_msat, 100);
3056 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3057 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3058 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3061 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3062 let zero_fees = RoutingFees {
3064 proportional_millionths: 0,
3066 vec![RouteHint(vec![RouteHintHop {
3067 src_node_id: nodes[4],
3068 short_channel_id: 11,
3070 cltv_expiry_delta: (11 << 4) | 1,
3071 htlc_minimum_msat: None,
3072 htlc_maximum_msat: None,
3074 src_node_id: nodes[3],
3075 short_channel_id: 8,
3077 cltv_expiry_delta: (8 << 4) | 1,
3078 htlc_minimum_msat: None,
3079 htlc_maximum_msat: None,
3080 }]), RouteHint(vec![RouteHintHop {
3081 src_node_id: nodes[4],
3082 short_channel_id: 9,
3085 proportional_millionths: 0,
3087 cltv_expiry_delta: (9 << 4) | 1,
3088 htlc_minimum_msat: None,
3089 htlc_maximum_msat: None,
3090 }]), RouteHint(vec![RouteHintHop {
3091 src_node_id: nodes[5],
3092 short_channel_id: 10,
3094 cltv_expiry_delta: (10 << 4) | 1,
3095 htlc_minimum_msat: None,
3096 htlc_maximum_msat: None,
3101 fn last_hops_with_public_channel_test() {
3102 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3103 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3104 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes));
3105 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3106 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3107 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3108 // This test shows that public routes can be present in the invoice
3109 // which would be handled in the same manner.
3111 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3112 assert_eq!(route.paths[0].len(), 5);
3114 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3115 assert_eq!(route.paths[0][0].short_channel_id, 2);
3116 assert_eq!(route.paths[0][0].fee_msat, 100);
3117 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3118 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3119 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3121 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3122 assert_eq!(route.paths[0][1].short_channel_id, 4);
3123 assert_eq!(route.paths[0][1].fee_msat, 0);
3124 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3125 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3126 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3128 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3129 assert_eq!(route.paths[0][2].short_channel_id, 6);
3130 assert_eq!(route.paths[0][2].fee_msat, 0);
3131 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3132 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3133 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3135 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3136 assert_eq!(route.paths[0][3].short_channel_id, 11);
3137 assert_eq!(route.paths[0][3].fee_msat, 0);
3138 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3139 // If we have a peer in the node map, we'll use their features here since we don't have
3140 // a way of figuring out their features from the invoice:
3141 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3142 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3144 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3145 assert_eq!(route.paths[0][4].short_channel_id, 8);
3146 assert_eq!(route.paths[0][4].fee_msat, 100);
3147 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3148 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3149 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3153 fn our_chans_last_hop_connect_test() {
3154 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3155 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3156 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3157 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3158 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3160 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3161 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3162 let mut last_hops = last_hops(&nodes);
3163 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3164 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3165 assert_eq!(route.paths[0].len(), 2);
3167 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3168 assert_eq!(route.paths[0][0].short_channel_id, 42);
3169 assert_eq!(route.paths[0][0].fee_msat, 0);
3170 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3171 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3172 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3174 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3175 assert_eq!(route.paths[0][1].short_channel_id, 8);
3176 assert_eq!(route.paths[0][1].fee_msat, 100);
3177 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3178 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3179 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3181 last_hops[0].0[0].fees.base_msat = 1000;
3183 // Revert to via 6 as the fee on 8 goes up
3184 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops);
3185 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3186 assert_eq!(route.paths[0].len(), 4);
3188 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3189 assert_eq!(route.paths[0][0].short_channel_id, 2);
3190 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3191 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3192 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3193 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3195 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3196 assert_eq!(route.paths[0][1].short_channel_id, 4);
3197 assert_eq!(route.paths[0][1].fee_msat, 100);
3198 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3199 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3200 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3202 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3203 assert_eq!(route.paths[0][2].short_channel_id, 7);
3204 assert_eq!(route.paths[0][2].fee_msat, 0);
3205 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3206 // If we have a peer in the node map, we'll use their features here since we don't have
3207 // a way of figuring out their features from the invoice:
3208 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3209 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3211 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3212 assert_eq!(route.paths[0][3].short_channel_id, 10);
3213 assert_eq!(route.paths[0][3].fee_msat, 100);
3214 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3215 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3216 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3218 // ...but still use 8 for larger payments as 6 has a variable feerate
3219 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3220 assert_eq!(route.paths[0].len(), 5);
3222 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3223 assert_eq!(route.paths[0][0].short_channel_id, 2);
3224 assert_eq!(route.paths[0][0].fee_msat, 3000);
3225 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3226 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3227 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3229 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3230 assert_eq!(route.paths[0][1].short_channel_id, 4);
3231 assert_eq!(route.paths[0][1].fee_msat, 0);
3232 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3233 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3234 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3236 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3237 assert_eq!(route.paths[0][2].short_channel_id, 6);
3238 assert_eq!(route.paths[0][2].fee_msat, 0);
3239 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3240 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3241 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3243 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3244 assert_eq!(route.paths[0][3].short_channel_id, 11);
3245 assert_eq!(route.paths[0][3].fee_msat, 1000);
3246 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3247 // If we have a peer in the node map, we'll use their features here since we don't have
3248 // a way of figuring out their features from the invoice:
3249 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3250 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3252 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3253 assert_eq!(route.paths[0][4].short_channel_id, 8);
3254 assert_eq!(route.paths[0][4].fee_msat, 2000);
3255 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3256 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3257 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3260 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> {
3261 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3262 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3263 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3265 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3266 let last_hops = RouteHint(vec![RouteHintHop {
3267 src_node_id: middle_node_id,
3268 short_channel_id: 8,
3271 proportional_millionths: last_hop_fee_prop,
3273 cltv_expiry_delta: (8 << 4) | 1,
3274 htlc_minimum_msat: None,
3275 htlc_maximum_msat: last_hop_htlc_max,
3277 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]);
3278 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3279 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3280 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3281 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3282 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
3283 let logger = ln_test_utils::TestLogger::new();
3284 let network_graph = NetworkGraph::new(genesis_hash, &logger);
3285 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3286 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3291 fn unannounced_path_test() {
3292 // We should be able to send a payment to a destination without any help of a routing graph
3293 // if we have a channel with a common counterparty that appears in the first and last hop
3295 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3297 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3298 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3299 assert_eq!(route.paths[0].len(), 2);
3301 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3302 assert_eq!(route.paths[0][0].short_channel_id, 42);
3303 assert_eq!(route.paths[0][0].fee_msat, 1001);
3304 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3305 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3306 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3308 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3309 assert_eq!(route.paths[0][1].short_channel_id, 8);
3310 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3311 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3312 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3313 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3317 fn overflow_unannounced_path_test_liquidity_underflow() {
3318 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3319 // the last-hop had a fee which overflowed a u64, we'd panic.
3320 // This was due to us adding the first-hop from us unconditionally, causing us to think
3321 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3322 // In this test, we previously hit a subtraction underflow due to having less available
3323 // liquidity at the last hop than 0.
3324 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());
3328 fn overflow_unannounced_path_test_feerate_overflow() {
3329 // This tests for the same case as above, except instead of hitting a subtraction
3330 // underflow, we hit a case where the fee charged at a hop overflowed.
3331 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());
3335 fn available_amount_while_routing_test() {
3336 // Tests whether we choose the correct available channel amount while routing.
3338 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3339 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3340 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3341 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3342 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3343 let config = UserConfig::default();
3344 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
3346 // We will use a simple single-path route from
3347 // our node to node2 via node0: channels {1, 3}.
3349 // First disable all other paths.
3350 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3352 short_channel_id: 2,
3355 cltv_expiry_delta: 0,
3356 htlc_minimum_msat: 0,
3357 htlc_maximum_msat: 100_000,
3359 fee_proportional_millionths: 0,
3360 excess_data: Vec::new()
3362 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3364 short_channel_id: 12,
3367 cltv_expiry_delta: 0,
3368 htlc_minimum_msat: 0,
3369 htlc_maximum_msat: 100_000,
3371 fee_proportional_millionths: 0,
3372 excess_data: Vec::new()
3375 // Make the first channel (#1) very permissive,
3376 // and we will be testing all limits on the second channel.
3377 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3379 short_channel_id: 1,
3382 cltv_expiry_delta: 0,
3383 htlc_minimum_msat: 0,
3384 htlc_maximum_msat: 1_000_000_000,
3386 fee_proportional_millionths: 0,
3387 excess_data: Vec::new()
3390 // First, let's see if routing works if we have absolutely no idea about the available amount.
3391 // In this case, it should be set to 250_000 sats.
3392 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3394 short_channel_id: 3,
3397 cltv_expiry_delta: 0,
3398 htlc_minimum_msat: 0,
3399 htlc_maximum_msat: 250_000_000,
3401 fee_proportional_millionths: 0,
3402 excess_data: Vec::new()
3406 // Attempt to route more than available results in a failure.
3407 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3408 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3409 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3410 } else { panic!(); }
3414 // Now, attempt to route an exact amount we have should be fine.
3415 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3416 assert_eq!(route.paths.len(), 1);
3417 let path = route.paths.last().unwrap();
3418 assert_eq!(path.len(), 2);
3419 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3420 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3423 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3424 // Disable channel #1 and use another first hop.
3425 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3427 short_channel_id: 1,
3430 cltv_expiry_delta: 0,
3431 htlc_minimum_msat: 0,
3432 htlc_maximum_msat: 1_000_000_000,
3434 fee_proportional_millionths: 0,
3435 excess_data: Vec::new()
3438 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3439 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3442 // Attempt to route more than available results in a failure.
3443 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3444 &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3445 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3446 } else { panic!(); }
3450 // Now, attempt to route an exact amount we have should be fine.
3451 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3452 assert_eq!(route.paths.len(), 1);
3453 let path = route.paths.last().unwrap();
3454 assert_eq!(path.len(), 2);
3455 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3456 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3459 // Enable channel #1 back.
3460 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3462 short_channel_id: 1,
3465 cltv_expiry_delta: 0,
3466 htlc_minimum_msat: 0,
3467 htlc_maximum_msat: 1_000_000_000,
3469 fee_proportional_millionths: 0,
3470 excess_data: Vec::new()
3474 // Now let's see if routing works if we know only htlc_maximum_msat.
3475 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3477 short_channel_id: 3,
3480 cltv_expiry_delta: 0,
3481 htlc_minimum_msat: 0,
3482 htlc_maximum_msat: 15_000,
3484 fee_proportional_millionths: 0,
3485 excess_data: Vec::new()
3489 // Attempt to route more than available results in a failure.
3490 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3491 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3492 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3493 } else { panic!(); }
3497 // Now, attempt to route an exact amount we have should be fine.
3498 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3499 assert_eq!(route.paths.len(), 1);
3500 let path = route.paths.last().unwrap();
3501 assert_eq!(path.len(), 2);
3502 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3503 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3506 // Now let's see if routing works if we know only capacity from the UTXO.
3508 // We can't change UTXO capacity on the fly, so we'll disable
3509 // the existing channel and add another one with the capacity we need.
3510 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3512 short_channel_id: 3,
3515 cltv_expiry_delta: 0,
3516 htlc_minimum_msat: 0,
3517 htlc_maximum_msat: MAX_VALUE_MSAT,
3519 fee_proportional_millionths: 0,
3520 excess_data: Vec::new()
3523 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3524 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3525 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3526 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3527 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3529 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3530 gossip_sync.add_utxo_lookup(Some(chain_monitor));
3532 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3533 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3534 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3535 short_channel_id: 333,
3538 cltv_expiry_delta: (3 << 4) | 1,
3539 htlc_minimum_msat: 0,
3540 htlc_maximum_msat: 15_000,
3542 fee_proportional_millionths: 0,
3543 excess_data: Vec::new()
3545 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3546 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3547 short_channel_id: 333,
3550 cltv_expiry_delta: (3 << 4) | 2,
3551 htlc_minimum_msat: 0,
3552 htlc_maximum_msat: 15_000,
3554 fee_proportional_millionths: 0,
3555 excess_data: Vec::new()
3559 // Attempt to route more than available results in a failure.
3560 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3561 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3562 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3563 } else { panic!(); }
3567 // Now, attempt to route an exact amount we have should be fine.
3568 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3569 assert_eq!(route.paths.len(), 1);
3570 let path = route.paths.last().unwrap();
3571 assert_eq!(path.len(), 2);
3572 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3573 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3576 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3577 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3578 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3579 short_channel_id: 333,
3582 cltv_expiry_delta: 0,
3583 htlc_minimum_msat: 0,
3584 htlc_maximum_msat: 10_000,
3586 fee_proportional_millionths: 0,
3587 excess_data: Vec::new()
3591 // Attempt to route more than available results in a failure.
3592 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3593 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3594 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3595 } else { panic!(); }
3599 // Now, attempt to route an exact amount we have should be fine.
3600 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3601 assert_eq!(route.paths.len(), 1);
3602 let path = route.paths.last().unwrap();
3603 assert_eq!(path.len(), 2);
3604 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3605 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3610 fn available_liquidity_last_hop_test() {
3611 // Check that available liquidity properly limits the path even when only
3612 // one of the latter hops is limited.
3613 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3614 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3615 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3616 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3617 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3618 let config = UserConfig::default();
3619 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
3621 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3622 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3623 // Total capacity: 50 sats.
3625 // Disable other potential paths.
3626 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3628 short_channel_id: 2,
3631 cltv_expiry_delta: 0,
3632 htlc_minimum_msat: 0,
3633 htlc_maximum_msat: 100_000,
3635 fee_proportional_millionths: 0,
3636 excess_data: Vec::new()
3638 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3640 short_channel_id: 7,
3643 cltv_expiry_delta: 0,
3644 htlc_minimum_msat: 0,
3645 htlc_maximum_msat: 100_000,
3647 fee_proportional_millionths: 0,
3648 excess_data: Vec::new()
3653 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3654 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3655 short_channel_id: 12,
3658 cltv_expiry_delta: 0,
3659 htlc_minimum_msat: 0,
3660 htlc_maximum_msat: 100_000,
3662 fee_proportional_millionths: 0,
3663 excess_data: Vec::new()
3665 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3666 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3667 short_channel_id: 13,
3670 cltv_expiry_delta: 0,
3671 htlc_minimum_msat: 0,
3672 htlc_maximum_msat: 100_000,
3674 fee_proportional_millionths: 0,
3675 excess_data: Vec::new()
3678 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3680 short_channel_id: 6,
3683 cltv_expiry_delta: 0,
3684 htlc_minimum_msat: 0,
3685 htlc_maximum_msat: 50_000,
3687 fee_proportional_millionths: 0,
3688 excess_data: Vec::new()
3690 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3692 short_channel_id: 11,
3695 cltv_expiry_delta: 0,
3696 htlc_minimum_msat: 0,
3697 htlc_maximum_msat: 100_000,
3699 fee_proportional_millionths: 0,
3700 excess_data: Vec::new()
3703 // Attempt to route more than available results in a failure.
3704 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3705 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3706 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3707 } else { panic!(); }
3711 // Now, attempt to route 49 sats (just a bit below the capacity).
3712 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3713 assert_eq!(route.paths.len(), 1);
3714 let mut total_amount_paid_msat = 0;
3715 for path in &route.paths {
3716 assert_eq!(path.len(), 4);
3717 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3718 total_amount_paid_msat += path.last().unwrap().fee_msat;
3720 assert_eq!(total_amount_paid_msat, 49_000);
3724 // Attempt to route an exact amount is also fine
3725 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3726 assert_eq!(route.paths.len(), 1);
3727 let mut total_amount_paid_msat = 0;
3728 for path in &route.paths {
3729 assert_eq!(path.len(), 4);
3730 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3731 total_amount_paid_msat += path.last().unwrap().fee_msat;
3733 assert_eq!(total_amount_paid_msat, 50_000);
3738 fn ignore_fee_first_hop_test() {
3739 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3740 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3741 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3742 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3743 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3744 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3746 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3747 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3748 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3749 short_channel_id: 1,
3752 cltv_expiry_delta: 0,
3753 htlc_minimum_msat: 0,
3754 htlc_maximum_msat: 100_000,
3755 fee_base_msat: 1_000_000,
3756 fee_proportional_millionths: 0,
3757 excess_data: Vec::new()
3759 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3761 short_channel_id: 3,
3764 cltv_expiry_delta: 0,
3765 htlc_minimum_msat: 0,
3766 htlc_maximum_msat: 50_000,
3768 fee_proportional_millionths: 0,
3769 excess_data: Vec::new()
3773 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3774 assert_eq!(route.paths.len(), 1);
3775 let mut total_amount_paid_msat = 0;
3776 for path in &route.paths {
3777 assert_eq!(path.len(), 2);
3778 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3779 total_amount_paid_msat += path.last().unwrap().fee_msat;
3781 assert_eq!(total_amount_paid_msat, 50_000);
3786 fn simple_mpp_route_test() {
3787 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3788 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3789 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3790 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3791 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3792 let config = UserConfig::default();
3793 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3794 .with_features(channelmanager::provided_invoice_features(&config));
3796 // We need a route consisting of 3 paths:
3797 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3798 // To achieve this, the amount being transferred should be around
3799 // the total capacity of these 3 paths.
3801 // First, we set limits on these (previously unlimited) channels.
3802 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3804 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3805 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3807 short_channel_id: 1,
3810 cltv_expiry_delta: 0,
3811 htlc_minimum_msat: 0,
3812 htlc_maximum_msat: 100_000,
3814 fee_proportional_millionths: 0,
3815 excess_data: Vec::new()
3817 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3819 short_channel_id: 3,
3822 cltv_expiry_delta: 0,
3823 htlc_minimum_msat: 0,
3824 htlc_maximum_msat: 50_000,
3826 fee_proportional_millionths: 0,
3827 excess_data: Vec::new()
3830 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3831 // (total limit 60).
3832 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3833 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3834 short_channel_id: 12,
3837 cltv_expiry_delta: 0,
3838 htlc_minimum_msat: 0,
3839 htlc_maximum_msat: 60_000,
3841 fee_proportional_millionths: 0,
3842 excess_data: Vec::new()
3844 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3845 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3846 short_channel_id: 13,
3849 cltv_expiry_delta: 0,
3850 htlc_minimum_msat: 0,
3851 htlc_maximum_msat: 60_000,
3853 fee_proportional_millionths: 0,
3854 excess_data: Vec::new()
3857 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3858 // (total capacity 180 sats).
3859 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3860 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3861 short_channel_id: 2,
3864 cltv_expiry_delta: 0,
3865 htlc_minimum_msat: 0,
3866 htlc_maximum_msat: 200_000,
3868 fee_proportional_millionths: 0,
3869 excess_data: Vec::new()
3871 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3873 short_channel_id: 4,
3876 cltv_expiry_delta: 0,
3877 htlc_minimum_msat: 0,
3878 htlc_maximum_msat: 180_000,
3880 fee_proportional_millionths: 0,
3881 excess_data: Vec::new()
3885 // Attempt to route more than available results in a failure.
3886 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3887 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3888 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3889 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3890 } else { panic!(); }
3894 // Attempt to route while setting max_path_count to 0 results in a failure.
3895 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3896 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3897 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3898 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3899 assert_eq!(err, "Can't find a route with no paths allowed.");
3900 } else { panic!(); }
3904 // Attempt to route while setting max_path_count to 3 results in a failure.
3905 // This is the case because the minimal_value_contribution_msat would require each path
3906 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3907 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3908 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3909 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3910 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3911 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3912 } else { panic!(); }
3916 // Now, attempt to route 250 sats (just a bit below the capacity).
3917 // Our algorithm should provide us with these 3 paths.
3918 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3919 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3920 assert_eq!(route.paths.len(), 3);
3921 let mut total_amount_paid_msat = 0;
3922 for path in &route.paths {
3923 assert_eq!(path.len(), 2);
3924 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3925 total_amount_paid_msat += path.last().unwrap().fee_msat;
3927 assert_eq!(total_amount_paid_msat, 250_000);
3931 // Attempt to route an exact amount is also fine
3932 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3933 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3934 assert_eq!(route.paths.len(), 3);
3935 let mut total_amount_paid_msat = 0;
3936 for path in &route.paths {
3937 assert_eq!(path.len(), 2);
3938 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3939 total_amount_paid_msat += path.last().unwrap().fee_msat;
3941 assert_eq!(total_amount_paid_msat, 290_000);
3946 fn long_mpp_route_test() {
3947 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3948 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3949 let scorer = ln_test_utils::TestScorer::with_penalty(0);
3950 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3951 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3952 let config = UserConfig::default();
3953 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
3955 // We need a route consisting of 3 paths:
3956 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3957 // Note that these paths overlap (channels 5, 12, 13).
3958 // We will route 300 sats.
3959 // Each path will have 100 sats capacity, those channels which
3960 // are used twice will have 200 sats capacity.
3962 // Disable other potential paths.
3963 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3965 short_channel_id: 2,
3968 cltv_expiry_delta: 0,
3969 htlc_minimum_msat: 0,
3970 htlc_maximum_msat: 100_000,
3972 fee_proportional_millionths: 0,
3973 excess_data: Vec::new()
3975 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3976 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3977 short_channel_id: 7,
3980 cltv_expiry_delta: 0,
3981 htlc_minimum_msat: 0,
3982 htlc_maximum_msat: 100_000,
3984 fee_proportional_millionths: 0,
3985 excess_data: Vec::new()
3988 // Path via {node0, node2} is channels {1, 3, 5}.
3989 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3990 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3991 short_channel_id: 1,
3994 cltv_expiry_delta: 0,
3995 htlc_minimum_msat: 0,
3996 htlc_maximum_msat: 100_000,
3998 fee_proportional_millionths: 0,
3999 excess_data: Vec::new()
4001 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4002 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4003 short_channel_id: 3,
4006 cltv_expiry_delta: 0,
4007 htlc_minimum_msat: 0,
4008 htlc_maximum_msat: 100_000,
4010 fee_proportional_millionths: 0,
4011 excess_data: Vec::new()
4014 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4015 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4016 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4017 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4018 short_channel_id: 5,
4021 cltv_expiry_delta: 0,
4022 htlc_minimum_msat: 0,
4023 htlc_maximum_msat: 200_000,
4025 fee_proportional_millionths: 0,
4026 excess_data: Vec::new()
4029 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4030 // Add 100 sats to the capacities of {12, 13}, because these channels
4031 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4032 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4034 short_channel_id: 12,
4037 cltv_expiry_delta: 0,
4038 htlc_minimum_msat: 0,
4039 htlc_maximum_msat: 200_000,
4041 fee_proportional_millionths: 0,
4042 excess_data: Vec::new()
4044 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4046 short_channel_id: 13,
4049 cltv_expiry_delta: 0,
4050 htlc_minimum_msat: 0,
4051 htlc_maximum_msat: 200_000,
4053 fee_proportional_millionths: 0,
4054 excess_data: Vec::new()
4057 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4059 short_channel_id: 6,
4062 cltv_expiry_delta: 0,
4063 htlc_minimum_msat: 0,
4064 htlc_maximum_msat: 100_000,
4066 fee_proportional_millionths: 0,
4067 excess_data: Vec::new()
4069 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4071 short_channel_id: 11,
4074 cltv_expiry_delta: 0,
4075 htlc_minimum_msat: 0,
4076 htlc_maximum_msat: 100_000,
4078 fee_proportional_millionths: 0,
4079 excess_data: Vec::new()
4082 // Path via {node7, node2} is channels {12, 13, 5}.
4083 // We already limited them to 200 sats (they are used twice for 100 sats).
4084 // Nothing to do here.
4087 // Attempt to route more than available results in a failure.
4088 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4089 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4090 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4091 } else { panic!(); }
4095 // Now, attempt to route 300 sats (exact amount we can route).
4096 // Our algorithm should provide us with these 3 paths, 100 sats each.
4097 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4098 assert_eq!(route.paths.len(), 3);
4100 let mut total_amount_paid_msat = 0;
4101 for path in &route.paths {
4102 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4103 total_amount_paid_msat += path.last().unwrap().fee_msat;
4105 assert_eq!(total_amount_paid_msat, 300_000);
4111 fn mpp_cheaper_route_test() {
4112 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4113 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4114 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4115 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4116 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4117 let config = UserConfig::default();
4118 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4120 // This test checks that if we have two cheaper paths and one more expensive path,
4121 // so that liquidity-wise any 2 of 3 combination is sufficient,
4122 // two cheaper paths will be taken.
4123 // These paths have equal available liquidity.
4125 // We need a combination of 3 paths:
4126 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4127 // Note that these paths overlap (channels 5, 12, 13).
4128 // Each path will have 100 sats capacity, those channels which
4129 // are used twice will have 200 sats capacity.
4131 // Disable other potential paths.
4132 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4133 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4134 short_channel_id: 2,
4137 cltv_expiry_delta: 0,
4138 htlc_minimum_msat: 0,
4139 htlc_maximum_msat: 100_000,
4141 fee_proportional_millionths: 0,
4142 excess_data: Vec::new()
4144 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4145 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4146 short_channel_id: 7,
4149 cltv_expiry_delta: 0,
4150 htlc_minimum_msat: 0,
4151 htlc_maximum_msat: 100_000,
4153 fee_proportional_millionths: 0,
4154 excess_data: Vec::new()
4157 // Path via {node0, node2} is channels {1, 3, 5}.
4158 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4160 short_channel_id: 1,
4163 cltv_expiry_delta: 0,
4164 htlc_minimum_msat: 0,
4165 htlc_maximum_msat: 100_000,
4167 fee_proportional_millionths: 0,
4168 excess_data: Vec::new()
4170 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4172 short_channel_id: 3,
4175 cltv_expiry_delta: 0,
4176 htlc_minimum_msat: 0,
4177 htlc_maximum_msat: 100_000,
4179 fee_proportional_millionths: 0,
4180 excess_data: Vec::new()
4183 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4184 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4185 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4186 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4187 short_channel_id: 5,
4190 cltv_expiry_delta: 0,
4191 htlc_minimum_msat: 0,
4192 htlc_maximum_msat: 200_000,
4194 fee_proportional_millionths: 0,
4195 excess_data: Vec::new()
4198 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4199 // Add 100 sats to the capacities of {12, 13}, because these channels
4200 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
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: 200_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: 200_000,
4222 fee_proportional_millionths: 0,
4223 excess_data: Vec::new()
4226 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4227 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4228 short_channel_id: 6,
4231 cltv_expiry_delta: 0,
4232 htlc_minimum_msat: 0,
4233 htlc_maximum_msat: 100_000,
4234 fee_base_msat: 1_000,
4235 fee_proportional_millionths: 0,
4236 excess_data: Vec::new()
4238 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4239 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4240 short_channel_id: 11,
4243 cltv_expiry_delta: 0,
4244 htlc_minimum_msat: 0,
4245 htlc_maximum_msat: 100_000,
4247 fee_proportional_millionths: 0,
4248 excess_data: Vec::new()
4251 // Path via {node7, node2} is channels {12, 13, 5}.
4252 // We already limited them to 200 sats (they are used twice for 100 sats).
4253 // Nothing to do here.
4256 // Now, attempt to route 180 sats.
4257 // Our algorithm should provide us with these 2 paths.
4258 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4259 assert_eq!(route.paths.len(), 2);
4261 let mut total_value_transferred_msat = 0;
4262 let mut total_paid_msat = 0;
4263 for path in &route.paths {
4264 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4265 total_value_transferred_msat += path.last().unwrap().fee_msat;
4267 total_paid_msat += hop.fee_msat;
4270 // If we paid fee, this would be higher.
4271 assert_eq!(total_value_transferred_msat, 180_000);
4272 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4273 assert_eq!(total_fees_paid, 0);
4278 fn fees_on_mpp_route_test() {
4279 // This test makes sure that MPP algorithm properly takes into account
4280 // fees charged on the channels, by making the fees impactful:
4281 // if the fee is not properly accounted for, the behavior is different.
4282 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4283 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4284 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4285 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4286 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4287 let config = UserConfig::default();
4288 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4290 // We need a route consisting of 2 paths:
4291 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4292 // We will route 200 sats, Each path will have 100 sats capacity.
4294 // This test is not particularly stable: e.g.,
4295 // there's a way to route via {node0, node2, node4}.
4296 // It works while pathfinding is deterministic, but can be broken otherwise.
4297 // It's fine to ignore this concern for now.
4299 // Disable other potential paths.
4300 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4302 short_channel_id: 2,
4305 cltv_expiry_delta: 0,
4306 htlc_minimum_msat: 0,
4307 htlc_maximum_msat: 100_000,
4309 fee_proportional_millionths: 0,
4310 excess_data: Vec::new()
4313 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4314 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4315 short_channel_id: 7,
4318 cltv_expiry_delta: 0,
4319 htlc_minimum_msat: 0,
4320 htlc_maximum_msat: 100_000,
4322 fee_proportional_millionths: 0,
4323 excess_data: Vec::new()
4326 // Path via {node0, node2} is channels {1, 3, 5}.
4327 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4329 short_channel_id: 1,
4332 cltv_expiry_delta: 0,
4333 htlc_minimum_msat: 0,
4334 htlc_maximum_msat: 100_000,
4336 fee_proportional_millionths: 0,
4337 excess_data: Vec::new()
4339 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4340 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4341 short_channel_id: 3,
4344 cltv_expiry_delta: 0,
4345 htlc_minimum_msat: 0,
4346 htlc_maximum_msat: 100_000,
4348 fee_proportional_millionths: 0,
4349 excess_data: Vec::new()
4352 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4353 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4354 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4355 short_channel_id: 5,
4358 cltv_expiry_delta: 0,
4359 htlc_minimum_msat: 0,
4360 htlc_maximum_msat: 100_000,
4362 fee_proportional_millionths: 0,
4363 excess_data: Vec::new()
4366 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4367 // All channels should be 100 sats capacity. But for the fee experiment,
4368 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4369 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4370 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4371 // so no matter how large are other channels,
4372 // the whole path will be limited by 100 sats with just these 2 conditions:
4373 // - channel 12 capacity is 250 sats
4374 // - fee for channel 6 is 150 sats
4375 // Let's test this by enforcing these 2 conditions and removing other limits.
4376 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4377 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4378 short_channel_id: 12,
4381 cltv_expiry_delta: 0,
4382 htlc_minimum_msat: 0,
4383 htlc_maximum_msat: 250_000,
4385 fee_proportional_millionths: 0,
4386 excess_data: Vec::new()
4388 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4390 short_channel_id: 13,
4393 cltv_expiry_delta: 0,
4394 htlc_minimum_msat: 0,
4395 htlc_maximum_msat: MAX_VALUE_MSAT,
4397 fee_proportional_millionths: 0,
4398 excess_data: Vec::new()
4401 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4402 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4403 short_channel_id: 6,
4406 cltv_expiry_delta: 0,
4407 htlc_minimum_msat: 0,
4408 htlc_maximum_msat: MAX_VALUE_MSAT,
4409 fee_base_msat: 150_000,
4410 fee_proportional_millionths: 0,
4411 excess_data: Vec::new()
4413 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4415 short_channel_id: 11,
4418 cltv_expiry_delta: 0,
4419 htlc_minimum_msat: 0,
4420 htlc_maximum_msat: MAX_VALUE_MSAT,
4422 fee_proportional_millionths: 0,
4423 excess_data: Vec::new()
4427 // Attempt to route more than available results in a failure.
4428 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4429 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4430 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4431 } else { panic!(); }
4435 // Now, attempt to route 200 sats (exact amount we can route).
4436 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4437 assert_eq!(route.paths.len(), 2);
4439 let mut total_amount_paid_msat = 0;
4440 for path in &route.paths {
4441 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4442 total_amount_paid_msat += path.last().unwrap().fee_msat;
4444 assert_eq!(total_amount_paid_msat, 200_000);
4445 assert_eq!(route.get_total_fees(), 150_000);
4450 fn mpp_with_last_hops() {
4451 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4452 // via a single last-hop route hint, we'd fail to route if we first collected routes
4453 // totaling close but not quite enough to fund the full payment.
4455 // This was because we considered last-hop hints to have exactly the sought payment amount
4456 // instead of the amount we were trying to collect, needlessly limiting our path searching
4457 // at the very first hop.
4459 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4460 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4461 // to only have the remaining to-collect amount in available liquidity.
4463 // This bug appeared in production in some specific channel configurations.
4464 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4465 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4466 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4467 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4468 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4469 let config = UserConfig::default();
4470 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_features(channelmanager::provided_invoice_features(&config))
4471 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4472 src_node_id: nodes[2],
4473 short_channel_id: 42,
4474 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4475 cltv_expiry_delta: 42,
4476 htlc_minimum_msat: None,
4477 htlc_maximum_msat: None,
4478 }])]).with_max_channel_saturation_power_of_half(0);
4480 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4481 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4482 // would first use the no-fee route and then fail to find a path along the second route as
4483 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4484 // under 5% of our payment amount.
4485 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4487 short_channel_id: 1,
4490 cltv_expiry_delta: (5 << 4) | 5,
4491 htlc_minimum_msat: 0,
4492 htlc_maximum_msat: 99_000,
4493 fee_base_msat: u32::max_value(),
4494 fee_proportional_millionths: u32::max_value(),
4495 excess_data: Vec::new()
4497 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4499 short_channel_id: 2,
4502 cltv_expiry_delta: (5 << 4) | 3,
4503 htlc_minimum_msat: 0,
4504 htlc_maximum_msat: 99_000,
4505 fee_base_msat: u32::max_value(),
4506 fee_proportional_millionths: u32::max_value(),
4507 excess_data: Vec::new()
4509 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4511 short_channel_id: 4,
4514 cltv_expiry_delta: (4 << 4) | 1,
4515 htlc_minimum_msat: 0,
4516 htlc_maximum_msat: MAX_VALUE_MSAT,
4518 fee_proportional_millionths: 0,
4519 excess_data: Vec::new()
4521 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4522 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4523 short_channel_id: 13,
4525 flags: 0|2, // Channel disabled
4526 cltv_expiry_delta: (13 << 4) | 1,
4527 htlc_minimum_msat: 0,
4528 htlc_maximum_msat: MAX_VALUE_MSAT,
4530 fee_proportional_millionths: 2000000,
4531 excess_data: Vec::new()
4534 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4536 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4537 assert_eq!(route.paths.len(), 2);
4538 route.paths.sort_by_key(|path| path[0].short_channel_id);
4539 // Paths are manually ordered ordered by SCID, so:
4540 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4541 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4542 assert_eq!(route.paths[0][0].short_channel_id, 1);
4543 assert_eq!(route.paths[0][0].fee_msat, 0);
4544 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4545 assert_eq!(route.paths[1][0].short_channel_id, 2);
4546 assert_eq!(route.paths[1][0].fee_msat, 1);
4547 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4548 assert_eq!(route.get_total_fees(), 1);
4549 assert_eq!(route.get_total_amount(), 100_000);
4553 fn drop_lowest_channel_mpp_route_test() {
4554 // This test checks that low-capacity channel is dropped when after
4555 // path finding we realize that we found more capacity than we need.
4556 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4557 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4558 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4559 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4560 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4561 let config = UserConfig::default();
4562 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config))
4563 .with_max_channel_saturation_power_of_half(0);
4565 // We need a route consisting of 3 paths:
4566 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4568 // The first and the second paths should be sufficient, but the third should be
4569 // cheaper, so that we select it but drop later.
4571 // First, we set limits on these (previously unlimited) channels.
4572 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4574 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4575 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4576 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4577 short_channel_id: 1,
4580 cltv_expiry_delta: 0,
4581 htlc_minimum_msat: 0,
4582 htlc_maximum_msat: 100_000,
4584 fee_proportional_millionths: 0,
4585 excess_data: Vec::new()
4587 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4588 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4589 short_channel_id: 3,
4592 cltv_expiry_delta: 0,
4593 htlc_minimum_msat: 0,
4594 htlc_maximum_msat: 50_000,
4596 fee_proportional_millionths: 0,
4597 excess_data: Vec::new()
4600 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4601 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4603 short_channel_id: 12,
4606 cltv_expiry_delta: 0,
4607 htlc_minimum_msat: 0,
4608 htlc_maximum_msat: 60_000,
4610 fee_proportional_millionths: 0,
4611 excess_data: Vec::new()
4613 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4615 short_channel_id: 13,
4618 cltv_expiry_delta: 0,
4619 htlc_minimum_msat: 0,
4620 htlc_maximum_msat: 60_000,
4622 fee_proportional_millionths: 0,
4623 excess_data: Vec::new()
4626 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4627 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4628 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4629 short_channel_id: 2,
4632 cltv_expiry_delta: 0,
4633 htlc_minimum_msat: 0,
4634 htlc_maximum_msat: 20_000,
4636 fee_proportional_millionths: 0,
4637 excess_data: Vec::new()
4639 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4641 short_channel_id: 4,
4644 cltv_expiry_delta: 0,
4645 htlc_minimum_msat: 0,
4646 htlc_maximum_msat: 20_000,
4648 fee_proportional_millionths: 0,
4649 excess_data: Vec::new()
4653 // Attempt to route more than available results in a failure.
4654 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4655 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4656 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4657 } else { panic!(); }
4661 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4662 // Our algorithm should provide us with these 3 paths.
4663 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4664 assert_eq!(route.paths.len(), 3);
4665 let mut total_amount_paid_msat = 0;
4666 for path in &route.paths {
4667 assert_eq!(path.len(), 2);
4668 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4669 total_amount_paid_msat += path.last().unwrap().fee_msat;
4671 assert_eq!(total_amount_paid_msat, 125_000);
4675 // Attempt to route without the last small cheap channel
4676 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4677 assert_eq!(route.paths.len(), 2);
4678 let mut total_amount_paid_msat = 0;
4679 for path in &route.paths {
4680 assert_eq!(path.len(), 2);
4681 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4682 total_amount_paid_msat += path.last().unwrap().fee_msat;
4684 assert_eq!(total_amount_paid_msat, 90_000);
4689 fn min_criteria_consistency() {
4690 // Test that we don't use an inconsistent metric between updating and walking nodes during
4691 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4692 // was updated with a different criterion from the heap sorting, resulting in loops in
4693 // calculated paths. We test for that specific case here.
4695 // We construct a network that looks like this:
4697 // node2 -1(3)2- node3
4701 // node1 -1(5)2- node4 -1(1)2- node6
4707 // We create a loop on the side of our real path - our destination is node 6, with a
4708 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4709 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4710 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4711 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4712 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4713 // "previous hop" being set to node 3, creating a loop in the path.
4714 let secp_ctx = Secp256k1::new();
4715 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4716 let logger = Arc::new(ln_test_utils::TestLogger::new());
4717 let network = Arc::new(NetworkGraph::new(genesis_hash, Arc::clone(&logger)));
4718 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4719 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4720 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4721 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4722 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4723 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
4725 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4726 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4727 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4728 short_channel_id: 6,
4731 cltv_expiry_delta: (6 << 4) | 0,
4732 htlc_minimum_msat: 0,
4733 htlc_maximum_msat: MAX_VALUE_MSAT,
4735 fee_proportional_millionths: 0,
4736 excess_data: Vec::new()
4738 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4740 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4741 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4742 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4743 short_channel_id: 5,
4746 cltv_expiry_delta: (5 << 4) | 0,
4747 htlc_minimum_msat: 0,
4748 htlc_maximum_msat: MAX_VALUE_MSAT,
4750 fee_proportional_millionths: 0,
4751 excess_data: Vec::new()
4753 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4755 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4756 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4758 short_channel_id: 4,
4761 cltv_expiry_delta: (4 << 4) | 0,
4762 htlc_minimum_msat: 0,
4763 htlc_maximum_msat: MAX_VALUE_MSAT,
4765 fee_proportional_millionths: 0,
4766 excess_data: Vec::new()
4768 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4770 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4771 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4772 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4773 short_channel_id: 3,
4776 cltv_expiry_delta: (3 << 4) | 0,
4777 htlc_minimum_msat: 0,
4778 htlc_maximum_msat: MAX_VALUE_MSAT,
4780 fee_proportional_millionths: 0,
4781 excess_data: Vec::new()
4783 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4785 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4786 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4787 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4788 short_channel_id: 2,
4791 cltv_expiry_delta: (2 << 4) | 0,
4792 htlc_minimum_msat: 0,
4793 htlc_maximum_msat: MAX_VALUE_MSAT,
4795 fee_proportional_millionths: 0,
4796 excess_data: Vec::new()
4799 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4800 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4802 short_channel_id: 1,
4805 cltv_expiry_delta: (1 << 4) | 0,
4806 htlc_minimum_msat: 100,
4807 htlc_maximum_msat: MAX_VALUE_MSAT,
4809 fee_proportional_millionths: 0,
4810 excess_data: Vec::new()
4812 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4815 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4816 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4817 assert_eq!(route.paths.len(), 1);
4818 assert_eq!(route.paths[0].len(), 3);
4820 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4821 assert_eq!(route.paths[0][0].short_channel_id, 6);
4822 assert_eq!(route.paths[0][0].fee_msat, 100);
4823 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4824 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4825 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4827 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4828 assert_eq!(route.paths[0][1].short_channel_id, 5);
4829 assert_eq!(route.paths[0][1].fee_msat, 0);
4830 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4831 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4832 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4834 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4835 assert_eq!(route.paths[0][2].short_channel_id, 1);
4836 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4837 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4838 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4839 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4845 fn exact_fee_liquidity_limit() {
4846 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4847 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4848 // we calculated fees on a higher value, resulting in us ignoring such paths.
4849 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4850 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4851 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4852 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4853 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4854 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4856 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4858 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4860 short_channel_id: 2,
4863 cltv_expiry_delta: 0,
4864 htlc_minimum_msat: 0,
4865 htlc_maximum_msat: 85_000,
4867 fee_proportional_millionths: 0,
4868 excess_data: Vec::new()
4871 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4873 short_channel_id: 12,
4876 cltv_expiry_delta: (4 << 4) | 1,
4877 htlc_minimum_msat: 0,
4878 htlc_maximum_msat: 270_000,
4880 fee_proportional_millionths: 1000000,
4881 excess_data: Vec::new()
4885 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4886 // 200% fee charged channel 13 in the 1-to-2 direction.
4887 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4888 assert_eq!(route.paths.len(), 1);
4889 assert_eq!(route.paths[0].len(), 2);
4891 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4892 assert_eq!(route.paths[0][0].short_channel_id, 12);
4893 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4894 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4895 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4896 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4898 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4899 assert_eq!(route.paths[0][1].short_channel_id, 13);
4900 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4901 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4902 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4903 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4908 fn htlc_max_reduction_below_min() {
4909 // Test that if, while walking the graph, we reduce the value being sent to meet an
4910 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4911 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4912 // resulting in us thinking there is no possible path, even if other paths exist.
4913 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4914 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4915 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4916 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4917 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4918 let config = UserConfig::default();
4919 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
4921 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4922 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4923 // then try to send 90_000.
4924 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4926 short_channel_id: 2,
4929 cltv_expiry_delta: 0,
4930 htlc_minimum_msat: 0,
4931 htlc_maximum_msat: 80_000,
4933 fee_proportional_millionths: 0,
4934 excess_data: Vec::new()
4936 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4938 short_channel_id: 4,
4941 cltv_expiry_delta: (4 << 4) | 1,
4942 htlc_minimum_msat: 90_000,
4943 htlc_maximum_msat: MAX_VALUE_MSAT,
4945 fee_proportional_millionths: 0,
4946 excess_data: Vec::new()
4950 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4951 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4952 // expensive) channels 12-13 path.
4953 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4954 assert_eq!(route.paths.len(), 1);
4955 assert_eq!(route.paths[0].len(), 2);
4957 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4958 assert_eq!(route.paths[0][0].short_channel_id, 12);
4959 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4960 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4961 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4962 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4964 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4965 assert_eq!(route.paths[0][1].short_channel_id, 13);
4966 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4967 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4968 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
4969 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4974 fn multiple_direct_first_hops() {
4975 // Previously we'd only ever considered one first hop path per counterparty.
4976 // However, as we don't restrict users to one channel per peer, we really need to support
4977 // looking at all first hop paths.
4978 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4979 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4980 // route over multiple channels with the same first hop.
4981 let secp_ctx = Secp256k1::new();
4982 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4983 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
4984 let logger = Arc::new(ln_test_utils::TestLogger::new());
4985 let network_graph = NetworkGraph::new(genesis_hash, Arc::clone(&logger));
4986 let scorer = ln_test_utils::TestScorer::with_penalty(0);
4987 let config = UserConfig::default();
4988 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_features(channelmanager::provided_invoice_features(&config));
4989 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4990 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4993 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
4994 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
4995 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
4996 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4997 assert_eq!(route.paths.len(), 1);
4998 assert_eq!(route.paths[0].len(), 1);
5000 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5001 assert_eq!(route.paths[0][0].short_channel_id, 3);
5002 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5005 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5006 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5007 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5008 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5009 assert_eq!(route.paths.len(), 2);
5010 assert_eq!(route.paths[0].len(), 1);
5011 assert_eq!(route.paths[1].len(), 1);
5013 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
5014 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
5016 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5017 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5019 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5020 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5024 // If we have a bunch of outbound channels to the same node, where most are not
5025 // sufficient to pay the full payment, but one is, we should default to just using the
5026 // one single channel that has sufficient balance, avoiding MPP.
5028 // If we have several options above the 3xpayment value threshold, we should pick the
5029 // smallest of them, avoiding further fragmenting our available outbound balance to
5031 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5032 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5033 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5034 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5035 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5036 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5037 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5038 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5039 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5040 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5041 assert_eq!(route.paths.len(), 1);
5042 assert_eq!(route.paths[0].len(), 1);
5044 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5045 assert_eq!(route.paths[0][0].short_channel_id, 6);
5046 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5051 fn prefers_shorter_route_with_higher_fees() {
5052 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5053 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5054 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5056 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5057 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5058 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5059 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5060 let route = get_route(
5061 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5062 Arc::clone(&logger), &scorer, &random_seed_bytes
5064 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5066 assert_eq!(route.get_total_fees(), 100);
5067 assert_eq!(route.get_total_amount(), 100);
5068 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5070 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5071 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5072 let scorer = ln_test_utils::TestScorer::with_penalty(100);
5073 let route = get_route(
5074 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5075 Arc::clone(&logger), &scorer, &random_seed_bytes
5077 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5079 assert_eq!(route.get_total_fees(), 300);
5080 assert_eq!(route.get_total_amount(), 100);
5081 assert_eq!(path, vec![2, 4, 7, 10]);
5084 struct BadChannelScorer {
5085 short_channel_id: u64,
5089 impl Writeable for BadChannelScorer {
5090 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5092 impl Score for BadChannelScorer {
5093 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5094 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5097 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5098 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5099 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5100 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5103 struct BadNodeScorer {
5108 impl Writeable for BadNodeScorer {
5109 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5112 impl Score for BadNodeScorer {
5113 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5114 if *target == self.node_id { u64::max_value() } else { 0 }
5117 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5118 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5119 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5120 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5124 fn avoids_routing_through_bad_channels_and_nodes() {
5125 let (secp_ctx, network, _, _, logger) = build_graph();
5126 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5127 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5128 let network_graph = network.read_only();
5130 // A path to nodes[6] exists when no penalties are applied to any channel.
5131 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5132 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5133 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5134 let route = get_route(
5135 &our_id, &payment_params, &network_graph, None, 100, 42,
5136 Arc::clone(&logger), &scorer, &random_seed_bytes
5138 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5140 assert_eq!(route.get_total_fees(), 100);
5141 assert_eq!(route.get_total_amount(), 100);
5142 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5144 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5145 let scorer = BadChannelScorer { short_channel_id: 6 };
5146 let route = get_route(
5147 &our_id, &payment_params, &network_graph, None, 100, 42,
5148 Arc::clone(&logger), &scorer, &random_seed_bytes
5150 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5152 assert_eq!(route.get_total_fees(), 300);
5153 assert_eq!(route.get_total_amount(), 100);
5154 assert_eq!(path, vec![2, 4, 7, 10]);
5156 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5157 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5159 &our_id, &payment_params, &network_graph, None, 100, 42,
5160 Arc::clone(&logger), &scorer, &random_seed_bytes
5162 Err(LightningError { err, .. } ) => {
5163 assert_eq!(err, "Failed to find a path to the given destination");
5165 Ok(_) => panic!("Expected error"),
5170 fn total_fees_single_path() {
5174 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5175 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5176 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5179 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5180 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5181 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5184 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5185 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5186 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5189 payment_params: None,
5192 assert_eq!(route.get_total_fees(), 250);
5193 assert_eq!(route.get_total_amount(), 225);
5197 fn total_fees_multi_path() {
5201 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5202 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5203 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5206 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5207 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5208 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5212 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5213 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5214 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5217 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5218 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5219 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5222 payment_params: None,
5225 assert_eq!(route.get_total_fees(), 200);
5226 assert_eq!(route.get_total_amount(), 300);
5230 fn total_empty_route_no_panic() {
5231 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5232 // would both panic if the route was completely empty. We test to ensure they return 0
5233 // here, even though its somewhat nonsensical as a route.
5234 let route = Route { paths: Vec::new(), payment_params: None };
5236 assert_eq!(route.get_total_fees(), 0);
5237 assert_eq!(route.get_total_amount(), 0);
5241 fn limits_total_cltv_delta() {
5242 let (secp_ctx, network, _, _, logger) = build_graph();
5243 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5244 let network_graph = network.read_only();
5246 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5248 // Make sure that generally there is at least one route available
5249 let feasible_max_total_cltv_delta = 1008;
5250 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5251 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5252 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5253 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5254 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5255 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5256 assert_ne!(path.len(), 0);
5258 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5259 let fail_max_total_cltv_delta = 23;
5260 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5261 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5262 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5264 Err(LightningError { err, .. } ) => {
5265 assert_eq!(err, "Failed to find a path to the given destination");
5267 Ok(_) => panic!("Expected error"),
5272 fn avoids_recently_failed_paths() {
5273 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5274 // randomly inserting channels into it until we can't find a route anymore.
5275 let (secp_ctx, network, _, _, logger) = build_graph();
5276 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5277 let network_graph = network.read_only();
5279 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5280 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5281 .with_max_path_count(1);
5282 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5283 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5285 // We should be able to find a route initially, and then after we fail a few random
5286 // channels eventually we won't be able to any longer.
5287 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5289 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5290 for chan in route.paths[0].iter() {
5291 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5293 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5294 % route.paths[0].len();
5295 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5301 fn limits_path_length() {
5302 let (secp_ctx, network, _, _, logger) = build_line_graph();
5303 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5304 let network_graph = network.read_only();
5306 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5307 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5308 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5310 // First check we can actually create a long route on this graph.
5311 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5312 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5313 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5314 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5315 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5317 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5318 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5319 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5320 Arc::clone(&logger), &scorer, &random_seed_bytes)
5322 Err(LightningError { err, .. } ) => {
5323 assert_eq!(err, "Failed to find a path to the given destination");
5325 Ok(_) => panic!("Expected error"),
5330 fn adds_and_limits_cltv_offset() {
5331 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5332 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5334 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5336 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5337 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5338 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5339 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5340 assert_eq!(route.paths.len(), 1);
5342 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5344 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5345 let mut route_default = route.clone();
5346 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5347 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5348 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5349 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5350 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5352 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5353 let mut route_limited = route.clone();
5354 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5355 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5356 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5357 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5358 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5362 fn adds_plausible_cltv_offset() {
5363 let (secp_ctx, network, _, _, logger) = build_graph();
5364 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5365 let network_graph = network.read_only();
5366 let network_nodes = network_graph.nodes();
5367 let network_channels = network_graph.channels();
5368 let scorer = ln_test_utils::TestScorer::with_penalty(0);
5369 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5370 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5371 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5373 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5374 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5375 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5377 let mut path_plausibility = vec![];
5379 for p in route.paths {
5380 // 1. Select random observation point
5381 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5382 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5384 prng.process_in_place(&mut random_bytes);
5385 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5386 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5388 // 2. Calculate what CLTV expiry delta we would observe there
5389 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5391 // 3. Starting from the observation point, find candidate paths
5392 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5393 candidates.push_back((observation_point, vec![]));
5395 let mut found_plausible_candidate = false;
5397 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5398 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5399 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5400 found_plausible_candidate = true;
5401 break 'candidate_loop;
5405 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5406 for channel_id in &cur_node.channels {
5407 if let Some(channel_info) = network_channels.get(&channel_id) {
5408 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5409 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5410 if cur_path_cltv_deltas.iter().sum::<u32>()
5411 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5412 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5413 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5414 candidates.push_back((*next_id, new_path_cltv_deltas));
5422 path_plausibility.push(found_plausible_candidate);
5424 assert!(path_plausibility.iter().all(|x| *x));
5428 fn builds_correct_path_from_hops() {
5429 let (secp_ctx, network, _, _, logger) = build_graph();
5430 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5431 let network_graph = network.read_only();
5433 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5434 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5436 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5437 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5438 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5439 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5440 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5441 assert_eq!(hops.len(), route.paths[0].len());
5442 for (idx, hop_pubkey) in hops.iter().enumerate() {
5443 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5448 fn avoids_saturating_channels() {
5449 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5450 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5452 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5454 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5455 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5456 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5458 short_channel_id: 4,
5461 cltv_expiry_delta: (4 << 4) | 1,
5462 htlc_minimum_msat: 0,
5463 htlc_maximum_msat: 250_000_000,
5465 fee_proportional_millionths: 0,
5466 excess_data: Vec::new()
5468 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5470 short_channel_id: 13,
5473 cltv_expiry_delta: (13 << 4) | 1,
5474 htlc_minimum_msat: 0,
5475 htlc_maximum_msat: 250_000_000,
5477 fee_proportional_millionths: 0,
5478 excess_data: Vec::new()
5481 let config = UserConfig::default();
5482 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
5483 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5484 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5485 // 100,000 sats is less than the available liquidity on each channel, set above.
5486 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5487 assert_eq!(route.paths.len(), 2);
5488 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5489 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5492 #[cfg(not(feature = "no-std"))]
5493 pub(super) fn random_init_seed() -> u64 {
5494 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5495 use core::hash::{BuildHasher, Hasher};
5496 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5497 println!("Using seed of {}", seed);
5500 #[cfg(not(feature = "no-std"))]
5501 use crate::util::ser::ReadableArgs;
5504 #[cfg(not(feature = "no-std"))]
5505 fn generate_routes() {
5506 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5508 let mut d = match super::bench_utils::get_route_file() {
5515 let logger = ln_test_utils::TestLogger::new();
5516 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5517 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5518 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5520 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5521 let mut seed = random_init_seed() as usize;
5522 let nodes = graph.read_only().nodes().clone();
5523 'load_endpoints: for _ in 0..10 {
5525 seed = seed.overflowing_mul(0xdeadbeef).0;
5526 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5527 seed = seed.overflowing_mul(0xdeadbeef).0;
5528 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5529 let payment_params = PaymentParameters::from_node_id(dst, 42);
5530 let amt = seed as u64 % 200_000_000;
5531 let params = ProbabilisticScoringParameters::default();
5532 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5533 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5534 continue 'load_endpoints;
5541 #[cfg(not(feature = "no-std"))]
5542 fn generate_routes_mpp() {
5543 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5545 let mut d = match super::bench_utils::get_route_file() {
5552 let logger = ln_test_utils::TestLogger::new();
5553 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5554 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5555 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5556 let config = UserConfig::default();
5558 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5559 let mut seed = random_init_seed() as usize;
5560 let nodes = graph.read_only().nodes().clone();
5561 'load_endpoints: for _ in 0..10 {
5563 seed = seed.overflowing_mul(0xdeadbeef).0;
5564 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5565 seed = seed.overflowing_mul(0xdeadbeef).0;
5566 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5567 let payment_params = PaymentParameters::from_node_id(dst, 42).with_features(channelmanager::provided_invoice_features(&config));
5568 let amt = seed as u64 % 200_000_000;
5569 let params = ProbabilisticScoringParameters::default();
5570 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5571 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5572 continue 'load_endpoints;
5579 fn honors_manual_penalties() {
5580 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5581 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5583 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5584 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5586 let scorer_params = ProbabilisticScoringParameters::default();
5587 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5589 // First check set manual penalties are returned by the scorer.
5590 let usage = ChannelUsage {
5592 inflight_htlc_msat: 0,
5593 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5595 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5596 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5597 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5599 // Then check we can get a normal route
5600 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
5601 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5602 assert!(route.is_ok());
5604 // Then check that we can't get a route if we ban an intermediate node.
5605 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5606 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5607 assert!(route.is_err());
5609 // Finally make sure we can route again, when we remove the ban.
5610 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5611 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5612 assert!(route.is_ok());
5616 #[cfg(all(test, not(feature = "no-std")))]
5617 pub(crate) mod bench_utils {
5619 /// Tries to open a network graph file, or panics with a URL to fetch it.
5620 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5621 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
5622 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
5623 .or_else(|_| { // Fall back to guessing based on the binary location
5624 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5625 let mut path = std::env::current_exe().unwrap();
5626 path.pop(); // lightning-...
5628 path.pop(); // debug
5629 path.pop(); // target
5630 path.push("lightning");
5631 path.push("net_graph-2023-01-18.bin");
5632 eprintln!("{}", path.to_str().unwrap());
5635 .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");
5636 #[cfg(require_route_graph_test)]
5637 return Ok(res.unwrap());
5638 #[cfg(not(require_route_graph_test))]
5643 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5646 use bitcoin::hashes::Hash;
5647 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5648 use crate::chain::transaction::OutPoint;
5649 use crate::chain::keysinterface::{EntropySource, KeysManager};
5650 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5651 use crate::ln::features::InvoiceFeatures;
5652 use crate::routing::gossip::NetworkGraph;
5653 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5654 use crate::util::config::UserConfig;
5655 use crate::util::logger::{Logger, Record};
5656 use crate::util::ser::ReadableArgs;
5660 struct DummyLogger {}
5661 impl Logger for DummyLogger {
5662 fn log(&self, _record: &Record) {}
5665 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5666 let mut d = bench_utils::get_route_file().unwrap();
5667 NetworkGraph::read(&mut d, logger).unwrap()
5670 fn payer_pubkey() -> PublicKey {
5671 let secp_ctx = Secp256k1::new();
5672 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5676 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5678 channel_id: [0; 32],
5679 counterparty: ChannelCounterparty {
5680 features: channelmanager::provided_init_features(&UserConfig::default()),
5682 unspendable_punishment_reserve: 0,
5683 forwarding_info: None,
5684 outbound_htlc_minimum_msat: None,
5685 outbound_htlc_maximum_msat: None,
5687 funding_txo: Some(OutPoint {
5688 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5691 short_channel_id: Some(1),
5692 inbound_scid_alias: None,
5693 outbound_scid_alias: None,
5694 channel_value_satoshis: 10_000_000,
5696 balance_msat: 10_000_000,
5697 outbound_capacity_msat: 10_000_000,
5698 next_outbound_htlc_limit_msat: 10_000_000,
5699 inbound_capacity_msat: 0,
5700 unspendable_punishment_reserve: None,
5701 confirmations_required: None,
5702 confirmations: None,
5703 force_close_spend_delay: None,
5705 is_channel_ready: true,
5708 inbound_htlc_minimum_msat: None,
5709 inbound_htlc_maximum_msat: None,
5715 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5716 let logger = DummyLogger {};
5717 let network_graph = read_network_graph(&logger);
5718 let scorer = FixedPenaltyScorer::with_penalty(0);
5719 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5723 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5724 let logger = DummyLogger {};
5725 let network_graph = read_network_graph(&logger);
5726 let scorer = FixedPenaltyScorer::with_penalty(0);
5727 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5731 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5732 let logger = DummyLogger {};
5733 let network_graph = read_network_graph(&logger);
5734 let params = ProbabilisticScoringParameters::default();
5735 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5736 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5740 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5741 let logger = DummyLogger {};
5742 let network_graph = read_network_graph(&logger);
5743 let params = ProbabilisticScoringParameters::default();
5744 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5745 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5748 fn generate_routes<S: Score>(
5749 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5750 features: InvoiceFeatures
5752 let nodes = graph.read_only().nodes().clone();
5753 let payer = payer_pubkey();
5754 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5755 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5757 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5758 let mut routes = Vec::new();
5759 let mut route_endpoints = Vec::new();
5760 let mut seed: usize = 0xdeadbeef;
5761 'load_endpoints: for _ in 0..150 {
5764 let src = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5766 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5767 let params = PaymentParameters::from_node_id(dst, 42).with_features(features.clone());
5768 let first_hop = first_hop(src);
5769 let amt = seed as u64 % 1_000_000;
5770 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5772 route_endpoints.push((first_hop, params, amt));
5773 continue 'load_endpoints;
5778 // ...and seed the scorer with success and failure data...
5779 for route in routes {
5780 let amount = route.get_total_amount();
5781 if amount < 250_000 {
5782 for path in route.paths {
5783 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5785 } else if amount > 750_000 {
5786 for path in route.paths {
5787 let short_channel_id = path[path.len() / 2].short_channel_id;
5788 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5793 // Because we've changed channel scores, its possible we'll take different routes to the
5794 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5795 // requires a too-high CLTV delta.
5796 route_endpoints.retain(|(first_hop, params, amt)| {
5797 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5799 route_endpoints.truncate(100);
5800 assert_eq!(route_endpoints.len(), 100);
5802 // ...then benchmark finding paths between the nodes we learned.
5805 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5806 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());