1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::BlindedPath;
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::BlindedPayInfo;
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
29 use crate::prelude::*;
30 use crate::sync::Mutex;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> where
38 S::Target: for <'a> LockableScore<'a>,
42 random_seed_bytes: Mutex<[u8; 32]>,
46 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> DefaultRouter<G, L, S> where
48 S::Target: for <'a> LockableScore<'a>,
50 /// Creates a new router.
51 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S) -> Self {
52 let random_seed_bytes = Mutex::new(random_seed_bytes);
53 Self { network_graph, logger, random_seed_bytes, scorer }
57 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> Router for DefaultRouter<G, L, S> where
59 S::Target: for <'a> LockableScore<'a>,
62 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
63 inflight_htlcs: &InFlightHtlcs
64 ) -> Result<Route, LightningError> {
65 let random_seed_bytes = {
66 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
67 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
68 *locked_random_seed_bytes
72 payer, params, &self.network_graph, first_hops, &*self.logger,
73 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock(), inflight_htlcs),
79 /// A trait defining behavior for routing a payment.
81 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
83 &self, payer: &PublicKey, route_params: &RouteParameters,
84 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
85 ) -> Result<Route, LightningError>;
86 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
87 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
88 fn find_route_with_id(
89 &self, payer: &PublicKey, route_params: &RouteParameters,
90 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
91 _payment_hash: PaymentHash, _payment_id: PaymentId
92 ) -> Result<Route, LightningError> {
93 self.find_route(payer, route_params, first_hops, inflight_htlcs)
97 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
99 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
102 /// [`Score`]: crate::routing::scoring::Score
103 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score> {
105 // Maps a channel's short channel id and its direction to the liquidity used up.
106 inflight_htlcs: &'a InFlightHtlcs,
109 impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> {
110 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
111 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
112 ScorerAccountingForInFlightHtlcs {
120 impl<'a, S: Score> Writeable for ScorerAccountingForInFlightHtlcs<'a, S> {
121 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
124 impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> {
125 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage) -> u64 {
126 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
127 source, target, short_channel_id
129 let usage = ChannelUsage {
130 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
134 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
136 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
140 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
141 self.scorer.payment_path_failed(path, short_channel_id)
144 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
145 self.scorer.payment_path_successful(path)
148 fn probe_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
149 self.scorer.probe_failed(path, short_channel_id)
152 fn probe_successful(&mut self, path: &[&RouteHop]) {
153 self.scorer.probe_successful(path)
157 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
158 /// in-use channel liquidity.
160 pub struct InFlightHtlcs(
161 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
162 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
163 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
165 HashMap<(u64, bool), u64>
169 /// Constructs an empty `InFlightHtlcs`.
170 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
172 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
173 pub fn process_path(&mut self, path: &[RouteHop], payer_node_id: PublicKey) {
174 if path.is_empty() { return };
175 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
176 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
177 // the router excludes the payer node. In the following lines, the payer's information is
178 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
179 // in our sliding window of two.
180 let reversed_hops_with_payer = path.iter().rev().skip(1)
181 .map(|hop| hop.pubkey)
182 .chain(core::iter::once(payer_node_id));
183 let mut cumulative_msat = 0;
185 // Taking the reversed vector from above, we zip it with just the reversed hops list to
186 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
187 // the total amount sent.
188 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
189 cumulative_msat += next_hop.fee_msat;
191 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
192 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
193 .or_insert(cumulative_msat);
197 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
199 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
200 self.0.get(&(channel_scid, source < target)).map(|v| *v)
204 impl Writeable for InFlightHtlcs {
205 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
208 impl Readable for InFlightHtlcs {
209 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
210 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
211 Ok(Self(infight_map))
215 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
216 /// that leads to it.
217 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
218 pub struct RouteHop {
219 /// The node_id of the node at this hop.
220 pub pubkey: PublicKey,
221 /// The node_announcement features of the node at this hop. For the last hop, these may be
222 /// amended to match the features present in the invoice this node generated.
223 pub node_features: NodeFeatures,
224 /// The channel that should be used from the previous hop to reach this node.
225 pub short_channel_id: u64,
226 /// The channel_announcement features of the channel that should be used from the previous hop
227 /// to reach this node.
228 pub channel_features: ChannelFeatures,
229 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
230 /// For the last hop, this should be the full value of this path's part of the payment.
232 /// The CLTV delta added for this hop. For the last hop, this is the CLTV delta expected at the
234 pub cltv_expiry_delta: u32,
237 impl_writeable_tlv_based!(RouteHop, {
238 (0, pubkey, required),
239 (2, node_features, required),
240 (4, short_channel_id, required),
241 (6, channel_features, required),
242 (8, fee_msat, required),
243 (10, cltv_expiry_delta, required),
246 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
247 /// it can take multiple paths. Each path is composed of one or more hops through the network.
248 #[derive(Clone, Hash, PartialEq, Eq)]
250 /// The list of paths taken for a single (potentially-)multi-part payment. The pubkey of the
251 /// last [`RouteHop`] in each path must be the same. Each entry represents a list of hops, where
252 /// the last hop is the destination. Thus, this must always be at least length one. While the
253 /// maximum length of any given path is variable, keeping the length of any path less or equal to
254 /// 19 should currently ensure it is viable.
255 pub paths: Vec<Vec<RouteHop>>,
256 /// The `payment_params` parameter passed to [`find_route`].
257 /// This is used by `ChannelManager` to track information which may be required for retries,
258 /// provided back to you via [`Event::PaymentPathFailed`].
260 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
261 pub payment_params: Option<PaymentParameters>,
264 // This trait is deleted in the next commit
265 pub(crate) trait RoutePath {
266 /// Gets the fees for a given path, excluding any excess paid to the recipient.
267 fn fee_msat(&self) -> u64;
269 /// Gets the total amount paid on this path, excluding the fees.
270 fn final_value_msat(&self) -> u64;
272 /// Gets the final hop's CLTV expiry delta.
273 fn final_cltv_expiry_delta(&self) -> u32;
275 impl RoutePath for Vec<RouteHop> {
276 fn fee_msat(&self) -> u64 {
277 // Do not count last hop of each path since that's the full value of the payment
278 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
279 .iter().map(|hop| &hop.fee_msat)
282 fn final_value_msat(&self) -> u64 {
283 self.last().map_or(0, |hop| hop.fee_msat)
285 fn final_cltv_expiry_delta(&self) -> u32 {
286 self.last().map_or(0, |hop| hop.cltv_expiry_delta)
289 impl RoutePath for &[&RouteHop] {
290 fn fee_msat(&self) -> u64 {
291 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
292 .iter().map(|hop| &hop.fee_msat)
295 fn final_value_msat(&self) -> u64 {
296 self.last().map_or(0, |hop| hop.fee_msat)
298 fn final_cltv_expiry_delta(&self) -> u32 {
299 self.last().map_or(0, |hop| hop.cltv_expiry_delta)
304 /// Returns the total amount of fees paid on this [`Route`].
306 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
307 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
308 pub fn get_total_fees(&self) -> u64 {
309 self.paths.iter().map(|path| path.fee_msat()).sum()
312 /// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
313 /// requested if we had to reach htlc_minimum_msat.
314 pub fn get_total_amount(&self) -> u64 {
315 self.paths.iter().map(|path| path.final_value_msat()).sum()
319 const SERIALIZATION_VERSION: u8 = 1;
320 const MIN_SERIALIZATION_VERSION: u8 = 1;
322 impl Writeable for Route {
323 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
324 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
325 (self.paths.len() as u64).write(writer)?;
326 for hops in self.paths.iter() {
327 (hops.len() as u8).write(writer)?;
328 for hop in hops.iter() {
332 write_tlv_fields!(writer, {
333 (1, self.payment_params, option),
339 impl Readable for Route {
340 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
341 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
342 let path_count: u64 = Readable::read(reader)?;
343 if path_count == 0 { return Err(DecodeError::InvalidValue); }
344 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
345 let mut min_final_cltv_expiry_delta = u32::max_value();
346 for _ in 0..path_count {
347 let hop_count: u8 = Readable::read(reader)?;
348 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
349 for _ in 0..hop_count {
350 hops.push(Readable::read(reader)?);
352 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
353 min_final_cltv_expiry_delta =
354 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
357 let mut payment_params = None;
358 read_tlv_fields!(reader, {
359 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
361 Ok(Route { paths, payment_params })
365 /// Parameters needed to find a [`Route`].
367 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
368 /// [`Event::PaymentPathFailed`].
370 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
371 #[derive(Clone, Debug, PartialEq, Eq)]
372 pub struct RouteParameters {
373 /// The parameters of the failed payment path.
374 pub payment_params: PaymentParameters,
376 /// The amount in msats sent on the failed payment path.
377 pub final_value_msat: u64,
380 impl Writeable for RouteParameters {
381 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
382 write_tlv_fields!(writer, {
383 (0, self.payment_params, required),
384 (2, self.final_value_msat, required),
385 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
386 // `RouteParameters` directly. For compatibility, we write it here.
387 (4, self.payment_params.final_cltv_expiry_delta, required),
393 impl Readable for RouteParameters {
394 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
395 _init_and_read_tlv_fields!(reader, {
396 (0, payment_params, (required: ReadableArgs, 0)),
397 (2, final_value_msat, required),
398 (4, final_cltv_expiry_delta, required),
400 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
401 if payment_params.final_cltv_expiry_delta == 0 {
402 payment_params.final_cltv_expiry_delta = final_cltv_expiry_delta.0.unwrap();
406 final_value_msat: final_value_msat.0.unwrap(),
411 /// Maximum total CTLV difference we allow for a full payment path.
412 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
414 /// Maximum number of paths we allow an (MPP) payment to have.
415 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
416 // limits, but for now more than 10 paths likely carries too much one-path failure.
417 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
419 // The median hop CLTV expiry delta currently seen in the network.
420 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
422 // During routing, we only consider paths shorter than our maximum length estimate.
423 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
424 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
425 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
427 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
428 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
429 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
430 // (payment_secret and total_msat) = 93 bytes for the final hop.
431 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
432 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
433 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
435 /// The recipient of a payment.
436 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
437 pub struct PaymentParameters {
438 /// The node id of the payee.
439 pub payee_pubkey: PublicKey,
441 /// Features supported by the payee.
443 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
444 /// does not contain any features.
446 /// [`for_keysend`]: Self::for_keysend
447 pub features: Option<InvoiceFeatures>,
449 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
450 pub route_hints: Hints,
452 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
453 pub expiry_time: Option<u64>,
455 /// The maximum total CLTV delta we accept for the route.
456 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
457 pub max_total_cltv_expiry_delta: u32,
459 /// The maximum number of paths that may be used by (MPP) payments.
460 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
461 pub max_path_count: u8,
463 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
464 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
465 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
466 /// increasing failure probability for those paths.
468 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
469 /// restriction have been found. While paths which meet this criteria will be searched for, it
470 /// is ultimately up to the scorer to select them over other paths.
472 /// A value of 0 will allow payments up to and including a channel's total announced usable
473 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
476 pub max_channel_saturation_power_of_half: u8,
478 /// A list of SCIDs which this payment was previously attempted over and which caused the
479 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
481 pub previously_failed_channels: Vec<u64>,
483 /// The minimum CLTV delta at the end of the route. This value must not be zero.
484 pub final_cltv_expiry_delta: u32,
487 impl Writeable for PaymentParameters {
488 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
489 let mut clear_hints = &vec![];
490 let mut blinded_hints = &vec![];
491 match &self.route_hints {
492 Hints::Clear(hints) => clear_hints = hints,
493 Hints::Blinded(hints) => blinded_hints = hints,
495 write_tlv_fields!(writer, {
496 (0, self.payee_pubkey, required),
497 (1, self.max_total_cltv_expiry_delta, required),
498 (2, self.features, option),
499 (3, self.max_path_count, required),
500 (4, *clear_hints, vec_type),
501 (5, self.max_channel_saturation_power_of_half, required),
502 (6, self.expiry_time, option),
503 (7, self.previously_failed_channels, vec_type),
504 (8, *blinded_hints, optional_vec),
505 (9, self.final_cltv_expiry_delta, required),
511 impl ReadableArgs<u32> for PaymentParameters {
512 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
513 _init_and_read_tlv_fields!(reader, {
514 (0, payee_pubkey, required),
515 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
516 (2, features, option),
517 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
518 (4, route_hints, vec_type),
519 (5, max_channel_saturation_power_of_half, (default_value, 2)),
520 (6, expiry_time, option),
521 (7, previously_failed_channels, vec_type),
522 (8, blinded_route_hints, optional_vec),
523 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
525 let clear_route_hints = route_hints.unwrap_or(vec![]);
526 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
527 let route_hints = if blinded_route_hints.len() != 0 {
528 if clear_route_hints.len() != 0 { return Err(DecodeError::InvalidValue) }
529 Hints::Blinded(blinded_route_hints)
531 Hints::Clear(clear_route_hints)
534 payee_pubkey: _init_tlv_based_struct_field!(payee_pubkey, required),
535 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
537 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
539 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
541 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
542 final_cltv_expiry_delta: _init_tlv_based_struct_field!(final_cltv_expiry_delta, (default_value, unused)),
548 impl PaymentParameters {
549 /// Creates a payee with the node id of the given `pubkey`.
551 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
553 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
557 route_hints: Hints::Clear(vec![]),
559 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
560 max_path_count: DEFAULT_MAX_PATH_COUNT,
561 max_channel_saturation_power_of_half: 2,
562 previously_failed_channels: Vec::new(),
563 final_cltv_expiry_delta,
567 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
569 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
571 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
572 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta).with_features(InvoiceFeatures::for_keysend())
575 /// Includes the payee's features.
577 /// This is not exported to bindings users since bindings don't support move semantics
578 pub fn with_features(self, features: InvoiceFeatures) -> Self {
579 Self { features: Some(features), ..self }
582 /// Includes hints for routing to the payee.
584 /// This is not exported to bindings users since bindings don't support move semantics
585 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
586 Self { route_hints: Hints::Clear(route_hints), ..self }
589 /// Includes a payment expiration in seconds relative to the UNIX epoch.
591 /// This is not exported to bindings users since bindings don't support move semantics
592 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
593 Self { expiry_time: Some(expiry_time), ..self }
596 /// Includes a limit for the total CLTV expiry delta which is considered during routing
598 /// This is not exported to bindings users since bindings don't support move semantics
599 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
600 Self { max_total_cltv_expiry_delta, ..self }
603 /// Includes a limit for the maximum number of payment paths that may be used.
605 /// This is not exported to bindings users since bindings don't support move semantics
606 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
607 Self { max_path_count, ..self }
610 /// Includes a limit for the maximum number of payment paths that may be used.
612 /// This is not exported to bindings users since bindings don't support move semantics
613 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
614 Self { max_channel_saturation_power_of_half, ..self }
618 /// Routing hints for the tail of the route.
619 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
621 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
622 /// will be included in the final [`Route`].
623 Blinded(Vec<(BlindedPayInfo, BlindedPath)>),
624 /// The recipient included these route hints in their BOLT11 invoice.
625 Clear(Vec<RouteHint>),
628 /// A list of hops along a payment path terminating with a channel to the recipient.
629 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
630 pub struct RouteHint(pub Vec<RouteHintHop>);
632 impl Writeable for RouteHint {
633 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
634 (self.0.len() as u64).write(writer)?;
635 for hop in self.0.iter() {
642 impl Readable for RouteHint {
643 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
644 let hop_count: u64 = Readable::read(reader)?;
645 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
646 for _ in 0..hop_count {
647 hops.push(Readable::read(reader)?);
653 /// A channel descriptor for a hop along a payment path.
654 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
655 pub struct RouteHintHop {
656 /// The node_id of the non-target end of the route
657 pub src_node_id: PublicKey,
658 /// The short_channel_id of this channel
659 pub short_channel_id: u64,
660 /// The fees which must be paid to use this channel
661 pub fees: RoutingFees,
662 /// The difference in CLTV values between this node and the next node.
663 pub cltv_expiry_delta: u16,
664 /// The minimum value, in msat, which must be relayed to the next hop.
665 pub htlc_minimum_msat: Option<u64>,
666 /// The maximum value in msat available for routing with a single HTLC.
667 pub htlc_maximum_msat: Option<u64>,
670 impl_writeable_tlv_based!(RouteHintHop, {
671 (0, src_node_id, required),
672 (1, htlc_minimum_msat, option),
673 (2, short_channel_id, required),
674 (3, htlc_maximum_msat, option),
676 (6, cltv_expiry_delta, required),
679 #[derive(Eq, PartialEq)]
680 struct RouteGraphNode {
682 lowest_fee_to_node: u64,
683 total_cltv_delta: u32,
684 // The maximum value a yet-to-be-constructed payment path might flow through this node.
685 // This value is upper-bounded by us by:
686 // - how much is needed for a path being constructed
687 // - how much value can channels following this node (up to the destination) can contribute,
688 // considering their capacity and fees
689 value_contribution_msat: u64,
690 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
691 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
692 path_htlc_minimum_msat: u64,
693 /// All penalties incurred from this hop on the way to the destination, as calculated using
695 path_penalty_msat: u64,
696 /// The number of hops walked up to this node.
697 path_length_to_node: u8,
700 impl cmp::Ord for RouteGraphNode {
701 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
702 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
703 .saturating_add(other.path_penalty_msat);
704 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
705 .saturating_add(self.path_penalty_msat);
706 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
710 impl cmp::PartialOrd for RouteGraphNode {
711 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
712 Some(self.cmp(other))
716 /// A wrapper around the various hop representations.
718 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
719 #[derive(Clone, Debug)]
720 enum CandidateRouteHop<'a> {
721 /// A hop from the payer, where the outbound liquidity is known.
723 details: &'a ChannelDetails,
725 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
727 info: DirectedChannelInfo<'a>,
728 short_channel_id: u64,
730 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
732 hint: &'a RouteHintHop,
736 impl<'a> CandidateRouteHop<'a> {
737 fn short_channel_id(&self) -> u64 {
739 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
740 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
741 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
745 // NOTE: This may alloc memory so avoid calling it in a hot code path.
746 fn features(&self) -> ChannelFeatures {
748 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
749 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
750 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
754 fn cltv_expiry_delta(&self) -> u32 {
756 CandidateRouteHop::FirstHop { .. } => 0,
757 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
758 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
762 fn htlc_minimum_msat(&self) -> u64 {
764 CandidateRouteHop::FirstHop { .. } => 0,
765 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
766 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
770 fn fees(&self) -> RoutingFees {
772 CandidateRouteHop::FirstHop { .. } => RoutingFees {
773 base_msat: 0, proportional_millionths: 0,
775 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
776 CandidateRouteHop::PrivateHop { hint } => hint.fees,
780 fn effective_capacity(&self) -> EffectiveCapacity {
782 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
783 liquidity_msat: details.next_outbound_htlc_limit_msat,
785 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
786 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
792 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
793 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
795 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
796 EffectiveCapacity::Infinite => u64::max_value(),
797 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
798 EffectiveCapacity::MaximumHTLC { amount_msat } =>
799 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
800 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
801 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
805 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
806 -> bool where I1::Item: PartialEq<I2::Item> {
808 let a = iter_a.next();
809 let b = iter_b.next();
810 if a.is_none() && b.is_none() { return true; }
811 if a.is_none() || b.is_none() { return false; }
812 if a.unwrap().ne(&b.unwrap()) { return false; }
816 /// It's useful to keep track of the hops associated with the fees required to use them,
817 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
818 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
819 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
821 struct PathBuildingHop<'a> {
822 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
823 // is a larger refactor and will require careful performance analysis.
825 candidate: CandidateRouteHop<'a>,
828 /// All the fees paid *after* this channel on the way to the destination
829 next_hops_fee_msat: u64,
830 /// Fee paid for the use of the current channel (see candidate.fees()).
831 /// The value will be actually deducted from the counterparty balance on the previous link.
832 hop_use_fee_msat: u64,
833 /// Used to compare channels when choosing the for routing.
834 /// Includes paying for the use of a hop and the following hops, as well as
835 /// an estimated cost of reaching this hop.
836 /// Might get stale when fees are recomputed. Primarily for internal use.
838 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
839 /// walk and may be invalid thereafter.
840 path_htlc_minimum_msat: u64,
841 /// All penalties incurred from this channel on the way to the destination, as calculated using
843 path_penalty_msat: u64,
844 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
845 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
846 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
847 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
848 /// avoid processing them again.
850 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
851 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
852 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
853 // value_contribution_msat, which requires tracking it here. See comments below where it is
854 // used for more info.
855 value_contribution_msat: u64,
858 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
859 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
860 let mut debug_struct = f.debug_struct("PathBuildingHop");
862 .field("node_id", &self.node_id)
863 .field("short_channel_id", &self.candidate.short_channel_id())
864 .field("total_fee_msat", &self.total_fee_msat)
865 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
866 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
867 .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)))
868 .field("path_penalty_msat", &self.path_penalty_msat)
869 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
870 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
871 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
872 let debug_struct = debug_struct
873 .field("value_contribution_msat", &self.value_contribution_msat);
874 debug_struct.finish()
878 // Instantiated with a list of hops with correct data in them collected during path finding,
879 // an instance of this struct should be further modified only via given methods.
881 struct PaymentPath<'a> {
882 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
885 impl<'a> PaymentPath<'a> {
886 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
887 fn get_value_msat(&self) -> u64 {
888 self.hops.last().unwrap().0.fee_msat
891 fn get_path_penalty_msat(&self) -> u64 {
892 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
895 fn get_total_fee_paid_msat(&self) -> u64 {
896 if self.hops.len() < 1 {
900 // Can't use next_hops_fee_msat because it gets outdated.
901 for (i, (hop, _)) in self.hops.iter().enumerate() {
902 if i != self.hops.len() - 1 {
903 result += hop.fee_msat;
909 fn get_cost_msat(&self) -> u64 {
910 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
913 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
914 // to change fees may result in an inconsistency.
916 // Sometimes we call this function right after constructing a path which is inconsistent in
917 // that it the value being transferred has decreased while we were doing path finding, leading
918 // to the fees being paid not lining up with the actual limits.
920 // Note that this function is not aware of the available_liquidity limit, and thus does not
921 // support increasing the value being transferred beyond what was selected during the initial
923 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
924 let mut total_fee_paid_msat = 0 as u64;
925 for i in (0..self.hops.len()).rev() {
926 let last_hop = i == self.hops.len() - 1;
928 // For non-last-hop, this value will represent the fees paid on the current hop. It
929 // will consist of the fees for the use of the next hop, and extra fees to match
930 // htlc_minimum_msat of the current channel. Last hop is handled separately.
931 let mut cur_hop_fees_msat = 0;
933 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
936 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
937 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
938 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
939 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
940 // set it too high just to maliciously take more fees by exploiting this
941 // match htlc_minimum_msat logic.
942 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
943 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
944 // Note that there is a risk that *previous hops* (those closer to us, as we go
945 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
947 // This might make us end up with a broken route, although this should be super-rare
948 // in practice, both because of how healthy channels look like, and how we pick
949 // channels in add_entry.
950 // Also, this can't be exploited more heavily than *announce a free path and fail
952 cur_hop_transferred_amount_msat += extra_fees_msat;
953 total_fee_paid_msat += extra_fees_msat;
954 cur_hop_fees_msat += extra_fees_msat;
958 // Final hop is a special case: it usually has just value_msat (by design), but also
959 // it still could overpay for the htlc_minimum_msat.
960 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
962 // Propagate updated fees for the use of the channels to one hop back, where they
963 // will be actually paid (fee_msat). The last hop is handled above separately.
964 cur_hop.fee_msat = cur_hop_fees_msat;
967 // Fee for the use of the current hop which will be deducted on the previous hop.
968 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
969 // this channel is free for us.
971 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
972 cur_hop.hop_use_fee_msat = new_fee;
973 total_fee_paid_msat += new_fee;
975 // It should not be possible because this function is called only to reduce the
976 // value. In that case, compute_fee was already called with the same fees for
977 // larger amount and there was no overflow.
986 /// Calculate the fees required to route the given amount over a channel with the given fees.
987 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
988 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
989 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
993 /// Calculate the fees required to route the given amount over a channel with the given fees,
994 /// saturating to [`u64::max_value`].
995 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
996 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
997 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
998 .saturating_add(channel_fees.base_msat as u64)
1001 /// The default `features` we assume for a node in a route, when no `features` are known about that
1004 /// Default features are:
1005 /// * variable_length_onion_optional
1006 fn default_node_features() -> NodeFeatures {
1007 let mut features = NodeFeatures::empty();
1008 features.set_variable_length_onion_optional();
1012 /// Finds a route from us (payer) to the given target node (payee).
1014 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
1015 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1017 /// Private routing paths between a public node and the target may be included in `params.payee`.
1019 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1020 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1021 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1023 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1024 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1025 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1029 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
1030 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
1035 /// Panics if first_hops contains channels without short_channel_ids;
1036 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1038 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1039 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1040 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1041 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1042 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1043 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1044 scorer: &S, random_seed_bytes: &[u8; 32]
1045 ) -> Result<Route, LightningError>
1046 where L::Target: Logger, GL::Target: Logger {
1047 let graph_lock = network_graph.read_only();
1048 let final_cltv_expiry_delta = route_params.payment_params.final_cltv_expiry_delta;
1049 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1050 route_params.final_value_msat, final_cltv_expiry_delta, logger, scorer,
1051 random_seed_bytes)?;
1052 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1056 pub(crate) fn get_route<L: Deref, S: Score>(
1057 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1058 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
1059 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
1060 ) -> Result<Route, LightningError>
1061 where L::Target: Logger {
1062 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
1063 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1065 if payee_node_id == our_node_id {
1066 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1069 if final_value_msat > MAX_VALUE_MSAT {
1070 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1073 if final_value_msat == 0 {
1074 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1077 match &payment_params.route_hints {
1078 Hints::Clear(hints) => {
1079 for route in hints.iter() {
1080 for hop in &route.0 {
1081 if hop.src_node_id == payment_params.payee_pubkey {
1082 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1087 _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1090 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1091 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});
1094 // TODO: Remove the explicit final_cltv_expiry_delta parameter
1095 debug_assert_eq!(final_cltv_expiry_delta, payment_params.final_cltv_expiry_delta);
1097 // The general routing idea is the following:
1098 // 1. Fill first/last hops communicated by the caller.
1099 // 2. Attempt to construct a path from payer to payee for transferring
1100 // any ~sufficient (described later) value.
1101 // If succeed, remember which channels were used and how much liquidity they have available,
1102 // so that future paths don't rely on the same liquidity.
1103 // 3. Proceed to the next step if:
1104 // - we hit the recommended target value;
1105 // - OR if we could not construct a new path. Any next attempt will fail too.
1106 // Otherwise, repeat step 2.
1107 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1108 // (not recommended value).
1109 // 5. If yes, proceed. If not, fail routing.
1110 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1111 // transferred up to the transfer target value.
1112 // 7. Reduce the value of the last path until we are sending only the target value.
1113 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1114 // them so that we're not sending two HTLCs along the same path.
1116 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1117 // distance from the payee
1119 // We are not a faithful Dijkstra's implementation because we can change values which impact
1120 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1121 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1122 // the value we are currently attempting to send over a path, we simply reduce the value being
1123 // sent along the path for any hops after that channel. This may imply that later fees (which
1124 // we've already tabulated) are lower because a smaller value is passing through the channels
1125 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1126 // channels which were selected earlier (and which may still be used for other paths without a
1127 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1130 // One potentially problematic case for this algorithm would be if there are many
1131 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1132 // graph walking), we may never find a path which is not liquidity-limited and has lower
1133 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1134 // Because we only consider paths with at least 5% of the total value being sent, the damage
1135 // from such a case should be limited, however this could be further reduced in the future by
1136 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1137 // limits for the purposes of fee calculation.
1139 // Alternatively, we could store more detailed path information in the heap (targets, below)
1140 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1141 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1142 // and practically (as we would need to store dynamically-allocated path information in heap
1143 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1144 // results of such an algorithm would likely be biased towards lower-value paths.
1146 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1147 // outside of our current search value, running a path search more times to gather candidate
1148 // paths at different values. While this may be acceptable, further path searches may increase
1149 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1150 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1151 // the same time, remaining generic across different payment values.
1153 let network_channels = network_graph.channels();
1154 let network_nodes = network_graph.nodes();
1156 if payment_params.max_path_count == 0 {
1157 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1160 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1161 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1163 let allow_mpp = if payment_params.max_path_count == 1 {
1165 } else if let Some(features) = &payment_params.features {
1166 features.supports_basic_mpp()
1167 } else if let Some(node) = network_nodes.get(&payee_node_id) {
1168 if let Some(node_info) = node.announcement_info.as_ref() {
1169 node_info.features.supports_basic_mpp()
1173 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1174 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
1175 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1178 // Prepare the data we'll use for payee-to-payer search by
1179 // inserting first hops suggested by the caller as targets.
1180 // Our search will then attempt to reach them while traversing from the payee node.
1181 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1182 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1183 if let Some(hops) = first_hops {
1185 if chan.get_outbound_payment_scid().is_none() {
1186 panic!("first_hops should be filled in with usable channels, not pending ones");
1188 if chan.counterparty.node_id == *our_node_pubkey {
1189 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1192 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1193 .or_insert(Vec::new())
1196 if first_hop_targets.is_empty() {
1197 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1201 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1202 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1203 // adding duplicate entries when we find a better path to a given node.
1204 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1206 // Map from node_id to information about the best current path to that node, including feerate
1208 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1210 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1211 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1212 // htlc_minimum with extra fees while still finding a cheaper path.
1213 let mut hit_minimum_limit;
1215 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1216 // We start with a path_value of the exact amount we want, and if that generates a route we may
1217 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1218 // amount we want in total across paths, selecting the best subset at the end.
1219 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1220 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1221 let mut path_value_msat = final_value_msat;
1223 // Routing Fragmentation Mitigation heuristic:
1225 // Routing fragmentation across many payment paths increases the overall routing
1226 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1227 // Taking too many smaller paths also increases the chance of payment failure.
1228 // Thus to avoid this effect, we require from our collected links to provide
1229 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1230 // This requirement is currently set to be 1/max_path_count of the payment
1231 // value to ensure we only ever return routes that do not violate this limit.
1232 let minimal_value_contribution_msat: u64 = if allow_mpp {
1233 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1238 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1239 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1240 // drop the requirement by setting this to 0.
1241 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1243 // Keep track of how much liquidity has been used in selected channels. Used to determine
1244 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1245 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1246 // liquidity used in one direction will not offset any used in the opposite direction.
1247 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1248 HashMap::with_capacity(network_nodes.len());
1250 // Keeping track of how much value we already collected across other paths. Helps to decide
1251 // when we want to stop looking for new paths.
1252 let mut already_collected_value_msat = 0;
1254 for (_, channels) in first_hop_targets.iter_mut() {
1255 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1256 // most like to use.
1258 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1259 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1262 // Second, because simply always sorting in descending order would always use our largest
1263 // available outbound capacity, needlessly fragmenting our available channel capacities,
1264 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1265 // which have enough, but not too much, capacity for the payment.
1266 channels.sort_unstable_by(|chan_a, chan_b| {
1267 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1268 // Sort in descending order
1269 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1271 // Sort in ascending order
1272 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1277 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1279 macro_rules! add_entry {
1280 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1281 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1282 // since that value has to be transferred over this channel.
1283 // Returns whether this channel caused an update to `targets`.
1284 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1285 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1286 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1287 // We "return" whether we updated the path at the end, via this:
1288 let mut did_add_update_path_to_src_node = false;
1289 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1290 // practice these cases should be caught earlier:
1291 // - for regular channels at channel announcement (TODO)
1292 // - for first and last hops early in get_route
1293 if $src_node_id != $dest_node_id {
1294 let short_channel_id = $candidate.short_channel_id();
1295 let effective_capacity = $candidate.effective_capacity();
1296 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1298 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1299 // It may be misleading because we might later choose to reduce the value transferred
1300 // over these channels, and the channel which was insufficient might become sufficient.
1301 // Worst case: we drop a good channel here because it can't cover the high following
1302 // fees caused by one expensive channel, but then this channel could have been used
1303 // if the amount being transferred over this path is lower.
1304 // We do this for now, but this is a subject for removal.
1305 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1306 let used_liquidity_msat = used_channel_liquidities
1307 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1308 .map_or(0, |used_liquidity_msat| {
1309 available_value_contribution_msat = available_value_contribution_msat
1310 .saturating_sub(*used_liquidity_msat);
1311 *used_liquidity_msat
1314 // Verify the liquidity offered by this channel complies to the minimal contribution.
1315 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1316 // Do not consider candidate hops that would exceed the maximum path length.
1317 let path_length_to_node = $next_hops_path_length + 1;
1318 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1320 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1321 // In order to already account for some of the privacy enhancing random CLTV
1322 // expiry delta offset we add on top later, we subtract a rough estimate
1323 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1324 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1325 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1326 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1327 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1328 .saturating_add($candidate.cltv_expiry_delta());
1329 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1331 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1332 // Includes paying fees for the use of the following channels.
1333 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1334 Some(result) => result,
1335 // Can't overflow due to how the values were computed right above.
1336 None => unreachable!(),
1338 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1339 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1340 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1342 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1343 let may_overpay_to_meet_path_minimum_msat =
1344 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1345 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1346 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1347 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1349 let payment_failed_on_this_channel =
1350 payment_params.previously_failed_channels.contains(&short_channel_id);
1352 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1353 // bother considering this channel. If retrying with recommended_value_msat may
1354 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1355 // around again with a higher amount.
1356 if !contributes_sufficient_value || exceeds_max_path_length ||
1357 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1358 // Path isn't useful, ignore it and move on.
1359 } else if may_overpay_to_meet_path_minimum_msat {
1360 hit_minimum_limit = true;
1361 } else if over_path_minimum_msat {
1362 // Note that low contribution here (limited by available_liquidity_msat)
1363 // might violate htlc_minimum_msat on the hops which are next along the
1364 // payment path (upstream to the payee). To avoid that, we recompute
1365 // path fees knowing the final path contribution after constructing it.
1366 let path_htlc_minimum_msat = cmp::max(
1367 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1368 .saturating_add($next_hops_path_htlc_minimum_msat),
1369 $candidate.htlc_minimum_msat());
1370 let hm_entry = dist.entry($src_node_id);
1371 let old_entry = hm_entry.or_insert_with(|| {
1372 // If there was previously no known way to access the source node
1373 // (recall it goes payee-to-payer) of short_channel_id, first add a
1374 // semi-dummy record just to compute the fees to reach the source node.
1375 // This will affect our decision on selecting short_channel_id
1376 // as a way to reach the $dest_node_id.
1378 node_id: $dest_node_id.clone(),
1379 candidate: $candidate.clone(),
1381 next_hops_fee_msat: u64::max_value(),
1382 hop_use_fee_msat: u64::max_value(),
1383 total_fee_msat: u64::max_value(),
1384 path_htlc_minimum_msat,
1385 path_penalty_msat: u64::max_value(),
1386 was_processed: false,
1387 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1388 value_contribution_msat,
1392 #[allow(unused_mut)] // We only use the mut in cfg(test)
1393 let mut should_process = !old_entry.was_processed;
1394 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1396 // In test/fuzzing builds, we do extra checks to make sure the skipping
1397 // of already-seen nodes only happens in cases we expect (see below).
1398 if !should_process { should_process = true; }
1402 let mut hop_use_fee_msat = 0;
1403 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1405 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1406 // will have the same effective-fee
1407 if $src_node_id != our_node_id {
1408 // Note that `u64::max_value` means we'll always fail the
1409 // `old_entry.total_fee_msat > total_fee_msat` check below
1410 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1411 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1414 let channel_usage = ChannelUsage {
1415 amount_msat: amount_to_transfer_over_msat,
1416 inflight_htlc_msat: used_liquidity_msat,
1419 let channel_penalty_msat = scorer.channel_penalty_msat(
1420 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1422 let path_penalty_msat = $next_hops_path_penalty_msat
1423 .saturating_add(channel_penalty_msat);
1424 let new_graph_node = RouteGraphNode {
1425 node_id: $src_node_id,
1426 lowest_fee_to_node: total_fee_msat,
1427 total_cltv_delta: hop_total_cltv_delta,
1428 value_contribution_msat,
1429 path_htlc_minimum_msat,
1431 path_length_to_node,
1434 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1435 // if this way is cheaper than the already known
1436 // (considering the cost to "reach" this channel from the route destination,
1437 // the cost of using this channel,
1438 // and the cost of routing to the source node of this channel).
1439 // Also, consider that htlc_minimum_msat_difference, because we might end up
1440 // paying it. Consider the following exploit:
1441 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1442 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1443 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1444 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1446 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1447 // but it may require additional tracking - we don't want to double-count
1448 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1449 // can't use something that may decrease on future hops.
1450 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1451 .saturating_add(old_entry.path_penalty_msat);
1452 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1453 .saturating_add(path_penalty_msat);
1455 if !old_entry.was_processed && new_cost < old_cost {
1456 targets.push(new_graph_node);
1457 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1458 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1459 old_entry.total_fee_msat = total_fee_msat;
1460 old_entry.node_id = $dest_node_id.clone();
1461 old_entry.candidate = $candidate.clone();
1462 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1463 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1464 old_entry.path_penalty_msat = path_penalty_msat;
1465 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1467 old_entry.value_contribution_msat = value_contribution_msat;
1469 did_add_update_path_to_src_node = true;
1470 } else if old_entry.was_processed && new_cost < old_cost {
1471 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1473 // If we're skipping processing a node which was previously
1474 // processed even though we found another path to it with a
1475 // cheaper fee, check that it was because the second path we
1476 // found (which we are processing now) has a lower value
1477 // contribution due to an HTLC minimum limit.
1479 // e.g. take a graph with two paths from node 1 to node 2, one
1480 // through channel A, and one through channel B. Channel A and
1481 // B are both in the to-process heap, with their scores set by
1482 // a higher htlc_minimum than fee.
1483 // Channel A is processed first, and the channels onwards from
1484 // node 1 are added to the to-process heap. Thereafter, we pop
1485 // Channel B off of the heap, note that it has a much more
1486 // restrictive htlc_maximum_msat, and recalculate the fees for
1487 // all of node 1's channels using the new, reduced, amount.
1489 // This would be bogus - we'd be selecting a higher-fee path
1490 // with a lower htlc_maximum_msat instead of the one we'd
1491 // already decided to use.
1492 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1494 value_contribution_msat + path_penalty_msat <
1495 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1503 did_add_update_path_to_src_node
1507 let default_node_features = default_node_features();
1509 // Find ways (channels with destination) to reach a given node and store them
1510 // in the corresponding data structures (routing graph etc).
1511 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1512 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1513 // This data can later be helpful to optimize routing (pay lower fees).
1514 macro_rules! add_entries_to_cheapest_to_target_node {
1515 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1516 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1517 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1518 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1519 let was_processed = elem.was_processed;
1520 elem.was_processed = true;
1523 // Entries are added to dist in add_entry!() when there is a channel from a node.
1524 // Because there are no channels from payee, it will not have a dist entry at this point.
1525 // If we're processing any other node, it is always be the result of a channel from it.
1526 assert_eq!($node_id, payee_node_id);
1531 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1532 for details in first_channels {
1533 let candidate = CandidateRouteHop::FirstHop { details };
1534 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1535 $next_hops_value_contribution,
1536 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1537 $next_hops_cltv_delta, $next_hops_path_length);
1541 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1544 &default_node_features
1547 if !features.requires_unknown_bits() {
1548 for chan_id in $node.channels.iter() {
1549 let chan = network_channels.get(chan_id).unwrap();
1550 if !chan.features.requires_unknown_bits() {
1551 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1552 if first_hops.is_none() || *source != our_node_id {
1553 if directed_channel.direction().enabled {
1554 let candidate = CandidateRouteHop::PublicHop {
1555 info: directed_channel,
1556 short_channel_id: *chan_id,
1558 add_entry!(candidate, *source, $node_id,
1559 $fee_to_target_msat,
1560 $next_hops_value_contribution,
1561 $next_hops_path_htlc_minimum_msat,
1562 $next_hops_path_penalty_msat,
1563 $next_hops_cltv_delta, $next_hops_path_length);
1574 let mut payment_paths = Vec::<PaymentPath>::new();
1576 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1577 'paths_collection: loop {
1578 // For every new path, start from scratch, except for used_channel_liquidities, which
1579 // helps to avoid reusing previously selected paths in future iterations.
1582 hit_minimum_limit = false;
1584 // If first hop is a private channel and the only way to reach the payee, this is the only
1585 // place where it could be added.
1586 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1587 for details in first_channels {
1588 let candidate = CandidateRouteHop::FirstHop { details };
1589 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1591 log_trace!(logger, "{} direct route to payee via SCID {}",
1592 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1596 // Add the payee as a target, so that the payee-to-payer
1597 // search algorithm knows what to start with.
1598 match network_nodes.get(&payee_node_id) {
1599 // The payee is not in our network graph, so nothing to add here.
1600 // There is still a chance of reaching them via last_hops though,
1601 // so don't yet fail the payment here.
1602 // If not, targets.pop() will not even let us enter the loop in step 2.
1605 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1610 // If a caller provided us with last hops, add them to routing targets. Since this happens
1611 // earlier than general path finding, they will be somewhat prioritized, although currently
1612 // it matters only if the fees are exactly the same.
1613 let route_hints = match &payment_params.route_hints {
1614 Hints::Clear(hints) => hints,
1615 _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1617 for route in route_hints.iter().filter(|route| !route.0.is_empty()) {
1618 let first_hop_in_route = &(route.0)[0];
1619 let have_hop_src_in_graph =
1620 // Only add the hops in this route to our candidate set if either
1621 // we have a direct channel to the first hop or the first hop is
1622 // in the regular network graph.
1623 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1624 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1625 if have_hop_src_in_graph {
1626 // We start building the path from reverse, i.e., from payee
1627 // to the first RouteHintHop in the path.
1628 let hop_iter = route.0.iter().rev();
1629 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1630 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1631 let mut hop_used = true;
1632 let mut aggregate_next_hops_fee_msat: u64 = 0;
1633 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1634 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1635 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1636 let mut aggregate_next_hops_path_length: u8 = 0;
1638 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1639 let source = NodeId::from_pubkey(&hop.src_node_id);
1640 let target = NodeId::from_pubkey(&prev_hop_id);
1641 let candidate = network_channels
1642 .get(&hop.short_channel_id)
1643 .and_then(|channel| channel.as_directed_to(&target))
1644 .map(|(info, _)| CandidateRouteHop::PublicHop {
1646 short_channel_id: hop.short_channel_id,
1648 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1650 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1651 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1652 aggregate_next_hops_path_penalty_msat,
1653 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1654 // If this hop was not used then there is no use checking the preceding
1655 // hops in the RouteHint. We can break by just searching for a direct
1656 // channel between last checked hop and first_hop_targets.
1660 let used_liquidity_msat = used_channel_liquidities
1661 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1662 let channel_usage = ChannelUsage {
1663 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1664 inflight_htlc_msat: used_liquidity_msat,
1665 effective_capacity: candidate.effective_capacity(),
1667 let channel_penalty_msat = scorer.channel_penalty_msat(
1668 hop.short_channel_id, &source, &target, channel_usage
1670 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1671 .saturating_add(channel_penalty_msat);
1673 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1674 .saturating_add(hop.cltv_expiry_delta as u32);
1676 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1679 // Searching for a direct channel between last checked hop and first_hop_targets
1680 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1681 for details in first_channels {
1682 let candidate = CandidateRouteHop::FirstHop { details };
1683 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1684 aggregate_next_hops_fee_msat, path_value_msat,
1685 aggregate_next_hops_path_htlc_minimum_msat,
1686 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1687 aggregate_next_hops_path_length);
1695 // In the next values of the iterator, the aggregate fees already reflects
1696 // the sum of value sent from payer (final_value_msat) and routing fees
1697 // for the last node in the RouteHint. We need to just add the fees to
1698 // route through the current node so that the preceding node (next iteration)
1700 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1701 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1702 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1704 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1705 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1706 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1707 .checked_add(hop_htlc_minimum_msat_inc);
1708 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1710 if idx == route.0.len() - 1 {
1711 // The last hop in this iterator is the first hop in
1712 // overall RouteHint.
1713 // If this hop connects to a node with which we have a direct channel,
1714 // ignore the network graph and, if the last hop was added, add our
1715 // direct channel to the candidate set.
1717 // Note that we *must* check if the last hop was added as `add_entry`
1718 // always assumes that the third argument is a node to which we have a
1720 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1721 for details in first_channels {
1722 let candidate = CandidateRouteHop::FirstHop { details };
1723 add_entry!(candidate, our_node_id,
1724 NodeId::from_pubkey(&hop.src_node_id),
1725 aggregate_next_hops_fee_msat, path_value_msat,
1726 aggregate_next_hops_path_htlc_minimum_msat,
1727 aggregate_next_hops_path_penalty_msat,
1728 aggregate_next_hops_cltv_delta,
1729 aggregate_next_hops_path_length);
1737 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1739 // At this point, targets are filled with the data from first and
1740 // last hops communicated by the caller, and the payment receiver.
1741 let mut found_new_path = false;
1744 // If this loop terminates due the exhaustion of targets, two situations are possible:
1745 // - not enough outgoing liquidity:
1746 // 0 < already_collected_value_msat < final_value_msat
1747 // - enough outgoing liquidity:
1748 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1749 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1750 // paths_collection will be stopped because found_new_path==false.
1751 // This is not necessarily a routing failure.
1752 '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() {
1754 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1755 // traversing the graph and arrange the path out of what we found.
1756 if node_id == our_node_id {
1757 let mut new_entry = dist.remove(&our_node_id).unwrap();
1758 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1761 let mut features_set = false;
1762 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1763 for details in first_channels {
1764 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1765 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1766 features_set = true;
1772 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1773 if let Some(node_info) = node.announcement_info.as_ref() {
1774 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1776 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1779 // We can fill in features for everything except hops which were
1780 // provided via the invoice we're paying. We could guess based on the
1781 // recipient's features but for now we simply avoid guessing at all.
1785 // Means we succesfully traversed from the payer to the payee, now
1786 // save this path for the payment route. Also, update the liquidity
1787 // remaining on the used hops, so that we take them into account
1788 // while looking for more paths.
1789 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1793 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1794 Some(payment_hop) => payment_hop,
1795 // We can't arrive at None because, if we ever add an entry to targets,
1796 // we also fill in the entry in dist (see add_entry!).
1797 None => unreachable!(),
1799 // We "propagate" the fees one hop backward (topologically) here,
1800 // so that fees paid for a HTLC forwarding on the current channel are
1801 // associated with the previous channel (where they will be subtracted).
1802 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1803 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1805 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1806 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1808 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1809 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1811 let mut payment_path = PaymentPath {hops: ordered_hops};
1813 // We could have possibly constructed a slightly inconsistent path: since we reduce
1814 // value being transferred along the way, we could have violated htlc_minimum_msat
1815 // on some channels we already passed (assuming dest->source direction). Here, we
1816 // recompute the fees again, so that if that's the case, we match the currently
1817 // underpaid htlc_minimum_msat with fees.
1818 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1819 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1820 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1822 // Since a path allows to transfer as much value as
1823 // the smallest channel it has ("bottleneck"), we should recompute
1824 // the fees so sender HTLC don't overpay fees when traversing
1825 // larger channels than the bottleneck. This may happen because
1826 // when we were selecting those channels we were not aware how much value
1827 // this path will transfer, and the relative fee for them
1828 // might have been computed considering a larger value.
1829 // Remember that we used these channels so that we don't rely
1830 // on the same liquidity in future paths.
1831 let mut prevented_redundant_path_selection = false;
1832 let prev_hop_iter = core::iter::once(&our_node_id)
1833 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1834 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1835 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1836 let used_liquidity_msat = used_channel_liquidities
1837 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1838 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1839 .or_insert(spent_on_hop_msat);
1840 let hop_capacity = hop.candidate.effective_capacity();
1841 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1842 if *used_liquidity_msat == hop_max_msat {
1843 // If this path used all of this channel's available liquidity, we know
1844 // this path will not be selected again in the next loop iteration.
1845 prevented_redundant_path_selection = true;
1847 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1849 if !prevented_redundant_path_selection {
1850 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1851 // we'll probably end up picking the same path again on the next iteration.
1852 // Decrease the available liquidity of a hop in the middle of the path.
1853 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1854 let exhausted = u64::max_value();
1855 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1856 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1857 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1860 // Track the total amount all our collected paths allow to send so that we know
1861 // when to stop looking for more paths
1862 already_collected_value_msat += value_contribution_msat;
1864 payment_paths.push(payment_path);
1865 found_new_path = true;
1866 break 'path_construction;
1869 // If we found a path back to the payee, we shouldn't try to process it again. This is
1870 // the equivalent of the `elem.was_processed` check in
1871 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1872 if node_id == payee_node_id { continue 'path_construction; }
1874 // Otherwise, since the current target node is not us,
1875 // keep "unrolling" the payment graph from payee to payer by
1876 // finding a way to reach the current target from the payer side.
1877 match network_nodes.get(&node_id) {
1880 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1881 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1882 total_cltv_delta, path_length_to_node);
1888 if !found_new_path && channel_saturation_pow_half != 0 {
1889 channel_saturation_pow_half = 0;
1890 continue 'paths_collection;
1892 // If we don't support MPP, no use trying to gather more value ever.
1893 break 'paths_collection;
1897 // Stop either when the recommended value is reached or if no new path was found in this
1899 // In the latter case, making another path finding attempt won't help,
1900 // because we deterministically terminated the search due to low liquidity.
1901 if !found_new_path && channel_saturation_pow_half != 0 {
1902 channel_saturation_pow_half = 0;
1903 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1904 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1905 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1906 break 'paths_collection;
1907 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1908 // Further, if this was our first walk of the graph, and we weren't limited by an
1909 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1910 // limited by an htlc_minimum_msat value, find another path with a higher value,
1911 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1912 // still keeping a lower total fee than this path.
1913 if !hit_minimum_limit {
1914 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1915 break 'paths_collection;
1917 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1918 path_value_msat = recommended_value_msat;
1923 if payment_paths.len() == 0 {
1924 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1927 if already_collected_value_msat < final_value_msat {
1928 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1932 let mut selected_route = payment_paths;
1934 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1935 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1937 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1938 // the value they contribute towards the payment amount.
1939 // We sort in descending order as we will remove from the front in `retain`, next.
1940 selected_route.sort_unstable_by(|a, b|
1941 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1942 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1945 // We should make sure that at least 1 path left.
1946 let mut paths_left = selected_route.len();
1947 selected_route.retain(|path| {
1948 if paths_left == 1 {
1951 let path_value_msat = path.get_value_msat();
1952 if path_value_msat <= overpaid_value_msat {
1953 overpaid_value_msat -= path_value_msat;
1959 debug_assert!(selected_route.len() > 0);
1961 if overpaid_value_msat != 0 {
1963 // Now, subtract the remaining overpaid value from the most-expensive path.
1964 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1965 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1966 selected_route.sort_unstable_by(|a, b| {
1967 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1968 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1969 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1971 let expensive_payment_path = selected_route.first_mut().unwrap();
1973 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1974 // can't go negative.
1975 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1976 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1980 // Sort by the path itself and combine redundant paths.
1981 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1982 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1984 selected_route.sort_unstable_by_key(|path| {
1985 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1986 debug_assert!(path.hops.len() <= key.len());
1987 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1992 for idx in 0..(selected_route.len() - 1) {
1993 if idx + 1 >= selected_route.len() { break; }
1994 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1995 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1996 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1997 selected_route[idx].update_value_and_recompute_fees(new_value);
1998 selected_route.remove(idx + 1);
2002 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
2003 for payment_path in selected_route {
2004 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
2006 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)})?,
2007 node_features: node_features.clone(),
2008 short_channel_id: payment_hop.candidate.short_channel_id(),
2009 channel_features: payment_hop.candidate.features(),
2010 fee_msat: payment_hop.fee_msat,
2011 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
2013 }).collect::<Vec<_>>();
2014 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2015 // applicable for the previous hop.
2016 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
2017 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
2019 selected_paths.push(path);
2021 // Make sure we would never create a route with more paths than we allow.
2022 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
2024 if let Some(features) = &payment_params.features {
2025 for path in selected_paths.iter_mut() {
2026 if let Ok(route_hop) = path.last_mut().unwrap() {
2027 route_hop.node_features = features.to_context();
2033 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
2034 payment_params: Some(payment_params.clone()),
2036 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
2040 // When an adversarial intermediary node observes a payment, it may be able to infer its
2041 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2042 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2043 // payment path by adding a randomized 'shadow route' offset to the final hop.
2044 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2045 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2047 let network_channels = network_graph.channels();
2048 let network_nodes = network_graph.nodes();
2050 for path in route.paths.iter_mut() {
2051 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2053 // Remember the last three nodes of the random walk and avoid looping back on them.
2054 // Init with the last three nodes from the actual path, if possible.
2055 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
2056 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
2057 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
2059 // Choose the last publicly known node as the starting point for the random walk.
2060 let mut cur_hop: Option<NodeId> = None;
2061 let mut path_nonce = [0u8; 12];
2062 if let Some(starting_hop) = path.iter().rev()
2063 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2064 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2065 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2068 // Init PRNG with the path-dependant nonce, which is static for private paths.
2069 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2070 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2072 // Pick a random path length in [1 .. 3]
2073 prng.process_in_place(&mut random_path_bytes);
2074 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2076 for random_hop in 0..random_walk_length {
2077 // If we don't find a suitable offset in the public network graph, we default to
2078 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2079 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2081 if let Some(cur_node_id) = cur_hop {
2082 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2083 // Randomly choose the next unvisited hop.
2084 prng.process_in_place(&mut random_path_bytes);
2085 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2086 .checked_rem(cur_node.channels.len())
2087 .and_then(|index| cur_node.channels.get(index))
2088 .and_then(|id| network_channels.get(id)) {
2089 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2090 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2091 nodes_to_avoid[random_hop] = *next_id;
2092 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2093 cur_hop = Some(*next_id);
2100 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2101 .checked_add(random_hop_offset)
2102 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2105 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2106 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2107 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2109 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2110 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2111 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
2112 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2113 max_path_offset = cmp::max(
2114 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2115 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2116 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2118 // Add 'shadow' CLTV offset to the final hop
2119 if let Some(last_hop) = path.last_mut() {
2120 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2121 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2126 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2127 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2129 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2130 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2131 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2132 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2133 ) -> Result<Route, LightningError>
2134 where L::Target: Logger, GL::Target: Logger {
2135 let graph_lock = network_graph.read_only();
2136 let mut route = build_route_from_hops_internal(
2137 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2138 route_params.final_value_msat, route_params.payment_params.final_cltv_expiry_delta,
2139 logger, random_seed_bytes)?;
2140 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2144 fn build_route_from_hops_internal<L: Deref>(
2145 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2146 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
2147 logger: L, random_seed_bytes: &[u8; 32]
2148 ) -> Result<Route, LightningError> where L::Target: Logger {
2151 our_node_id: NodeId,
2152 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2155 impl Score for HopScorer {
2156 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2157 _usage: ChannelUsage) -> u64
2159 let mut cur_id = self.our_node_id;
2160 for i in 0..self.hop_ids.len() {
2161 if let Some(next_id) = self.hop_ids[i] {
2162 if cur_id == *source && next_id == *target {
2173 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2175 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
2177 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2179 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
2182 impl<'a> Writeable for HopScorer {
2184 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2189 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2190 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2193 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2194 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2195 for i in 0..hops.len() {
2196 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2199 let scorer = HopScorer { our_node_id, hop_ids };
2201 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2202 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
2207 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2208 use crate::routing::utxo::UtxoResult;
2209 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2210 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees, RoutePath,
2211 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2212 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
2213 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2214 use crate::chain::transaction::OutPoint;
2215 use crate::chain::keysinterface::EntropySource;
2216 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2217 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2218 use crate::ln::channelmanager;
2219 use crate::util::config::UserConfig;
2220 use crate::util::test_utils as ln_test_utils;
2221 use crate::util::chacha20::ChaCha20;
2223 use crate::util::ser::{Writeable, Writer};
2225 use bitcoin::hashes::Hash;
2226 use bitcoin::network::constants::Network;
2227 use bitcoin::blockdata::constants::genesis_block;
2228 use bitcoin::blockdata::script::Builder;
2229 use bitcoin::blockdata::opcodes;
2230 use bitcoin::blockdata::transaction::TxOut;
2234 use bitcoin::secp256k1::{PublicKey,SecretKey};
2235 use bitcoin::secp256k1::Secp256k1;
2237 use crate::prelude::*;
2238 use crate::sync::Arc;
2240 use core::convert::TryInto;
2242 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2243 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2244 channelmanager::ChannelDetails {
2245 channel_id: [0; 32],
2246 counterparty: channelmanager::ChannelCounterparty {
2249 unspendable_punishment_reserve: 0,
2250 forwarding_info: None,
2251 outbound_htlc_minimum_msat: None,
2252 outbound_htlc_maximum_msat: None,
2254 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2257 outbound_scid_alias: None,
2258 inbound_scid_alias: None,
2259 channel_value_satoshis: 0,
2262 outbound_capacity_msat,
2263 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2264 inbound_capacity_msat: 42,
2265 unspendable_punishment_reserve: None,
2266 confirmations_required: None,
2267 confirmations: None,
2268 force_close_spend_delay: None,
2269 is_outbound: true, is_channel_ready: true,
2270 is_usable: true, is_public: true,
2271 inbound_htlc_minimum_msat: None,
2272 inbound_htlc_maximum_msat: None,
2274 feerate_sat_per_1000_weight: None
2279 fn simple_route_test() {
2280 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2281 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2282 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2283 let scorer = ln_test_utils::TestScorer::new();
2284 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2285 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2287 // Simple route to 2 via 1
2289 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) {
2290 assert_eq!(err, "Cannot send a payment of 0 msat");
2291 } else { panic!(); }
2293 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2294 assert_eq!(route.paths[0].len(), 2);
2296 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2297 assert_eq!(route.paths[0][0].short_channel_id, 2);
2298 assert_eq!(route.paths[0][0].fee_msat, 100);
2299 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2300 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2301 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2303 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2304 assert_eq!(route.paths[0][1].short_channel_id, 4);
2305 assert_eq!(route.paths[0][1].fee_msat, 100);
2306 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2307 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2308 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2312 fn invalid_first_hop_test() {
2313 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2314 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2315 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2316 let scorer = ln_test_utils::TestScorer::new();
2317 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2318 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2320 // Simple route to 2 via 1
2322 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2324 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2325 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) {
2326 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2327 } else { panic!(); }
2329 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2330 assert_eq!(route.paths[0].len(), 2);
2334 fn htlc_minimum_test() {
2335 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2336 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2337 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2338 let scorer = ln_test_utils::TestScorer::new();
2339 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2340 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2342 // Simple route to 2 via 1
2344 // Disable other paths
2345 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2346 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2347 short_channel_id: 12,
2349 flags: 2, // to disable
2350 cltv_expiry_delta: 0,
2351 htlc_minimum_msat: 0,
2352 htlc_maximum_msat: MAX_VALUE_MSAT,
2354 fee_proportional_millionths: 0,
2355 excess_data: Vec::new()
2357 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2359 short_channel_id: 3,
2361 flags: 2, // to disable
2362 cltv_expiry_delta: 0,
2363 htlc_minimum_msat: 0,
2364 htlc_maximum_msat: MAX_VALUE_MSAT,
2366 fee_proportional_millionths: 0,
2367 excess_data: Vec::new()
2369 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2370 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2371 short_channel_id: 13,
2373 flags: 2, // to disable
2374 cltv_expiry_delta: 0,
2375 htlc_minimum_msat: 0,
2376 htlc_maximum_msat: MAX_VALUE_MSAT,
2378 fee_proportional_millionths: 0,
2379 excess_data: Vec::new()
2381 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2382 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2383 short_channel_id: 6,
2385 flags: 2, // to disable
2386 cltv_expiry_delta: 0,
2387 htlc_minimum_msat: 0,
2388 htlc_maximum_msat: MAX_VALUE_MSAT,
2390 fee_proportional_millionths: 0,
2391 excess_data: Vec::new()
2393 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2394 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2395 short_channel_id: 7,
2397 flags: 2, // to disable
2398 cltv_expiry_delta: 0,
2399 htlc_minimum_msat: 0,
2400 htlc_maximum_msat: MAX_VALUE_MSAT,
2402 fee_proportional_millionths: 0,
2403 excess_data: Vec::new()
2406 // Check against amount_to_transfer_over_msat.
2407 // Set minimal HTLC of 200_000_000 msat.
2408 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2410 short_channel_id: 2,
2413 cltv_expiry_delta: 0,
2414 htlc_minimum_msat: 200_000_000,
2415 htlc_maximum_msat: MAX_VALUE_MSAT,
2417 fee_proportional_millionths: 0,
2418 excess_data: Vec::new()
2421 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2423 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2424 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2425 short_channel_id: 4,
2428 cltv_expiry_delta: 0,
2429 htlc_minimum_msat: 0,
2430 htlc_maximum_msat: 199_999_999,
2432 fee_proportional_millionths: 0,
2433 excess_data: Vec::new()
2436 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2437 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) {
2438 assert_eq!(err, "Failed to find a path to the given destination");
2439 } else { panic!(); }
2441 // Lift the restriction on the first hop.
2442 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2443 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2444 short_channel_id: 2,
2447 cltv_expiry_delta: 0,
2448 htlc_minimum_msat: 0,
2449 htlc_maximum_msat: MAX_VALUE_MSAT,
2451 fee_proportional_millionths: 0,
2452 excess_data: Vec::new()
2455 // A payment above the minimum should pass
2456 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();
2457 assert_eq!(route.paths[0].len(), 2);
2461 fn htlc_minimum_overpay_test() {
2462 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2463 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2464 let config = UserConfig::default();
2465 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
2466 let scorer = ln_test_utils::TestScorer::new();
2467 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2468 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2470 // A route to node#2 via two paths.
2471 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2472 // Thus, they can't send 60 without overpaying.
2473 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2475 short_channel_id: 2,
2478 cltv_expiry_delta: 0,
2479 htlc_minimum_msat: 35_000,
2480 htlc_maximum_msat: 40_000,
2482 fee_proportional_millionths: 0,
2483 excess_data: Vec::new()
2485 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2487 short_channel_id: 12,
2490 cltv_expiry_delta: 0,
2491 htlc_minimum_msat: 35_000,
2492 htlc_maximum_msat: 40_000,
2494 fee_proportional_millionths: 0,
2495 excess_data: Vec::new()
2499 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2501 short_channel_id: 13,
2504 cltv_expiry_delta: 0,
2505 htlc_minimum_msat: 0,
2506 htlc_maximum_msat: MAX_VALUE_MSAT,
2508 fee_proportional_millionths: 0,
2509 excess_data: Vec::new()
2511 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2512 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2513 short_channel_id: 4,
2516 cltv_expiry_delta: 0,
2517 htlc_minimum_msat: 0,
2518 htlc_maximum_msat: MAX_VALUE_MSAT,
2520 fee_proportional_millionths: 0,
2521 excess_data: Vec::new()
2524 // Disable other paths
2525 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2527 short_channel_id: 1,
2529 flags: 2, // to disable
2530 cltv_expiry_delta: 0,
2531 htlc_minimum_msat: 0,
2532 htlc_maximum_msat: MAX_VALUE_MSAT,
2534 fee_proportional_millionths: 0,
2535 excess_data: Vec::new()
2538 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2539 // Overpay fees to hit htlc_minimum_msat.
2540 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2541 // TODO: this could be better balanced to overpay 10k and not 15k.
2542 assert_eq!(overpaid_fees, 15_000);
2544 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2545 // while taking even more fee to match htlc_minimum_msat.
2546 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2547 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2548 short_channel_id: 12,
2551 cltv_expiry_delta: 0,
2552 htlc_minimum_msat: 65_000,
2553 htlc_maximum_msat: 80_000,
2555 fee_proportional_millionths: 0,
2556 excess_data: Vec::new()
2558 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2560 short_channel_id: 2,
2563 cltv_expiry_delta: 0,
2564 htlc_minimum_msat: 0,
2565 htlc_maximum_msat: MAX_VALUE_MSAT,
2567 fee_proportional_millionths: 0,
2568 excess_data: Vec::new()
2570 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2572 short_channel_id: 4,
2575 cltv_expiry_delta: 0,
2576 htlc_minimum_msat: 0,
2577 htlc_maximum_msat: MAX_VALUE_MSAT,
2579 fee_proportional_millionths: 100_000,
2580 excess_data: Vec::new()
2583 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2584 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2585 assert_eq!(route.paths.len(), 1);
2586 assert_eq!(route.paths[0][0].short_channel_id, 12);
2587 let fees = route.paths[0][0].fee_msat;
2588 assert_eq!(fees, 5_000);
2590 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2591 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2592 // the other channel.
2593 assert_eq!(route.paths.len(), 1);
2594 assert_eq!(route.paths[0][0].short_channel_id, 2);
2595 let fees = route.paths[0][0].fee_msat;
2596 assert_eq!(fees, 5_000);
2600 fn disable_channels_test() {
2601 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2602 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2603 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2604 let scorer = ln_test_utils::TestScorer::new();
2605 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2606 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2608 // // Disable channels 4 and 12 by flags=2
2609 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2610 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2611 short_channel_id: 4,
2613 flags: 2, // to disable
2614 cltv_expiry_delta: 0,
2615 htlc_minimum_msat: 0,
2616 htlc_maximum_msat: MAX_VALUE_MSAT,
2618 fee_proportional_millionths: 0,
2619 excess_data: Vec::new()
2621 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2623 short_channel_id: 12,
2625 flags: 2, // to disable
2626 cltv_expiry_delta: 0,
2627 htlc_minimum_msat: 0,
2628 htlc_maximum_msat: MAX_VALUE_MSAT,
2630 fee_proportional_millionths: 0,
2631 excess_data: Vec::new()
2634 // If all the channels require some features we don't understand, route should fail
2635 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) {
2636 assert_eq!(err, "Failed to find a path to the given destination");
2637 } else { panic!(); }
2639 // If we specify a channel to node7, that overrides our local channel view and that gets used
2640 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2641 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();
2642 assert_eq!(route.paths[0].len(), 2);
2644 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2645 assert_eq!(route.paths[0][0].short_channel_id, 42);
2646 assert_eq!(route.paths[0][0].fee_msat, 200);
2647 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2648 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2649 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2651 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2652 assert_eq!(route.paths[0][1].short_channel_id, 13);
2653 assert_eq!(route.paths[0][1].fee_msat, 100);
2654 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2655 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2656 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2660 fn disable_node_test() {
2661 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2662 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2663 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2664 let scorer = ln_test_utils::TestScorer::new();
2665 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2666 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2668 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2669 let mut unknown_features = NodeFeatures::empty();
2670 unknown_features.set_unknown_feature_required();
2671 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2672 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2673 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2675 // If all nodes require some features we don't understand, route should fail
2676 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) {
2677 assert_eq!(err, "Failed to find a path to the given destination");
2678 } else { panic!(); }
2680 // If we specify a channel to node7, that overrides our local channel view and that gets used
2681 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2682 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();
2683 assert_eq!(route.paths[0].len(), 2);
2685 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2686 assert_eq!(route.paths[0][0].short_channel_id, 42);
2687 assert_eq!(route.paths[0][0].fee_msat, 200);
2688 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2689 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2690 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2692 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2693 assert_eq!(route.paths[0][1].short_channel_id, 13);
2694 assert_eq!(route.paths[0][1].fee_msat, 100);
2695 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2696 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2697 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2699 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2700 // naively) assume that the user checked the feature bits on the invoice, which override
2701 // the node_announcement.
2705 fn our_chans_test() {
2706 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2707 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2708 let scorer = ln_test_utils::TestScorer::new();
2709 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2710 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2712 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2713 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
2714 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2715 assert_eq!(route.paths[0].len(), 3);
2717 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2718 assert_eq!(route.paths[0][0].short_channel_id, 2);
2719 assert_eq!(route.paths[0][0].fee_msat, 200);
2720 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2721 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2722 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2724 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2725 assert_eq!(route.paths[0][1].short_channel_id, 4);
2726 assert_eq!(route.paths[0][1].fee_msat, 100);
2727 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2728 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2729 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2731 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2732 assert_eq!(route.paths[0][2].short_channel_id, 3);
2733 assert_eq!(route.paths[0][2].fee_msat, 100);
2734 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2735 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2736 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2738 // If we specify a channel to node7, that overrides our local channel view and that gets used
2739 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2740 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2741 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();
2742 assert_eq!(route.paths[0].len(), 2);
2744 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2745 assert_eq!(route.paths[0][0].short_channel_id, 42);
2746 assert_eq!(route.paths[0][0].fee_msat, 200);
2747 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2748 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2749 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2751 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2752 assert_eq!(route.paths[0][1].short_channel_id, 13);
2753 assert_eq!(route.paths[0][1].fee_msat, 100);
2754 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2755 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2756 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2759 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2760 let zero_fees = RoutingFees {
2762 proportional_millionths: 0,
2764 vec![RouteHint(vec![RouteHintHop {
2765 src_node_id: nodes[3],
2766 short_channel_id: 8,
2768 cltv_expiry_delta: (8 << 4) | 1,
2769 htlc_minimum_msat: None,
2770 htlc_maximum_msat: None,
2772 ]), RouteHint(vec![RouteHintHop {
2773 src_node_id: nodes[4],
2774 short_channel_id: 9,
2777 proportional_millionths: 0,
2779 cltv_expiry_delta: (9 << 4) | 1,
2780 htlc_minimum_msat: None,
2781 htlc_maximum_msat: None,
2782 }]), RouteHint(vec![RouteHintHop {
2783 src_node_id: nodes[5],
2784 short_channel_id: 10,
2786 cltv_expiry_delta: (10 << 4) | 1,
2787 htlc_minimum_msat: None,
2788 htlc_maximum_msat: None,
2792 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2793 let zero_fees = RoutingFees {
2795 proportional_millionths: 0,
2797 vec![RouteHint(vec![RouteHintHop {
2798 src_node_id: nodes[2],
2799 short_channel_id: 5,
2802 proportional_millionths: 0,
2804 cltv_expiry_delta: (5 << 4) | 1,
2805 htlc_minimum_msat: None,
2806 htlc_maximum_msat: None,
2808 src_node_id: nodes[3],
2809 short_channel_id: 8,
2811 cltv_expiry_delta: (8 << 4) | 1,
2812 htlc_minimum_msat: None,
2813 htlc_maximum_msat: None,
2815 ]), RouteHint(vec![RouteHintHop {
2816 src_node_id: nodes[4],
2817 short_channel_id: 9,
2820 proportional_millionths: 0,
2822 cltv_expiry_delta: (9 << 4) | 1,
2823 htlc_minimum_msat: None,
2824 htlc_maximum_msat: None,
2825 }]), RouteHint(vec![RouteHintHop {
2826 src_node_id: nodes[5],
2827 short_channel_id: 10,
2829 cltv_expiry_delta: (10 << 4) | 1,
2830 htlc_minimum_msat: None,
2831 htlc_maximum_msat: None,
2836 fn partial_route_hint_test() {
2837 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2838 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2839 let scorer = ln_test_utils::TestScorer::new();
2840 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2841 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2843 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2844 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2845 // RouteHint may be partially used by the algo to build the best path.
2847 // First check that last hop can't have its source as the payee.
2848 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2849 src_node_id: nodes[6],
2850 short_channel_id: 8,
2853 proportional_millionths: 0,
2855 cltv_expiry_delta: (8 << 4) | 1,
2856 htlc_minimum_msat: None,
2857 htlc_maximum_msat: None,
2860 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2861 invalid_last_hops.push(invalid_last_hop);
2863 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops);
2864 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) {
2865 assert_eq!(err, "Route hint cannot have the payee as the source.");
2866 } else { panic!(); }
2869 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes));
2870 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2871 assert_eq!(route.paths[0].len(), 5);
2873 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2874 assert_eq!(route.paths[0][0].short_channel_id, 2);
2875 assert_eq!(route.paths[0][0].fee_msat, 100);
2876 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2877 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2878 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2880 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2881 assert_eq!(route.paths[0][1].short_channel_id, 4);
2882 assert_eq!(route.paths[0][1].fee_msat, 0);
2883 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2884 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2885 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2887 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2888 assert_eq!(route.paths[0][2].short_channel_id, 6);
2889 assert_eq!(route.paths[0][2].fee_msat, 0);
2890 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2891 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2892 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2894 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2895 assert_eq!(route.paths[0][3].short_channel_id, 11);
2896 assert_eq!(route.paths[0][3].fee_msat, 0);
2897 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2898 // If we have a peer in the node map, we'll use their features here since we don't have
2899 // a way of figuring out their features from the invoice:
2900 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2901 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2903 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2904 assert_eq!(route.paths[0][4].short_channel_id, 8);
2905 assert_eq!(route.paths[0][4].fee_msat, 100);
2906 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2907 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2908 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2911 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2912 let zero_fees = RoutingFees {
2914 proportional_millionths: 0,
2916 vec![RouteHint(vec![RouteHintHop {
2917 src_node_id: nodes[3],
2918 short_channel_id: 8,
2920 cltv_expiry_delta: (8 << 4) | 1,
2921 htlc_minimum_msat: None,
2922 htlc_maximum_msat: None,
2923 }]), RouteHint(vec![
2925 ]), RouteHint(vec![RouteHintHop {
2926 src_node_id: nodes[5],
2927 short_channel_id: 10,
2929 cltv_expiry_delta: (10 << 4) | 1,
2930 htlc_minimum_msat: None,
2931 htlc_maximum_msat: None,
2936 fn ignores_empty_last_hops_test() {
2937 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2938 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2939 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes));
2940 let scorer = ln_test_utils::TestScorer::new();
2941 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2942 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2944 // Test handling of an empty RouteHint passed in Invoice.
2946 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2947 assert_eq!(route.paths[0].len(), 5);
2949 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2950 assert_eq!(route.paths[0][0].short_channel_id, 2);
2951 assert_eq!(route.paths[0][0].fee_msat, 100);
2952 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2953 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2954 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2956 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2957 assert_eq!(route.paths[0][1].short_channel_id, 4);
2958 assert_eq!(route.paths[0][1].fee_msat, 0);
2959 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2960 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2961 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2963 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2964 assert_eq!(route.paths[0][2].short_channel_id, 6);
2965 assert_eq!(route.paths[0][2].fee_msat, 0);
2966 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2967 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2968 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2970 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2971 assert_eq!(route.paths[0][3].short_channel_id, 11);
2972 assert_eq!(route.paths[0][3].fee_msat, 0);
2973 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2974 // If we have a peer in the node map, we'll use their features here since we don't have
2975 // a way of figuring out their features from the invoice:
2976 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2977 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2979 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2980 assert_eq!(route.paths[0][4].short_channel_id, 8);
2981 assert_eq!(route.paths[0][4].fee_msat, 100);
2982 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2983 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2984 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2987 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2989 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2990 let zero_fees = RoutingFees {
2992 proportional_millionths: 0,
2994 vec![RouteHint(vec![RouteHintHop {
2995 src_node_id: hint_hops[0],
2996 short_channel_id: 0xff00,
2999 proportional_millionths: 0,
3001 cltv_expiry_delta: (5 << 4) | 1,
3002 htlc_minimum_msat: None,
3003 htlc_maximum_msat: None,
3005 src_node_id: hint_hops[1],
3006 short_channel_id: 0xff01,
3008 cltv_expiry_delta: (8 << 4) | 1,
3009 htlc_minimum_msat: None,
3010 htlc_maximum_msat: None,
3015 fn multi_hint_last_hops_test() {
3016 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3017 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3018 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3019 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3020 let scorer = ln_test_utils::TestScorer::new();
3021 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3022 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3023 // Test through channels 2, 3, 0xff00, 0xff01.
3024 // Test shows that multiple hop hints are considered.
3026 // Disabling channels 6 & 7 by flags=2
3027 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3028 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3029 short_channel_id: 6,
3031 flags: 2, // to disable
3032 cltv_expiry_delta: 0,
3033 htlc_minimum_msat: 0,
3034 htlc_maximum_msat: MAX_VALUE_MSAT,
3036 fee_proportional_millionths: 0,
3037 excess_data: Vec::new()
3039 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3041 short_channel_id: 7,
3043 flags: 2, // to disable
3044 cltv_expiry_delta: 0,
3045 htlc_minimum_msat: 0,
3046 htlc_maximum_msat: MAX_VALUE_MSAT,
3048 fee_proportional_millionths: 0,
3049 excess_data: Vec::new()
3052 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3053 assert_eq!(route.paths[0].len(), 4);
3055 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3056 assert_eq!(route.paths[0][0].short_channel_id, 2);
3057 assert_eq!(route.paths[0][0].fee_msat, 200);
3058 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3059 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3060 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3062 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3063 assert_eq!(route.paths[0][1].short_channel_id, 4);
3064 assert_eq!(route.paths[0][1].fee_msat, 100);
3065 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3066 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3067 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3069 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3070 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3071 assert_eq!(route.paths[0][2].fee_msat, 0);
3072 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3073 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3074 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3076 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3077 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3078 assert_eq!(route.paths[0][3].fee_msat, 100);
3079 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3080 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3081 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3085 fn private_multi_hint_last_hops_test() {
3086 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3087 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3089 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3090 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3092 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3093 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3094 let scorer = ln_test_utils::TestScorer::new();
3095 // Test through channels 2, 3, 0xff00, 0xff01.
3096 // Test shows that multiple hop hints are considered.
3098 // Disabling channels 6 & 7 by flags=2
3099 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3101 short_channel_id: 6,
3103 flags: 2, // to disable
3104 cltv_expiry_delta: 0,
3105 htlc_minimum_msat: 0,
3106 htlc_maximum_msat: MAX_VALUE_MSAT,
3108 fee_proportional_millionths: 0,
3109 excess_data: Vec::new()
3111 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3113 short_channel_id: 7,
3115 flags: 2, // to disable
3116 cltv_expiry_delta: 0,
3117 htlc_minimum_msat: 0,
3118 htlc_maximum_msat: MAX_VALUE_MSAT,
3120 fee_proportional_millionths: 0,
3121 excess_data: Vec::new()
3124 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3125 assert_eq!(route.paths[0].len(), 4);
3127 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3128 assert_eq!(route.paths[0][0].short_channel_id, 2);
3129 assert_eq!(route.paths[0][0].fee_msat, 200);
3130 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3131 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3132 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3134 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3135 assert_eq!(route.paths[0][1].short_channel_id, 4);
3136 assert_eq!(route.paths[0][1].fee_msat, 100);
3137 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3138 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3139 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3141 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3142 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3143 assert_eq!(route.paths[0][2].fee_msat, 0);
3144 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3145 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3146 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3148 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3149 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3150 assert_eq!(route.paths[0][3].fee_msat, 100);
3151 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3152 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3153 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3156 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3157 let zero_fees = RoutingFees {
3159 proportional_millionths: 0,
3161 vec![RouteHint(vec![RouteHintHop {
3162 src_node_id: nodes[4],
3163 short_channel_id: 11,
3165 cltv_expiry_delta: (11 << 4) | 1,
3166 htlc_minimum_msat: None,
3167 htlc_maximum_msat: None,
3169 src_node_id: nodes[3],
3170 short_channel_id: 8,
3172 cltv_expiry_delta: (8 << 4) | 1,
3173 htlc_minimum_msat: None,
3174 htlc_maximum_msat: None,
3175 }]), RouteHint(vec![RouteHintHop {
3176 src_node_id: nodes[4],
3177 short_channel_id: 9,
3180 proportional_millionths: 0,
3182 cltv_expiry_delta: (9 << 4) | 1,
3183 htlc_minimum_msat: None,
3184 htlc_maximum_msat: None,
3185 }]), RouteHint(vec![RouteHintHop {
3186 src_node_id: nodes[5],
3187 short_channel_id: 10,
3189 cltv_expiry_delta: (10 << 4) | 1,
3190 htlc_minimum_msat: None,
3191 htlc_maximum_msat: None,
3196 fn last_hops_with_public_channel_test() {
3197 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3198 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3199 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes));
3200 let scorer = ln_test_utils::TestScorer::new();
3201 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3202 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3203 // This test shows that public routes can be present in the invoice
3204 // which would be handled in the same manner.
3206 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3207 assert_eq!(route.paths[0].len(), 5);
3209 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3210 assert_eq!(route.paths[0][0].short_channel_id, 2);
3211 assert_eq!(route.paths[0][0].fee_msat, 100);
3212 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3213 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3214 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3216 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3217 assert_eq!(route.paths[0][1].short_channel_id, 4);
3218 assert_eq!(route.paths[0][1].fee_msat, 0);
3219 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3220 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3221 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3223 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3224 assert_eq!(route.paths[0][2].short_channel_id, 6);
3225 assert_eq!(route.paths[0][2].fee_msat, 0);
3226 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3227 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3228 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3230 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3231 assert_eq!(route.paths[0][3].short_channel_id, 11);
3232 assert_eq!(route.paths[0][3].fee_msat, 0);
3233 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3234 // If we have a peer in the node map, we'll use their features here since we don't have
3235 // a way of figuring out their features from the invoice:
3236 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3237 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3239 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3240 assert_eq!(route.paths[0][4].short_channel_id, 8);
3241 assert_eq!(route.paths[0][4].fee_msat, 100);
3242 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3243 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3244 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3248 fn our_chans_last_hop_connect_test() {
3249 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3250 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3251 let scorer = ln_test_utils::TestScorer::new();
3252 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3253 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3255 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3256 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3257 let mut last_hops = last_hops(&nodes);
3258 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3259 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();
3260 assert_eq!(route.paths[0].len(), 2);
3262 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3263 assert_eq!(route.paths[0][0].short_channel_id, 42);
3264 assert_eq!(route.paths[0][0].fee_msat, 0);
3265 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3266 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3267 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3269 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3270 assert_eq!(route.paths[0][1].short_channel_id, 8);
3271 assert_eq!(route.paths[0][1].fee_msat, 100);
3272 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3273 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3274 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3276 last_hops[0].0[0].fees.base_msat = 1000;
3278 // Revert to via 6 as the fee on 8 goes up
3279 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops);
3280 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3281 assert_eq!(route.paths[0].len(), 4);
3283 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3284 assert_eq!(route.paths[0][0].short_channel_id, 2);
3285 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3286 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3287 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3288 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3290 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3291 assert_eq!(route.paths[0][1].short_channel_id, 4);
3292 assert_eq!(route.paths[0][1].fee_msat, 100);
3293 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3294 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3295 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3297 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3298 assert_eq!(route.paths[0][2].short_channel_id, 7);
3299 assert_eq!(route.paths[0][2].fee_msat, 0);
3300 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3301 // If we have a peer in the node map, we'll use their features here since we don't have
3302 // a way of figuring out their features from the invoice:
3303 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3304 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3306 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3307 assert_eq!(route.paths[0][3].short_channel_id, 10);
3308 assert_eq!(route.paths[0][3].fee_msat, 100);
3309 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3310 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3311 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3313 // ...but still use 8 for larger payments as 6 has a variable feerate
3314 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3315 assert_eq!(route.paths[0].len(), 5);
3317 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3318 assert_eq!(route.paths[0][0].short_channel_id, 2);
3319 assert_eq!(route.paths[0][0].fee_msat, 3000);
3320 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3321 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3322 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3324 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3325 assert_eq!(route.paths[0][1].short_channel_id, 4);
3326 assert_eq!(route.paths[0][1].fee_msat, 0);
3327 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3328 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3329 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3331 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3332 assert_eq!(route.paths[0][2].short_channel_id, 6);
3333 assert_eq!(route.paths[0][2].fee_msat, 0);
3334 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3335 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3336 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3338 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3339 assert_eq!(route.paths[0][3].short_channel_id, 11);
3340 assert_eq!(route.paths[0][3].fee_msat, 1000);
3341 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3342 // If we have a peer in the node map, we'll use their features here since we don't have
3343 // a way of figuring out their features from the invoice:
3344 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3345 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3347 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3348 assert_eq!(route.paths[0][4].short_channel_id, 8);
3349 assert_eq!(route.paths[0][4].fee_msat, 2000);
3350 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3351 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3352 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3355 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> {
3356 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3357 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3358 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3360 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3361 let last_hops = RouteHint(vec![RouteHintHop {
3362 src_node_id: middle_node_id,
3363 short_channel_id: 8,
3366 proportional_millionths: last_hop_fee_prop,
3368 cltv_expiry_delta: (8 << 4) | 1,
3369 htlc_minimum_msat: None,
3370 htlc_maximum_msat: last_hop_htlc_max,
3372 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]);
3373 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3374 let scorer = ln_test_utils::TestScorer::new();
3375 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3376 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3377 let logger = ln_test_utils::TestLogger::new();
3378 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3379 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3380 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3385 fn unannounced_path_test() {
3386 // We should be able to send a payment to a destination without any help of a routing graph
3387 // if we have a channel with a common counterparty that appears in the first and last hop
3389 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3391 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3392 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3393 assert_eq!(route.paths[0].len(), 2);
3395 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3396 assert_eq!(route.paths[0][0].short_channel_id, 42);
3397 assert_eq!(route.paths[0][0].fee_msat, 1001);
3398 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3399 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3400 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3402 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3403 assert_eq!(route.paths[0][1].short_channel_id, 8);
3404 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3405 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3406 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3407 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3411 fn overflow_unannounced_path_test_liquidity_underflow() {
3412 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3413 // the last-hop had a fee which overflowed a u64, we'd panic.
3414 // This was due to us adding the first-hop from us unconditionally, causing us to think
3415 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3416 // In this test, we previously hit a subtraction underflow due to having less available
3417 // liquidity at the last hop than 0.
3418 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());
3422 fn overflow_unannounced_path_test_feerate_overflow() {
3423 // This tests for the same case as above, except instead of hitting a subtraction
3424 // underflow, we hit a case where the fee charged at a hop overflowed.
3425 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());
3429 fn available_amount_while_routing_test() {
3430 // Tests whether we choose the correct available channel amount while routing.
3432 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3433 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3434 let scorer = ln_test_utils::TestScorer::new();
3435 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3436 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3437 let config = UserConfig::default();
3438 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
3440 // We will use a simple single-path route from
3441 // our node to node2 via node0: channels {1, 3}.
3443 // First disable all other paths.
3444 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3445 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3446 short_channel_id: 2,
3449 cltv_expiry_delta: 0,
3450 htlc_minimum_msat: 0,
3451 htlc_maximum_msat: 100_000,
3453 fee_proportional_millionths: 0,
3454 excess_data: Vec::new()
3456 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3458 short_channel_id: 12,
3461 cltv_expiry_delta: 0,
3462 htlc_minimum_msat: 0,
3463 htlc_maximum_msat: 100_000,
3465 fee_proportional_millionths: 0,
3466 excess_data: Vec::new()
3469 // Make the first channel (#1) very permissive,
3470 // and we will be testing all limits on the second channel.
3471 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3473 short_channel_id: 1,
3476 cltv_expiry_delta: 0,
3477 htlc_minimum_msat: 0,
3478 htlc_maximum_msat: 1_000_000_000,
3480 fee_proportional_millionths: 0,
3481 excess_data: Vec::new()
3484 // First, let's see if routing works if we have absolutely no idea about the available amount.
3485 // In this case, it should be set to 250_000 sats.
3486 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3487 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3488 short_channel_id: 3,
3491 cltv_expiry_delta: 0,
3492 htlc_minimum_msat: 0,
3493 htlc_maximum_msat: 250_000_000,
3495 fee_proportional_millionths: 0,
3496 excess_data: Vec::new()
3500 // Attempt to route more than available results in a failure.
3501 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3502 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3503 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3504 } else { panic!(); }
3508 // Now, attempt to route an exact amount we have should be fine.
3509 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();
3510 assert_eq!(route.paths.len(), 1);
3511 let path = route.paths.last().unwrap();
3512 assert_eq!(path.len(), 2);
3513 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3514 assert_eq!(path.final_value_msat(), 250_000_000);
3517 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3518 // Disable channel #1 and use another first hop.
3519 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3520 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3521 short_channel_id: 1,
3524 cltv_expiry_delta: 0,
3525 htlc_minimum_msat: 0,
3526 htlc_maximum_msat: 1_000_000_000,
3528 fee_proportional_millionths: 0,
3529 excess_data: Vec::new()
3532 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3533 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3536 // Attempt to route more than available results in a failure.
3537 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3538 &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) {
3539 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3540 } else { panic!(); }
3544 // Now, attempt to route an exact amount we have should be fine.
3545 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();
3546 assert_eq!(route.paths.len(), 1);
3547 let path = route.paths.last().unwrap();
3548 assert_eq!(path.len(), 2);
3549 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3550 assert_eq!(path.final_value_msat(), 200_000_000);
3553 // Enable channel #1 back.
3554 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3556 short_channel_id: 1,
3559 cltv_expiry_delta: 0,
3560 htlc_minimum_msat: 0,
3561 htlc_maximum_msat: 1_000_000_000,
3563 fee_proportional_millionths: 0,
3564 excess_data: Vec::new()
3568 // Now let's see if routing works if we know only htlc_maximum_msat.
3569 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3571 short_channel_id: 3,
3574 cltv_expiry_delta: 0,
3575 htlc_minimum_msat: 0,
3576 htlc_maximum_msat: 15_000,
3578 fee_proportional_millionths: 0,
3579 excess_data: Vec::new()
3583 // Attempt to route more than available results in a failure.
3584 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3585 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3586 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3587 } else { panic!(); }
3591 // Now, attempt to route an exact amount we have should be fine.
3592 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3593 assert_eq!(route.paths.len(), 1);
3594 let path = route.paths.last().unwrap();
3595 assert_eq!(path.len(), 2);
3596 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3597 assert_eq!(path.final_value_msat(), 15_000);
3600 // Now let's see if routing works if we know only capacity from the UTXO.
3602 // We can't change UTXO capacity on the fly, so we'll disable
3603 // the existing channel and add another one with the capacity we need.
3604 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3606 short_channel_id: 3,
3609 cltv_expiry_delta: 0,
3610 htlc_minimum_msat: 0,
3611 htlc_maximum_msat: MAX_VALUE_MSAT,
3613 fee_proportional_millionths: 0,
3614 excess_data: Vec::new()
3617 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3618 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3619 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3620 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3621 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3623 *chain_monitor.utxo_ret.lock().unwrap() =
3624 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
3625 gossip_sync.add_utxo_lookup(Some(chain_monitor));
3627 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3628 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3629 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3630 short_channel_id: 333,
3633 cltv_expiry_delta: (3 << 4) | 1,
3634 htlc_minimum_msat: 0,
3635 htlc_maximum_msat: 15_000,
3637 fee_proportional_millionths: 0,
3638 excess_data: Vec::new()
3640 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3642 short_channel_id: 333,
3645 cltv_expiry_delta: (3 << 4) | 2,
3646 htlc_minimum_msat: 0,
3647 htlc_maximum_msat: 15_000,
3649 fee_proportional_millionths: 0,
3650 excess_data: Vec::new()
3654 // Attempt to route more than available results in a failure.
3655 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3656 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3657 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3658 } else { panic!(); }
3662 // Now, attempt to route an exact amount we have should be fine.
3663 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3664 assert_eq!(route.paths.len(), 1);
3665 let path = route.paths.last().unwrap();
3666 assert_eq!(path.len(), 2);
3667 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3668 assert_eq!(path.final_value_msat(), 15_000);
3671 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3672 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3674 short_channel_id: 333,
3677 cltv_expiry_delta: 0,
3678 htlc_minimum_msat: 0,
3679 htlc_maximum_msat: 10_000,
3681 fee_proportional_millionths: 0,
3682 excess_data: Vec::new()
3686 // Attempt to route more than available results in a failure.
3687 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3688 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3689 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3690 } else { panic!(); }
3694 // Now, attempt to route an exact amount we have should be fine.
3695 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3696 assert_eq!(route.paths.len(), 1);
3697 let path = route.paths.last().unwrap();
3698 assert_eq!(path.len(), 2);
3699 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3700 assert_eq!(path.final_value_msat(), 10_000);
3705 fn available_liquidity_last_hop_test() {
3706 // Check that available liquidity properly limits the path even when only
3707 // one of the latter hops is limited.
3708 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3709 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3710 let scorer = ln_test_utils::TestScorer::new();
3711 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3712 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3713 let config = UserConfig::default();
3714 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
3716 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3717 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3718 // Total capacity: 50 sats.
3720 // Disable other potential paths.
3721 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3722 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3723 short_channel_id: 2,
3726 cltv_expiry_delta: 0,
3727 htlc_minimum_msat: 0,
3728 htlc_maximum_msat: 100_000,
3730 fee_proportional_millionths: 0,
3731 excess_data: Vec::new()
3733 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3734 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3735 short_channel_id: 7,
3738 cltv_expiry_delta: 0,
3739 htlc_minimum_msat: 0,
3740 htlc_maximum_msat: 100_000,
3742 fee_proportional_millionths: 0,
3743 excess_data: Vec::new()
3748 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3749 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3750 short_channel_id: 12,
3753 cltv_expiry_delta: 0,
3754 htlc_minimum_msat: 0,
3755 htlc_maximum_msat: 100_000,
3757 fee_proportional_millionths: 0,
3758 excess_data: Vec::new()
3760 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3762 short_channel_id: 13,
3765 cltv_expiry_delta: 0,
3766 htlc_minimum_msat: 0,
3767 htlc_maximum_msat: 100_000,
3769 fee_proportional_millionths: 0,
3770 excess_data: Vec::new()
3773 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3775 short_channel_id: 6,
3778 cltv_expiry_delta: 0,
3779 htlc_minimum_msat: 0,
3780 htlc_maximum_msat: 50_000,
3782 fee_proportional_millionths: 0,
3783 excess_data: Vec::new()
3785 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3787 short_channel_id: 11,
3790 cltv_expiry_delta: 0,
3791 htlc_minimum_msat: 0,
3792 htlc_maximum_msat: 100_000,
3794 fee_proportional_millionths: 0,
3795 excess_data: Vec::new()
3798 // Attempt to route more than available results in a failure.
3799 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3800 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3801 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3802 } else { panic!(); }
3806 // Now, attempt to route 49 sats (just a bit below the capacity).
3807 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3808 assert_eq!(route.paths.len(), 1);
3809 let mut total_amount_paid_msat = 0;
3810 for path in &route.paths {
3811 assert_eq!(path.len(), 4);
3812 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3813 total_amount_paid_msat += path.final_value_msat();
3815 assert_eq!(total_amount_paid_msat, 49_000);
3819 // Attempt to route an exact amount is also fine
3820 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3821 assert_eq!(route.paths.len(), 1);
3822 let mut total_amount_paid_msat = 0;
3823 for path in &route.paths {
3824 assert_eq!(path.len(), 4);
3825 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3826 total_amount_paid_msat += path.final_value_msat();
3828 assert_eq!(total_amount_paid_msat, 50_000);
3833 fn ignore_fee_first_hop_test() {
3834 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3835 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3836 let scorer = ln_test_utils::TestScorer::new();
3837 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3838 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3839 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3841 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3842 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3844 short_channel_id: 1,
3847 cltv_expiry_delta: 0,
3848 htlc_minimum_msat: 0,
3849 htlc_maximum_msat: 100_000,
3850 fee_base_msat: 1_000_000,
3851 fee_proportional_millionths: 0,
3852 excess_data: Vec::new()
3854 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3856 short_channel_id: 3,
3859 cltv_expiry_delta: 0,
3860 htlc_minimum_msat: 0,
3861 htlc_maximum_msat: 50_000,
3863 fee_proportional_millionths: 0,
3864 excess_data: Vec::new()
3868 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3869 assert_eq!(route.paths.len(), 1);
3870 let mut total_amount_paid_msat = 0;
3871 for path in &route.paths {
3872 assert_eq!(path.len(), 2);
3873 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3874 total_amount_paid_msat += path.final_value_msat();
3876 assert_eq!(total_amount_paid_msat, 50_000);
3881 fn simple_mpp_route_test() {
3882 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3883 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3884 let scorer = ln_test_utils::TestScorer::new();
3885 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3886 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3887 let config = UserConfig::default();
3888 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3889 .with_features(channelmanager::provided_invoice_features(&config));
3891 // We need a route consisting of 3 paths:
3892 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3893 // To achieve this, the amount being transferred should be around
3894 // the total capacity of these 3 paths.
3896 // First, we set limits on these (previously unlimited) channels.
3897 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3899 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3900 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3902 short_channel_id: 1,
3905 cltv_expiry_delta: 0,
3906 htlc_minimum_msat: 0,
3907 htlc_maximum_msat: 100_000,
3909 fee_proportional_millionths: 0,
3910 excess_data: Vec::new()
3912 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3914 short_channel_id: 3,
3917 cltv_expiry_delta: 0,
3918 htlc_minimum_msat: 0,
3919 htlc_maximum_msat: 50_000,
3921 fee_proportional_millionths: 0,
3922 excess_data: Vec::new()
3925 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3926 // (total limit 60).
3927 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3928 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3929 short_channel_id: 12,
3932 cltv_expiry_delta: 0,
3933 htlc_minimum_msat: 0,
3934 htlc_maximum_msat: 60_000,
3936 fee_proportional_millionths: 0,
3937 excess_data: Vec::new()
3939 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3940 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3941 short_channel_id: 13,
3944 cltv_expiry_delta: 0,
3945 htlc_minimum_msat: 0,
3946 htlc_maximum_msat: 60_000,
3948 fee_proportional_millionths: 0,
3949 excess_data: Vec::new()
3952 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3953 // (total capacity 180 sats).
3954 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3955 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3956 short_channel_id: 2,
3959 cltv_expiry_delta: 0,
3960 htlc_minimum_msat: 0,
3961 htlc_maximum_msat: 200_000,
3963 fee_proportional_millionths: 0,
3964 excess_data: Vec::new()
3966 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3968 short_channel_id: 4,
3971 cltv_expiry_delta: 0,
3972 htlc_minimum_msat: 0,
3973 htlc_maximum_msat: 180_000,
3975 fee_proportional_millionths: 0,
3976 excess_data: Vec::new()
3980 // Attempt to route more than available results in a failure.
3981 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3982 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3983 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3984 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3985 } else { panic!(); }
3989 // Attempt to route while setting max_path_count to 0 results in a failure.
3990 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3991 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3992 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3993 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3994 assert_eq!(err, "Can't find a route with no paths allowed.");
3995 } else { panic!(); }
3999 // Attempt to route while setting max_path_count to 3 results in a failure.
4000 // This is the case because the minimal_value_contribution_msat would require each path
4001 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4002 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4003 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4004 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
4005 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4006 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4007 } else { panic!(); }
4011 // Now, attempt to route 250 sats (just a bit below the capacity).
4012 // Our algorithm should provide us with these 3 paths.
4013 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4014 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4015 assert_eq!(route.paths.len(), 3);
4016 let mut total_amount_paid_msat = 0;
4017 for path in &route.paths {
4018 assert_eq!(path.len(), 2);
4019 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4020 total_amount_paid_msat += path.final_value_msat();
4022 assert_eq!(total_amount_paid_msat, 250_000);
4026 // Attempt to route an exact amount is also fine
4027 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4028 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4029 assert_eq!(route.paths.len(), 3);
4030 let mut total_amount_paid_msat = 0;
4031 for path in &route.paths {
4032 assert_eq!(path.len(), 2);
4033 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4034 total_amount_paid_msat += path.final_value_msat();
4036 assert_eq!(total_amount_paid_msat, 290_000);
4041 fn long_mpp_route_test() {
4042 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4043 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4044 let scorer = ln_test_utils::TestScorer::new();
4045 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4046 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4047 let config = UserConfig::default();
4048 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4050 // We need a route consisting of 3 paths:
4051 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4052 // Note that these paths overlap (channels 5, 12, 13).
4053 // We will route 300 sats.
4054 // Each path will have 100 sats capacity, those channels which
4055 // are used twice will have 200 sats capacity.
4057 // Disable other potential paths.
4058 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4060 short_channel_id: 2,
4063 cltv_expiry_delta: 0,
4064 htlc_minimum_msat: 0,
4065 htlc_maximum_msat: 100_000,
4067 fee_proportional_millionths: 0,
4068 excess_data: Vec::new()
4070 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4072 short_channel_id: 7,
4075 cltv_expiry_delta: 0,
4076 htlc_minimum_msat: 0,
4077 htlc_maximum_msat: 100_000,
4079 fee_proportional_millionths: 0,
4080 excess_data: Vec::new()
4083 // Path via {node0, node2} is channels {1, 3, 5}.
4084 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4085 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4086 short_channel_id: 1,
4089 cltv_expiry_delta: 0,
4090 htlc_minimum_msat: 0,
4091 htlc_maximum_msat: 100_000,
4093 fee_proportional_millionths: 0,
4094 excess_data: Vec::new()
4096 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4097 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4098 short_channel_id: 3,
4101 cltv_expiry_delta: 0,
4102 htlc_minimum_msat: 0,
4103 htlc_maximum_msat: 100_000,
4105 fee_proportional_millionths: 0,
4106 excess_data: Vec::new()
4109 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4110 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4111 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4113 short_channel_id: 5,
4116 cltv_expiry_delta: 0,
4117 htlc_minimum_msat: 0,
4118 htlc_maximum_msat: 200_000,
4120 fee_proportional_millionths: 0,
4121 excess_data: Vec::new()
4124 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4125 // Add 100 sats to the capacities of {12, 13}, because these channels
4126 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4127 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4129 short_channel_id: 12,
4132 cltv_expiry_delta: 0,
4133 htlc_minimum_msat: 0,
4134 htlc_maximum_msat: 200_000,
4136 fee_proportional_millionths: 0,
4137 excess_data: Vec::new()
4139 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4140 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4141 short_channel_id: 13,
4144 cltv_expiry_delta: 0,
4145 htlc_minimum_msat: 0,
4146 htlc_maximum_msat: 200_000,
4148 fee_proportional_millionths: 0,
4149 excess_data: Vec::new()
4152 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4153 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4154 short_channel_id: 6,
4157 cltv_expiry_delta: 0,
4158 htlc_minimum_msat: 0,
4159 htlc_maximum_msat: 100_000,
4161 fee_proportional_millionths: 0,
4162 excess_data: Vec::new()
4164 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4165 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4166 short_channel_id: 11,
4169 cltv_expiry_delta: 0,
4170 htlc_minimum_msat: 0,
4171 htlc_maximum_msat: 100_000,
4173 fee_proportional_millionths: 0,
4174 excess_data: Vec::new()
4177 // Path via {node7, node2} is channels {12, 13, 5}.
4178 // We already limited them to 200 sats (they are used twice for 100 sats).
4179 // Nothing to do here.
4182 // Attempt to route more than available results in a failure.
4183 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4184 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4185 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4186 } else { panic!(); }
4190 // Now, attempt to route 300 sats (exact amount we can route).
4191 // Our algorithm should provide us with these 3 paths, 100 sats each.
4192 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4193 assert_eq!(route.paths.len(), 3);
4195 let mut total_amount_paid_msat = 0;
4196 for path in &route.paths {
4197 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4198 total_amount_paid_msat += path.final_value_msat();
4200 assert_eq!(total_amount_paid_msat, 300_000);
4206 fn mpp_cheaper_route_test() {
4207 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4208 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4209 let scorer = ln_test_utils::TestScorer::new();
4210 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4211 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4212 let config = UserConfig::default();
4213 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4215 // This test checks that if we have two cheaper paths and one more expensive path,
4216 // so that liquidity-wise any 2 of 3 combination is sufficient,
4217 // two cheaper paths will be taken.
4218 // These paths have equal available liquidity.
4220 // We need a combination of 3 paths:
4221 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4222 // Note that these paths overlap (channels 5, 12, 13).
4223 // Each path will have 100 sats capacity, those channels which
4224 // are used twice will have 200 sats capacity.
4226 // Disable other potential paths.
4227 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4229 short_channel_id: 2,
4232 cltv_expiry_delta: 0,
4233 htlc_minimum_msat: 0,
4234 htlc_maximum_msat: 100_000,
4236 fee_proportional_millionths: 0,
4237 excess_data: Vec::new()
4239 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4240 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4241 short_channel_id: 7,
4244 cltv_expiry_delta: 0,
4245 htlc_minimum_msat: 0,
4246 htlc_maximum_msat: 100_000,
4248 fee_proportional_millionths: 0,
4249 excess_data: Vec::new()
4252 // Path via {node0, node2} is channels {1, 3, 5}.
4253 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4254 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4255 short_channel_id: 1,
4258 cltv_expiry_delta: 0,
4259 htlc_minimum_msat: 0,
4260 htlc_maximum_msat: 100_000,
4262 fee_proportional_millionths: 0,
4263 excess_data: Vec::new()
4265 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4266 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4267 short_channel_id: 3,
4270 cltv_expiry_delta: 0,
4271 htlc_minimum_msat: 0,
4272 htlc_maximum_msat: 100_000,
4274 fee_proportional_millionths: 0,
4275 excess_data: Vec::new()
4278 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4279 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4280 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4281 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4282 short_channel_id: 5,
4285 cltv_expiry_delta: 0,
4286 htlc_minimum_msat: 0,
4287 htlc_maximum_msat: 200_000,
4289 fee_proportional_millionths: 0,
4290 excess_data: Vec::new()
4293 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4294 // Add 100 sats to the capacities of {12, 13}, because these channels
4295 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4296 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4297 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4298 short_channel_id: 12,
4301 cltv_expiry_delta: 0,
4302 htlc_minimum_msat: 0,
4303 htlc_maximum_msat: 200_000,
4305 fee_proportional_millionths: 0,
4306 excess_data: Vec::new()
4308 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4309 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4310 short_channel_id: 13,
4313 cltv_expiry_delta: 0,
4314 htlc_minimum_msat: 0,
4315 htlc_maximum_msat: 200_000,
4317 fee_proportional_millionths: 0,
4318 excess_data: Vec::new()
4321 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4322 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4323 short_channel_id: 6,
4326 cltv_expiry_delta: 0,
4327 htlc_minimum_msat: 0,
4328 htlc_maximum_msat: 100_000,
4329 fee_base_msat: 1_000,
4330 fee_proportional_millionths: 0,
4331 excess_data: Vec::new()
4333 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4334 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4335 short_channel_id: 11,
4338 cltv_expiry_delta: 0,
4339 htlc_minimum_msat: 0,
4340 htlc_maximum_msat: 100_000,
4342 fee_proportional_millionths: 0,
4343 excess_data: Vec::new()
4346 // Path via {node7, node2} is channels {12, 13, 5}.
4347 // We already limited them to 200 sats (they are used twice for 100 sats).
4348 // Nothing to do here.
4351 // Now, attempt to route 180 sats.
4352 // Our algorithm should provide us with these 2 paths.
4353 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4354 assert_eq!(route.paths.len(), 2);
4356 let mut total_value_transferred_msat = 0;
4357 let mut total_paid_msat = 0;
4358 for path in &route.paths {
4359 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4360 total_value_transferred_msat += path.final_value_msat();
4362 total_paid_msat += hop.fee_msat;
4365 // If we paid fee, this would be higher.
4366 assert_eq!(total_value_transferred_msat, 180_000);
4367 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4368 assert_eq!(total_fees_paid, 0);
4373 fn fees_on_mpp_route_test() {
4374 // This test makes sure that MPP algorithm properly takes into account
4375 // fees charged on the channels, by making the fees impactful:
4376 // if the fee is not properly accounted for, the behavior is different.
4377 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4378 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4379 let scorer = ln_test_utils::TestScorer::new();
4380 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4381 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4382 let config = UserConfig::default();
4383 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4385 // We need a route consisting of 2 paths:
4386 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4387 // We will route 200 sats, Each path will have 100 sats capacity.
4389 // This test is not particularly stable: e.g.,
4390 // there's a way to route via {node0, node2, node4}.
4391 // It works while pathfinding is deterministic, but can be broken otherwise.
4392 // It's fine to ignore this concern for now.
4394 // Disable other potential paths.
4395 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4397 short_channel_id: 2,
4400 cltv_expiry_delta: 0,
4401 htlc_minimum_msat: 0,
4402 htlc_maximum_msat: 100_000,
4404 fee_proportional_millionths: 0,
4405 excess_data: Vec::new()
4408 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4410 short_channel_id: 7,
4413 cltv_expiry_delta: 0,
4414 htlc_minimum_msat: 0,
4415 htlc_maximum_msat: 100_000,
4417 fee_proportional_millionths: 0,
4418 excess_data: Vec::new()
4421 // Path via {node0, node2} is channels {1, 3, 5}.
4422 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4424 short_channel_id: 1,
4427 cltv_expiry_delta: 0,
4428 htlc_minimum_msat: 0,
4429 htlc_maximum_msat: 100_000,
4431 fee_proportional_millionths: 0,
4432 excess_data: Vec::new()
4434 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4436 short_channel_id: 3,
4439 cltv_expiry_delta: 0,
4440 htlc_minimum_msat: 0,
4441 htlc_maximum_msat: 100_000,
4443 fee_proportional_millionths: 0,
4444 excess_data: Vec::new()
4447 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4448 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4450 short_channel_id: 5,
4453 cltv_expiry_delta: 0,
4454 htlc_minimum_msat: 0,
4455 htlc_maximum_msat: 100_000,
4457 fee_proportional_millionths: 0,
4458 excess_data: Vec::new()
4461 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4462 // All channels should be 100 sats capacity. But for the fee experiment,
4463 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4464 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4465 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4466 // so no matter how large are other channels,
4467 // the whole path will be limited by 100 sats with just these 2 conditions:
4468 // - channel 12 capacity is 250 sats
4469 // - fee for channel 6 is 150 sats
4470 // Let's test this by enforcing these 2 conditions and removing other limits.
4471 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4472 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4473 short_channel_id: 12,
4476 cltv_expiry_delta: 0,
4477 htlc_minimum_msat: 0,
4478 htlc_maximum_msat: 250_000,
4480 fee_proportional_millionths: 0,
4481 excess_data: Vec::new()
4483 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4485 short_channel_id: 13,
4488 cltv_expiry_delta: 0,
4489 htlc_minimum_msat: 0,
4490 htlc_maximum_msat: MAX_VALUE_MSAT,
4492 fee_proportional_millionths: 0,
4493 excess_data: Vec::new()
4496 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4498 short_channel_id: 6,
4501 cltv_expiry_delta: 0,
4502 htlc_minimum_msat: 0,
4503 htlc_maximum_msat: MAX_VALUE_MSAT,
4504 fee_base_msat: 150_000,
4505 fee_proportional_millionths: 0,
4506 excess_data: Vec::new()
4508 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4510 short_channel_id: 11,
4513 cltv_expiry_delta: 0,
4514 htlc_minimum_msat: 0,
4515 htlc_maximum_msat: MAX_VALUE_MSAT,
4517 fee_proportional_millionths: 0,
4518 excess_data: Vec::new()
4522 // Attempt to route more than available results in a failure.
4523 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4524 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4525 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4526 } else { panic!(); }
4530 // Now, attempt to route 200 sats (exact amount we can route).
4531 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4532 assert_eq!(route.paths.len(), 2);
4534 let mut total_amount_paid_msat = 0;
4535 for path in &route.paths {
4536 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4537 total_amount_paid_msat += path.final_value_msat();
4539 assert_eq!(total_amount_paid_msat, 200_000);
4540 assert_eq!(route.get_total_fees(), 150_000);
4545 fn mpp_with_last_hops() {
4546 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4547 // via a single last-hop route hint, we'd fail to route if we first collected routes
4548 // totaling close but not quite enough to fund the full payment.
4550 // This was because we considered last-hop hints to have exactly the sought payment amount
4551 // instead of the amount we were trying to collect, needlessly limiting our path searching
4552 // at the very first hop.
4554 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4555 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4556 // to only have the remaining to-collect amount in available liquidity.
4558 // This bug appeared in production in some specific channel configurations.
4559 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4560 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4561 let scorer = ln_test_utils::TestScorer::new();
4562 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4563 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4564 let config = UserConfig::default();
4565 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_features(channelmanager::provided_invoice_features(&config))
4566 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4567 src_node_id: nodes[2],
4568 short_channel_id: 42,
4569 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4570 cltv_expiry_delta: 42,
4571 htlc_minimum_msat: None,
4572 htlc_maximum_msat: None,
4573 }])]).with_max_channel_saturation_power_of_half(0);
4575 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4576 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4577 // would first use the no-fee route and then fail to find a path along the second route as
4578 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4579 // under 5% of our payment amount.
4580 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4581 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4582 short_channel_id: 1,
4585 cltv_expiry_delta: (5 << 4) | 5,
4586 htlc_minimum_msat: 0,
4587 htlc_maximum_msat: 99_000,
4588 fee_base_msat: u32::max_value(),
4589 fee_proportional_millionths: u32::max_value(),
4590 excess_data: Vec::new()
4592 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4593 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4594 short_channel_id: 2,
4597 cltv_expiry_delta: (5 << 4) | 3,
4598 htlc_minimum_msat: 0,
4599 htlc_maximum_msat: 99_000,
4600 fee_base_msat: u32::max_value(),
4601 fee_proportional_millionths: u32::max_value(),
4602 excess_data: Vec::new()
4604 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4606 short_channel_id: 4,
4609 cltv_expiry_delta: (4 << 4) | 1,
4610 htlc_minimum_msat: 0,
4611 htlc_maximum_msat: MAX_VALUE_MSAT,
4613 fee_proportional_millionths: 0,
4614 excess_data: Vec::new()
4616 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4617 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4618 short_channel_id: 13,
4620 flags: 0|2, // Channel disabled
4621 cltv_expiry_delta: (13 << 4) | 1,
4622 htlc_minimum_msat: 0,
4623 htlc_maximum_msat: MAX_VALUE_MSAT,
4625 fee_proportional_millionths: 2000000,
4626 excess_data: Vec::new()
4629 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4631 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();
4632 assert_eq!(route.paths.len(), 2);
4633 route.paths.sort_by_key(|path| path[0].short_channel_id);
4634 // Paths are manually ordered ordered by SCID, so:
4635 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4636 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4637 assert_eq!(route.paths[0][0].short_channel_id, 1);
4638 assert_eq!(route.paths[0][0].fee_msat, 0);
4639 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4640 assert_eq!(route.paths[1][0].short_channel_id, 2);
4641 assert_eq!(route.paths[1][0].fee_msat, 1);
4642 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4643 assert_eq!(route.get_total_fees(), 1);
4644 assert_eq!(route.get_total_amount(), 100_000);
4648 fn drop_lowest_channel_mpp_route_test() {
4649 // This test checks that low-capacity channel is dropped when after
4650 // path finding we realize that we found more capacity than we need.
4651 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4652 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4653 let scorer = ln_test_utils::TestScorer::new();
4654 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4655 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4656 let config = UserConfig::default();
4657 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config))
4658 .with_max_channel_saturation_power_of_half(0);
4660 // We need a route consisting of 3 paths:
4661 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4663 // The first and the second paths should be sufficient, but the third should be
4664 // cheaper, so that we select it but drop later.
4666 // First, we set limits on these (previously unlimited) channels.
4667 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4669 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4670 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4672 short_channel_id: 1,
4675 cltv_expiry_delta: 0,
4676 htlc_minimum_msat: 0,
4677 htlc_maximum_msat: 100_000,
4679 fee_proportional_millionths: 0,
4680 excess_data: Vec::new()
4682 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4684 short_channel_id: 3,
4687 cltv_expiry_delta: 0,
4688 htlc_minimum_msat: 0,
4689 htlc_maximum_msat: 50_000,
4691 fee_proportional_millionths: 0,
4692 excess_data: Vec::new()
4695 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4696 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4698 short_channel_id: 12,
4701 cltv_expiry_delta: 0,
4702 htlc_minimum_msat: 0,
4703 htlc_maximum_msat: 60_000,
4705 fee_proportional_millionths: 0,
4706 excess_data: Vec::new()
4708 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4709 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4710 short_channel_id: 13,
4713 cltv_expiry_delta: 0,
4714 htlc_minimum_msat: 0,
4715 htlc_maximum_msat: 60_000,
4717 fee_proportional_millionths: 0,
4718 excess_data: Vec::new()
4721 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4722 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4724 short_channel_id: 2,
4727 cltv_expiry_delta: 0,
4728 htlc_minimum_msat: 0,
4729 htlc_maximum_msat: 20_000,
4731 fee_proportional_millionths: 0,
4732 excess_data: Vec::new()
4734 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4735 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4736 short_channel_id: 4,
4739 cltv_expiry_delta: 0,
4740 htlc_minimum_msat: 0,
4741 htlc_maximum_msat: 20_000,
4743 fee_proportional_millionths: 0,
4744 excess_data: Vec::new()
4748 // Attempt to route more than available results in a failure.
4749 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4750 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4751 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4752 } else { panic!(); }
4756 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4757 // Our algorithm should provide us with these 3 paths.
4758 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4759 assert_eq!(route.paths.len(), 3);
4760 let mut total_amount_paid_msat = 0;
4761 for path in &route.paths {
4762 assert_eq!(path.len(), 2);
4763 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4764 total_amount_paid_msat += path.final_value_msat();
4766 assert_eq!(total_amount_paid_msat, 125_000);
4770 // Attempt to route without the last small cheap channel
4771 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4772 assert_eq!(route.paths.len(), 2);
4773 let mut total_amount_paid_msat = 0;
4774 for path in &route.paths {
4775 assert_eq!(path.len(), 2);
4776 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4777 total_amount_paid_msat += path.final_value_msat();
4779 assert_eq!(total_amount_paid_msat, 90_000);
4784 fn min_criteria_consistency() {
4785 // Test that we don't use an inconsistent metric between updating and walking nodes during
4786 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4787 // was updated with a different criterion from the heap sorting, resulting in loops in
4788 // calculated paths. We test for that specific case here.
4790 // We construct a network that looks like this:
4792 // node2 -1(3)2- node3
4796 // node1 -1(5)2- node4 -1(1)2- node6
4802 // We create a loop on the side of our real path - our destination is node 6, with a
4803 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4804 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4805 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4806 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4807 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4808 // "previous hop" being set to node 3, creating a loop in the path.
4809 let secp_ctx = Secp256k1::new();
4810 let logger = Arc::new(ln_test_utils::TestLogger::new());
4811 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
4812 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4813 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4814 let scorer = ln_test_utils::TestScorer::new();
4815 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4816 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4817 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
4819 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4820 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4822 short_channel_id: 6,
4825 cltv_expiry_delta: (6 << 4) | 0,
4826 htlc_minimum_msat: 0,
4827 htlc_maximum_msat: MAX_VALUE_MSAT,
4829 fee_proportional_millionths: 0,
4830 excess_data: Vec::new()
4832 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4834 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4835 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4836 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4837 short_channel_id: 5,
4840 cltv_expiry_delta: (5 << 4) | 0,
4841 htlc_minimum_msat: 0,
4842 htlc_maximum_msat: MAX_VALUE_MSAT,
4844 fee_proportional_millionths: 0,
4845 excess_data: Vec::new()
4847 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4849 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4850 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4851 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4852 short_channel_id: 4,
4855 cltv_expiry_delta: (4 << 4) | 0,
4856 htlc_minimum_msat: 0,
4857 htlc_maximum_msat: MAX_VALUE_MSAT,
4859 fee_proportional_millionths: 0,
4860 excess_data: Vec::new()
4862 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4864 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4865 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4867 short_channel_id: 3,
4870 cltv_expiry_delta: (3 << 4) | 0,
4871 htlc_minimum_msat: 0,
4872 htlc_maximum_msat: MAX_VALUE_MSAT,
4874 fee_proportional_millionths: 0,
4875 excess_data: Vec::new()
4877 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4879 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4880 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4882 short_channel_id: 2,
4885 cltv_expiry_delta: (2 << 4) | 0,
4886 htlc_minimum_msat: 0,
4887 htlc_maximum_msat: MAX_VALUE_MSAT,
4889 fee_proportional_millionths: 0,
4890 excess_data: Vec::new()
4893 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4894 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4896 short_channel_id: 1,
4899 cltv_expiry_delta: (1 << 4) | 0,
4900 htlc_minimum_msat: 100,
4901 htlc_maximum_msat: MAX_VALUE_MSAT,
4903 fee_proportional_millionths: 0,
4904 excess_data: Vec::new()
4906 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4909 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4910 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4911 assert_eq!(route.paths.len(), 1);
4912 assert_eq!(route.paths[0].len(), 3);
4914 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4915 assert_eq!(route.paths[0][0].short_channel_id, 6);
4916 assert_eq!(route.paths[0][0].fee_msat, 100);
4917 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4918 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4919 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4921 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4922 assert_eq!(route.paths[0][1].short_channel_id, 5);
4923 assert_eq!(route.paths[0][1].fee_msat, 0);
4924 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4925 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4926 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4928 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4929 assert_eq!(route.paths[0][2].short_channel_id, 1);
4930 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4931 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4932 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4933 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4939 fn exact_fee_liquidity_limit() {
4940 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4941 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4942 // we calculated fees on a higher value, resulting in us ignoring such paths.
4943 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4944 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4945 let scorer = ln_test_utils::TestScorer::new();
4946 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4947 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4948 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4950 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4952 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4953 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4954 short_channel_id: 2,
4957 cltv_expiry_delta: 0,
4958 htlc_minimum_msat: 0,
4959 htlc_maximum_msat: 85_000,
4961 fee_proportional_millionths: 0,
4962 excess_data: Vec::new()
4965 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4967 short_channel_id: 12,
4970 cltv_expiry_delta: (4 << 4) | 1,
4971 htlc_minimum_msat: 0,
4972 htlc_maximum_msat: 270_000,
4974 fee_proportional_millionths: 1000000,
4975 excess_data: Vec::new()
4979 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4980 // 200% fee charged channel 13 in the 1-to-2 direction.
4981 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4982 assert_eq!(route.paths.len(), 1);
4983 assert_eq!(route.paths[0].len(), 2);
4985 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4986 assert_eq!(route.paths[0][0].short_channel_id, 12);
4987 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4988 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4989 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4990 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4992 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4993 assert_eq!(route.paths[0][1].short_channel_id, 13);
4994 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4995 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4996 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4997 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5002 fn htlc_max_reduction_below_min() {
5003 // Test that if, while walking the graph, we reduce the value being sent to meet an
5004 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5005 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5006 // resulting in us thinking there is no possible path, even if other paths exist.
5007 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5008 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5009 let scorer = ln_test_utils::TestScorer::new();
5010 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5011 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5012 let config = UserConfig::default();
5013 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
5015 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5016 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5017 // then try to send 90_000.
5018 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5020 short_channel_id: 2,
5023 cltv_expiry_delta: 0,
5024 htlc_minimum_msat: 0,
5025 htlc_maximum_msat: 80_000,
5027 fee_proportional_millionths: 0,
5028 excess_data: Vec::new()
5030 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5032 short_channel_id: 4,
5035 cltv_expiry_delta: (4 << 4) | 1,
5036 htlc_minimum_msat: 90_000,
5037 htlc_maximum_msat: MAX_VALUE_MSAT,
5039 fee_proportional_millionths: 0,
5040 excess_data: Vec::new()
5044 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5045 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5046 // expensive) channels 12-13 path.
5047 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5048 assert_eq!(route.paths.len(), 1);
5049 assert_eq!(route.paths[0].len(), 2);
5051 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
5052 assert_eq!(route.paths[0][0].short_channel_id, 12);
5053 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
5054 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
5055 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
5056 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
5058 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
5059 assert_eq!(route.paths[0][1].short_channel_id, 13);
5060 assert_eq!(route.paths[0][1].fee_msat, 90_000);
5061 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5062 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5063 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5068 fn multiple_direct_first_hops() {
5069 // Previously we'd only ever considered one first hop path per counterparty.
5070 // However, as we don't restrict users to one channel per peer, we really need to support
5071 // looking at all first hop paths.
5072 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5073 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5074 // route over multiple channels with the same first hop.
5075 let secp_ctx = Secp256k1::new();
5076 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5077 let logger = Arc::new(ln_test_utils::TestLogger::new());
5078 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5079 let scorer = ln_test_utils::TestScorer::new();
5080 let config = UserConfig::default();
5081 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_features(channelmanager::provided_invoice_features(&config));
5082 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5083 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5086 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5087 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5088 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5089 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5090 assert_eq!(route.paths.len(), 1);
5091 assert_eq!(route.paths[0].len(), 1);
5093 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5094 assert_eq!(route.paths[0][0].short_channel_id, 3);
5095 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5098 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5099 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5100 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5101 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5102 assert_eq!(route.paths.len(), 2);
5103 assert_eq!(route.paths[0].len(), 1);
5104 assert_eq!(route.paths[1].len(), 1);
5106 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
5107 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
5109 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5110 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5112 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5113 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5117 // If we have a bunch of outbound channels to the same node, where most are not
5118 // sufficient to pay the full payment, but one is, we should default to just using the
5119 // one single channel that has sufficient balance, avoiding MPP.
5121 // If we have several options above the 3xpayment value threshold, we should pick the
5122 // smallest of them, avoiding further fragmenting our available outbound balance to
5124 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5125 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5126 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5127 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5128 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5129 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5130 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5131 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5132 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5133 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5134 assert_eq!(route.paths.len(), 1);
5135 assert_eq!(route.paths[0].len(), 1);
5137 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5138 assert_eq!(route.paths[0][0].short_channel_id, 6);
5139 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5144 fn prefers_shorter_route_with_higher_fees() {
5145 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5146 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5147 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5149 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5150 let scorer = ln_test_utils::TestScorer::new();
5151 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5152 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5153 let route = get_route(
5154 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5155 Arc::clone(&logger), &scorer, &random_seed_bytes
5157 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5159 assert_eq!(route.get_total_fees(), 100);
5160 assert_eq!(route.get_total_amount(), 100);
5161 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5163 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5164 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5165 let scorer = FixedPenaltyScorer::with_penalty(100);
5166 let route = get_route(
5167 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5168 Arc::clone(&logger), &scorer, &random_seed_bytes
5170 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5172 assert_eq!(route.get_total_fees(), 300);
5173 assert_eq!(route.get_total_amount(), 100);
5174 assert_eq!(path, vec![2, 4, 7, 10]);
5177 struct BadChannelScorer {
5178 short_channel_id: u64,
5182 impl Writeable for BadChannelScorer {
5183 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5185 impl Score for BadChannelScorer {
5186 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5187 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5190 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5191 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5192 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5193 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5196 struct BadNodeScorer {
5201 impl Writeable for BadNodeScorer {
5202 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5205 impl Score for BadNodeScorer {
5206 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5207 if *target == self.node_id { u64::max_value() } else { 0 }
5210 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5211 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5212 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5213 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5217 fn avoids_routing_through_bad_channels_and_nodes() {
5218 let (secp_ctx, network, _, _, logger) = build_graph();
5219 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5220 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5221 let network_graph = network.read_only();
5223 // A path to nodes[6] exists when no penalties are applied to any channel.
5224 let scorer = ln_test_utils::TestScorer::new();
5225 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5226 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5227 let route = get_route(
5228 &our_id, &payment_params, &network_graph, None, 100, 42,
5229 Arc::clone(&logger), &scorer, &random_seed_bytes
5231 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5233 assert_eq!(route.get_total_fees(), 100);
5234 assert_eq!(route.get_total_amount(), 100);
5235 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5237 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5238 let scorer = BadChannelScorer { short_channel_id: 6 };
5239 let route = get_route(
5240 &our_id, &payment_params, &network_graph, None, 100, 42,
5241 Arc::clone(&logger), &scorer, &random_seed_bytes
5243 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5245 assert_eq!(route.get_total_fees(), 300);
5246 assert_eq!(route.get_total_amount(), 100);
5247 assert_eq!(path, vec![2, 4, 7, 10]);
5249 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5250 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5252 &our_id, &payment_params, &network_graph, None, 100, 42,
5253 Arc::clone(&logger), &scorer, &random_seed_bytes
5255 Err(LightningError { err, .. } ) => {
5256 assert_eq!(err, "Failed to find a path to the given destination");
5258 Ok(_) => panic!("Expected error"),
5263 fn total_fees_single_path() {
5267 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5268 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5269 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5272 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5273 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5274 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5277 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5278 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5279 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5282 payment_params: None,
5285 assert_eq!(route.get_total_fees(), 250);
5286 assert_eq!(route.get_total_amount(), 225);
5290 fn total_fees_multi_path() {
5294 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5295 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5296 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5299 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5300 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5301 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5305 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5306 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5307 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5310 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5311 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5312 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5315 payment_params: None,
5318 assert_eq!(route.get_total_fees(), 200);
5319 assert_eq!(route.get_total_amount(), 300);
5323 fn total_empty_route_no_panic() {
5324 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5325 // would both panic if the route was completely empty. We test to ensure they return 0
5326 // here, even though its somewhat nonsensical as a route.
5327 let route = Route { paths: Vec::new(), payment_params: None };
5329 assert_eq!(route.get_total_fees(), 0);
5330 assert_eq!(route.get_total_amount(), 0);
5334 fn limits_total_cltv_delta() {
5335 let (secp_ctx, network, _, _, logger) = build_graph();
5336 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5337 let network_graph = network.read_only();
5339 let scorer = ln_test_utils::TestScorer::new();
5341 // Make sure that generally there is at least one route available
5342 let feasible_max_total_cltv_delta = 1008;
5343 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5344 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5345 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5346 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5347 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5348 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5349 assert_ne!(path.len(), 0);
5351 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5352 let fail_max_total_cltv_delta = 23;
5353 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5354 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5355 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5357 Err(LightningError { err, .. } ) => {
5358 assert_eq!(err, "Failed to find a path to the given destination");
5360 Ok(_) => panic!("Expected error"),
5365 fn avoids_recently_failed_paths() {
5366 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5367 // randomly inserting channels into it until we can't find a route anymore.
5368 let (secp_ctx, network, _, _, logger) = build_graph();
5369 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5370 let network_graph = network.read_only();
5372 let scorer = ln_test_utils::TestScorer::new();
5373 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5374 .with_max_path_count(1);
5375 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5376 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5378 // We should be able to find a route initially, and then after we fail a few random
5379 // channels eventually we won't be able to any longer.
5380 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5382 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5383 for chan in route.paths[0].iter() {
5384 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5386 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5387 % route.paths[0].len();
5388 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5394 fn limits_path_length() {
5395 let (secp_ctx, network, _, _, logger) = build_line_graph();
5396 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5397 let network_graph = network.read_only();
5399 let scorer = ln_test_utils::TestScorer::new();
5400 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5401 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5403 // First check we can actually create a long route on this graph.
5404 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5405 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5406 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5407 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5408 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5410 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5411 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5412 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5413 Arc::clone(&logger), &scorer, &random_seed_bytes)
5415 Err(LightningError { err, .. } ) => {
5416 assert_eq!(err, "Failed to find a path to the given destination");
5418 Ok(_) => panic!("Expected error"),
5423 fn adds_and_limits_cltv_offset() {
5424 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5425 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5427 let scorer = ln_test_utils::TestScorer::new();
5429 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5430 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5431 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5432 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5433 assert_eq!(route.paths.len(), 1);
5435 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5437 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5438 let mut route_default = route.clone();
5439 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5440 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5441 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5442 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5443 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5445 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5446 let mut route_limited = route.clone();
5447 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5448 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5449 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5450 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5451 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5455 fn adds_plausible_cltv_offset() {
5456 let (secp_ctx, network, _, _, logger) = build_graph();
5457 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5458 let network_graph = network.read_only();
5459 let network_nodes = network_graph.nodes();
5460 let network_channels = network_graph.channels();
5461 let scorer = ln_test_utils::TestScorer::new();
5462 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5463 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5464 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5466 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5467 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5468 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5470 let mut path_plausibility = vec![];
5472 for p in route.paths {
5473 // 1. Select random observation point
5474 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5475 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5477 prng.process_in_place(&mut random_bytes);
5478 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5479 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5481 // 2. Calculate what CLTV expiry delta we would observe there
5482 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5484 // 3. Starting from the observation point, find candidate paths
5485 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5486 candidates.push_back((observation_point, vec![]));
5488 let mut found_plausible_candidate = false;
5490 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5491 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5492 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5493 found_plausible_candidate = true;
5494 break 'candidate_loop;
5498 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5499 for channel_id in &cur_node.channels {
5500 if let Some(channel_info) = network_channels.get(&channel_id) {
5501 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5502 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5503 if cur_path_cltv_deltas.iter().sum::<u32>()
5504 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5505 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5506 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5507 candidates.push_back((*next_id, new_path_cltv_deltas));
5515 path_plausibility.push(found_plausible_candidate);
5517 assert!(path_plausibility.iter().all(|x| *x));
5521 fn builds_correct_path_from_hops() {
5522 let (secp_ctx, network, _, _, logger) = build_graph();
5523 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5524 let network_graph = network.read_only();
5526 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5527 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5529 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5530 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5531 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5532 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5533 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5534 assert_eq!(hops.len(), route.paths[0].len());
5535 for (idx, hop_pubkey) in hops.iter().enumerate() {
5536 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5541 fn avoids_saturating_channels() {
5542 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5543 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5545 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5547 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5548 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5549 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5551 short_channel_id: 4,
5554 cltv_expiry_delta: (4 << 4) | 1,
5555 htlc_minimum_msat: 0,
5556 htlc_maximum_msat: 250_000_000,
5558 fee_proportional_millionths: 0,
5559 excess_data: Vec::new()
5561 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5562 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5563 short_channel_id: 13,
5566 cltv_expiry_delta: (13 << 4) | 1,
5567 htlc_minimum_msat: 0,
5568 htlc_maximum_msat: 250_000_000,
5570 fee_proportional_millionths: 0,
5571 excess_data: Vec::new()
5574 let config = UserConfig::default();
5575 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
5576 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5577 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5578 // 100,000 sats is less than the available liquidity on each channel, set above.
5579 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();
5580 assert_eq!(route.paths.len(), 2);
5581 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5582 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5585 #[cfg(not(feature = "no-std"))]
5586 pub(super) fn random_init_seed() -> u64 {
5587 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5588 use core::hash::{BuildHasher, Hasher};
5589 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5590 println!("Using seed of {}", seed);
5593 #[cfg(not(feature = "no-std"))]
5594 use crate::util::ser::ReadableArgs;
5597 #[cfg(not(feature = "no-std"))]
5598 fn generate_routes() {
5599 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5601 let mut d = match super::bench_utils::get_route_file() {
5608 let logger = ln_test_utils::TestLogger::new();
5609 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5610 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5611 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5613 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5614 let mut seed = random_init_seed() as usize;
5615 let nodes = graph.read_only().nodes().clone();
5616 'load_endpoints: for _ in 0..10 {
5618 seed = seed.overflowing_mul(0xdeadbeef).0;
5619 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5620 seed = seed.overflowing_mul(0xdeadbeef).0;
5621 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5622 let payment_params = PaymentParameters::from_node_id(dst, 42);
5623 let amt = seed as u64 % 200_000_000;
5624 let params = ProbabilisticScoringParameters::default();
5625 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5626 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5627 continue 'load_endpoints;
5634 #[cfg(not(feature = "no-std"))]
5635 fn generate_routes_mpp() {
5636 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5638 let mut d = match super::bench_utils::get_route_file() {
5645 let logger = ln_test_utils::TestLogger::new();
5646 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5647 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5648 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5649 let config = UserConfig::default();
5651 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5652 let mut seed = random_init_seed() as usize;
5653 let nodes = graph.read_only().nodes().clone();
5654 'load_endpoints: for _ in 0..10 {
5656 seed = seed.overflowing_mul(0xdeadbeef).0;
5657 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5658 seed = seed.overflowing_mul(0xdeadbeef).0;
5659 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5660 let payment_params = PaymentParameters::from_node_id(dst, 42).with_features(channelmanager::provided_invoice_features(&config));
5661 let amt = seed as u64 % 200_000_000;
5662 let params = ProbabilisticScoringParameters::default();
5663 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5664 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5665 continue 'load_endpoints;
5672 fn honors_manual_penalties() {
5673 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5674 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5676 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5677 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5679 let scorer_params = ProbabilisticScoringParameters::default();
5680 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5682 // First check set manual penalties are returned by the scorer.
5683 let usage = ChannelUsage {
5685 inflight_htlc_msat: 0,
5686 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5688 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5689 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5690 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5692 // Then check we can get a normal route
5693 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
5694 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5695 assert!(route.is_ok());
5697 // Then check that we can't get a route if we ban an intermediate node.
5698 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5699 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5700 assert!(route.is_err());
5702 // Finally make sure we can route again, when we remove the ban.
5703 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5704 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5705 assert!(route.is_ok());
5709 #[cfg(all(test, not(feature = "no-std")))]
5710 pub(crate) mod bench_utils {
5712 /// Tries to open a network graph file, or panics with a URL to fetch it.
5713 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5714 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
5715 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
5716 .or_else(|_| { // Fall back to guessing based on the binary location
5717 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5718 let mut path = std::env::current_exe().unwrap();
5719 path.pop(); // lightning-...
5721 path.pop(); // debug
5722 path.pop(); // target
5723 path.push("lightning");
5724 path.push("net_graph-2023-01-18.bin");
5725 eprintln!("{}", path.to_str().unwrap());
5728 .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");
5729 #[cfg(require_route_graph_test)]
5730 return Ok(res.unwrap());
5731 #[cfg(not(require_route_graph_test))]
5736 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5739 use bitcoin::hashes::Hash;
5740 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5741 use crate::chain::transaction::OutPoint;
5742 use crate::chain::keysinterface::{EntropySource, KeysManager};
5743 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5744 use crate::ln::features::InvoiceFeatures;
5745 use crate::routing::gossip::NetworkGraph;
5746 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5747 use crate::util::config::UserConfig;
5748 use crate::util::logger::{Logger, Record};
5749 use crate::util::ser::ReadableArgs;
5753 struct DummyLogger {}
5754 impl Logger for DummyLogger {
5755 fn log(&self, _record: &Record) {}
5758 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5759 let mut d = bench_utils::get_route_file().unwrap();
5760 NetworkGraph::read(&mut d, logger).unwrap()
5763 fn payer_pubkey() -> PublicKey {
5764 let secp_ctx = Secp256k1::new();
5765 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5769 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5771 channel_id: [0; 32],
5772 counterparty: ChannelCounterparty {
5773 features: channelmanager::provided_init_features(&UserConfig::default()),
5775 unspendable_punishment_reserve: 0,
5776 forwarding_info: None,
5777 outbound_htlc_minimum_msat: None,
5778 outbound_htlc_maximum_msat: None,
5780 funding_txo: Some(OutPoint {
5781 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5784 short_channel_id: Some(1),
5785 inbound_scid_alias: None,
5786 outbound_scid_alias: None,
5787 channel_value_satoshis: 10_000_000,
5789 balance_msat: 10_000_000,
5790 outbound_capacity_msat: 10_000_000,
5791 next_outbound_htlc_limit_msat: 10_000_000,
5792 inbound_capacity_msat: 0,
5793 unspendable_punishment_reserve: None,
5794 confirmations_required: None,
5795 confirmations: None,
5796 force_close_spend_delay: None,
5798 is_channel_ready: true,
5801 inbound_htlc_minimum_msat: None,
5802 inbound_htlc_maximum_msat: None,
5804 feerate_sat_per_1000_weight: None,
5809 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5810 let logger = DummyLogger {};
5811 let network_graph = read_network_graph(&logger);
5812 let scorer = FixedPenaltyScorer::with_penalty(0);
5813 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5817 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5818 let logger = DummyLogger {};
5819 let network_graph = read_network_graph(&logger);
5820 let scorer = FixedPenaltyScorer::with_penalty(0);
5821 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5825 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5826 let logger = DummyLogger {};
5827 let network_graph = read_network_graph(&logger);
5828 let params = ProbabilisticScoringParameters::default();
5829 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5830 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5834 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5835 let logger = DummyLogger {};
5836 let network_graph = read_network_graph(&logger);
5837 let params = ProbabilisticScoringParameters::default();
5838 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5839 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5842 fn generate_routes<S: Score>(
5843 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5844 features: InvoiceFeatures
5846 let nodes = graph.read_only().nodes().clone();
5847 let payer = payer_pubkey();
5848 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5849 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5851 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5852 let mut routes = Vec::new();
5853 let mut route_endpoints = Vec::new();
5854 let mut seed: usize = 0xdeadbeef;
5855 'load_endpoints: for _ in 0..150 {
5858 let src = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5860 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5861 let params = PaymentParameters::from_node_id(dst, 42).with_features(features.clone());
5862 let first_hop = first_hop(src);
5863 let amt = seed as u64 % 1_000_000;
5864 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5866 route_endpoints.push((first_hop, params, amt));
5867 continue 'load_endpoints;
5872 // ...and seed the scorer with success and failure data...
5873 for route in routes {
5874 let amount = route.get_total_amount();
5875 if amount < 250_000 {
5876 for path in route.paths {
5877 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5879 } else if amount > 750_000 {
5880 for path in route.paths {
5881 let short_channel_id = path[path.len() / 2].short_channel_id;
5882 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5887 // Because we've changed channel scores, its possible we'll take different routes to the
5888 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5889 // requires a too-high CLTV delta.
5890 route_endpoints.retain(|(first_hop, params, amt)| {
5891 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5893 route_endpoints.truncate(100);
5894 assert_eq!(route_endpoints.len(), 100);
5896 // ...then benchmark finding paths between the nodes we learned.
5899 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5900 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());