1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::ln::PaymentHash;
17 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
18 use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
21 use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
22 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
23 use crate::util::logger::{Level, Logger};
24 use crate::util::chacha20::ChaCha20;
27 use crate::prelude::*;
28 use crate::sync::Mutex;
29 use alloc::collections::BinaryHeap;
33 /// A [`Router`] implemented using [`find_route`].
34 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> where
36 S::Target: for <'a> LockableScore<'a>,
40 random_seed_bytes: Mutex<[u8; 32]>,
44 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> DefaultRouter<G, L, S> where
46 S::Target: for <'a> LockableScore<'a>,
48 /// Creates a new router.
49 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S) -> Self {
50 let random_seed_bytes = Mutex::new(random_seed_bytes);
51 Self { network_graph, logger, random_seed_bytes, scorer }
55 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> Router for DefaultRouter<G, L, S> where
57 S::Target: for <'a> LockableScore<'a>,
60 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
61 inflight_htlcs: &InFlightHtlcs
62 ) -> Result<Route, LightningError> {
63 let random_seed_bytes = {
64 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
65 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
66 *locked_random_seed_bytes
70 payer, params, &self.network_graph, first_hops, &*self.logger,
71 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock(), inflight_htlcs),
77 /// A trait defining behavior for routing a payment.
79 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
81 &self, payer: &PublicKey, route_params: &RouteParameters,
82 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
83 ) -> Result<Route, LightningError>;
84 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
85 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
86 fn find_route_with_id(
87 &self, payer: &PublicKey, route_params: &RouteParameters,
88 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
89 _payment_hash: PaymentHash, _payment_id: PaymentId
90 ) -> Result<Route, LightningError> {
91 self.find_route(payer, route_params, first_hops, inflight_htlcs)
95 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
97 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
100 /// [`Score`]: crate::routing::scoring::Score
101 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score> {
103 // Maps a channel's short channel id and its direction to the liquidity used up.
104 inflight_htlcs: &'a InFlightHtlcs,
107 impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> {
108 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
109 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
110 ScorerAccountingForInFlightHtlcs {
118 impl<'a, S: Score> Writeable for ScorerAccountingForInFlightHtlcs<'a, S> {
119 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
122 impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> {
123 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage) -> u64 {
124 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
125 source, target, short_channel_id
127 let usage = ChannelUsage {
128 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
132 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
134 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
138 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
139 self.scorer.payment_path_failed(path, short_channel_id)
142 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
143 self.scorer.payment_path_successful(path)
146 fn probe_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
147 self.scorer.probe_failed(path, short_channel_id)
150 fn probe_successful(&mut self, path: &[&RouteHop]) {
151 self.scorer.probe_successful(path)
155 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
156 /// in-use channel liquidity.
158 pub struct InFlightHtlcs(
159 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
160 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
161 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
163 HashMap<(u64, bool), u64>
167 /// Constructs an empty `InFlightHtlcs`.
168 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
170 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
172 /// (C-not exported) as slices require memory layouts we cannot capture in bindings
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))
216 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
217 pub struct RouteHop {
218 /// The node_id of the node at this hop.
219 pub pubkey: PublicKey,
220 /// The node_announcement features of the node at this hop. For the last hop, these may be
221 /// amended to match the features present in the invoice this node generated.
222 pub node_features: NodeFeatures,
223 /// The channel that should be used from the previous hop to reach this node.
224 pub short_channel_id: u64,
225 /// The channel_announcement features of the channel that should be used from the previous hop
226 /// to reach this node.
227 pub channel_features: ChannelFeatures,
228 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
229 /// For the last hop, this should be the full value of the payment (might be more than
230 /// requested if we had to match htlc_minimum_msat).
232 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
233 /// expected at the destination, in excess of the current block height.
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 routes 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, NOT
252 /// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
253 /// least length one. While the maximum length of any given path is variable, keeping the length
254 /// of any path less or equal to 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::util::events::Event::PaymentPathFailed
261 pub payment_params: Option<PaymentParameters>,
264 pub(crate) trait RoutePath {
265 /// Gets the fees for a given path, excluding any excess paid to the recipient.
266 fn get_path_fees(&self) -> u64;
268 impl RoutePath for Vec<RouteHop> {
269 fn get_path_fees(&self) -> u64 {
270 // Do not count last hop of each path since that's the full value of the payment
271 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
272 .iter().map(|hop| &hop.fee_msat)
278 /// Returns the total amount of fees paid on this [`Route`].
280 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
281 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
282 pub fn get_total_fees(&self) -> u64 {
283 self.paths.iter().map(|path| path.get_path_fees()).sum()
286 /// Returns the total amount paid on this [`Route`], excluding the fees.
287 pub fn get_total_amount(&self) -> u64 {
288 return self.paths.iter()
289 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
294 const SERIALIZATION_VERSION: u8 = 1;
295 const MIN_SERIALIZATION_VERSION: u8 = 1;
297 impl Writeable for Route {
298 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
299 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
300 (self.paths.len() as u64).write(writer)?;
301 for hops in self.paths.iter() {
302 (hops.len() as u8).write(writer)?;
303 for hop in hops.iter() {
307 write_tlv_fields!(writer, {
308 (1, self.payment_params, option),
314 impl Readable for Route {
315 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
316 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
317 let path_count: u64 = Readable::read(reader)?;
318 if path_count == 0 { return Err(DecodeError::InvalidValue); }
319 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
320 let mut min_final_cltv_expiry_delta = u32::max_value();
321 for _ in 0..path_count {
322 let hop_count: u8 = Readable::read(reader)?;
323 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
324 for _ in 0..hop_count {
325 hops.push(Readable::read(reader)?);
327 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
328 min_final_cltv_expiry_delta =
329 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
332 let mut payment_params = None;
333 read_tlv_fields!(reader, {
334 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
336 Ok(Route { paths, payment_params })
340 /// Parameters needed to find a [`Route`].
342 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
343 /// [`Event::PaymentPathFailed`].
345 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
346 #[derive(Clone, Debug, PartialEq, Eq)]
347 pub struct RouteParameters {
348 /// The parameters of the failed payment path.
349 pub payment_params: PaymentParameters,
351 /// The amount in msats sent on the failed payment path.
352 pub final_value_msat: u64,
355 impl Writeable for RouteParameters {
356 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
357 write_tlv_fields!(writer, {
358 (0, self.payment_params, required),
359 (2, self.final_value_msat, required),
360 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
361 // `RouteParameters` directly. For compatibility, we write it here.
362 (4, self.payment_params.final_cltv_expiry_delta, required),
368 impl Readable for RouteParameters {
369 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
370 _init_and_read_tlv_fields!(reader, {
371 (0, payment_params, (required: ReadableArgs, 0)),
372 (2, final_value_msat, required),
373 (4, final_cltv_expiry_delta, required),
375 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
376 if payment_params.final_cltv_expiry_delta == 0 {
377 payment_params.final_cltv_expiry_delta = final_cltv_expiry_delta.0.unwrap();
381 final_value_msat: final_value_msat.0.unwrap(),
386 /// Maximum total CTLV difference we allow for a full payment path.
387 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
389 /// Maximum number of paths we allow an (MPP) payment to have.
390 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
391 // limits, but for now more than 10 paths likely carries too much one-path failure.
392 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
394 // The median hop CLTV expiry delta currently seen in the network.
395 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
397 // During routing, we only consider paths shorter than our maximum length estimate.
398 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
399 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
400 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
402 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
403 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
404 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
405 // (payment_secret and total_msat) = 93 bytes for the final hop.
406 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
407 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
408 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
410 /// The recipient of a payment.
411 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
412 pub struct PaymentParameters {
413 /// The node id of the payee.
414 pub payee_pubkey: PublicKey,
416 /// Features supported by the payee.
418 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
419 /// does not contain any features.
421 /// [`for_keysend`]: Self::for_keysend
422 pub features: Option<InvoiceFeatures>,
424 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
425 pub route_hints: Vec<RouteHint>,
427 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
428 pub expiry_time: Option<u64>,
430 /// The maximum total CLTV delta we accept for the route.
431 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
432 pub max_total_cltv_expiry_delta: u32,
434 /// The maximum number of paths that may be used by (MPP) payments.
435 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
436 pub max_path_count: u8,
438 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
439 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
440 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
441 /// increasing failure probability for those paths.
443 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
444 /// restriction have been found. While paths which meet this criteria will be searched for, it
445 /// is ultimately up to the scorer to select them over other paths.
447 /// A value of 0 will allow payments up to and including a channel's total announced usable
448 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
451 pub max_channel_saturation_power_of_half: u8,
453 /// A list of SCIDs which this payment was previously attempted over and which caused the
454 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
456 pub previously_failed_channels: Vec<u64>,
458 /// The minimum CLTV delta at the end of the route. This value must not be zero.
459 pub final_cltv_expiry_delta: u32,
462 impl Writeable for PaymentParameters {
463 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
464 write_tlv_fields!(writer, {
465 (0, self.payee_pubkey, required),
466 (1, self.max_total_cltv_expiry_delta, required),
467 (2, self.features, option),
468 (3, self.max_path_count, required),
469 (4, self.route_hints, vec_type),
470 (5, self.max_channel_saturation_power_of_half, required),
471 (6, self.expiry_time, option),
472 (7, self.previously_failed_channels, vec_type),
473 (9, self.final_cltv_expiry_delta, required),
479 impl ReadableArgs<u32> for PaymentParameters {
480 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
481 _init_and_read_tlv_fields!(reader, {
482 (0, payee_pubkey, required),
483 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
484 (2, features, option),
485 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
486 (4, route_hints, vec_type),
487 (5, max_channel_saturation_power_of_half, (default_value, 2)),
488 (6, expiry_time, option),
489 (7, previously_failed_channels, vec_type),
490 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
493 payee_pubkey: _init_tlv_based_struct_field!(payee_pubkey, required),
494 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
496 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
497 route_hints: route_hints.unwrap_or(Vec::new()),
498 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
500 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
501 final_cltv_expiry_delta: _init_tlv_based_struct_field!(final_cltv_expiry_delta, (default_value, unused)),
507 impl PaymentParameters {
508 /// Creates a payee with the node id of the given `pubkey`.
510 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
512 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
518 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
519 max_path_count: DEFAULT_MAX_PATH_COUNT,
520 max_channel_saturation_power_of_half: 2,
521 previously_failed_channels: Vec::new(),
522 final_cltv_expiry_delta,
526 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
528 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
530 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
531 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta).with_features(InvoiceFeatures::for_keysend())
534 /// Includes the payee's features.
536 /// (C-not exported) since bindings don't support move semantics
537 pub fn with_features(self, features: InvoiceFeatures) -> Self {
538 Self { features: Some(features), ..self }
541 /// Includes hints for routing to the payee.
543 /// (C-not exported) since bindings don't support move semantics
544 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
545 Self { route_hints, ..self }
548 /// Includes a payment expiration in seconds relative to the UNIX epoch.
550 /// (C-not exported) since bindings don't support move semantics
551 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
552 Self { expiry_time: Some(expiry_time), ..self }
555 /// Includes a limit for the total CLTV expiry delta which is considered during routing
557 /// (C-not exported) since bindings don't support move semantics
558 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
559 Self { max_total_cltv_expiry_delta, ..self }
562 /// Includes a limit for the maximum number of payment paths that may be used.
564 /// (C-not exported) since bindings don't support move semantics
565 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
566 Self { max_path_count, ..self }
569 /// Includes a limit for the maximum number of payment paths that may be used.
571 /// (C-not exported) since bindings don't support move semantics
572 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
573 Self { max_channel_saturation_power_of_half, ..self }
577 /// A list of hops along a payment path terminating with a channel to the recipient.
578 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
579 pub struct RouteHint(pub Vec<RouteHintHop>);
581 impl Writeable for RouteHint {
582 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
583 (self.0.len() as u64).write(writer)?;
584 for hop in self.0.iter() {
591 impl Readable for RouteHint {
592 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
593 let hop_count: u64 = Readable::read(reader)?;
594 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
595 for _ in 0..hop_count {
596 hops.push(Readable::read(reader)?);
602 /// A channel descriptor for a hop along a payment path.
603 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
604 pub struct RouteHintHop {
605 /// The node_id of the non-target end of the route
606 pub src_node_id: PublicKey,
607 /// The short_channel_id of this channel
608 pub short_channel_id: u64,
609 /// The fees which must be paid to use this channel
610 pub fees: RoutingFees,
611 /// The difference in CLTV values between this node and the next node.
612 pub cltv_expiry_delta: u16,
613 /// The minimum value, in msat, which must be relayed to the next hop.
614 pub htlc_minimum_msat: Option<u64>,
615 /// The maximum value in msat available for routing with a single HTLC.
616 pub htlc_maximum_msat: Option<u64>,
619 impl_writeable_tlv_based!(RouteHintHop, {
620 (0, src_node_id, required),
621 (1, htlc_minimum_msat, option),
622 (2, short_channel_id, required),
623 (3, htlc_maximum_msat, option),
625 (6, cltv_expiry_delta, required),
628 #[derive(Eq, PartialEq)]
629 struct RouteGraphNode {
631 lowest_fee_to_node: u64,
632 total_cltv_delta: u32,
633 // The maximum value a yet-to-be-constructed payment path might flow through this node.
634 // This value is upper-bounded by us by:
635 // - how much is needed for a path being constructed
636 // - how much value can channels following this node (up to the destination) can contribute,
637 // considering their capacity and fees
638 value_contribution_msat: u64,
639 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
640 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
641 path_htlc_minimum_msat: u64,
642 /// All penalties incurred from this hop on the way to the destination, as calculated using
644 path_penalty_msat: u64,
645 /// The number of hops walked up to this node.
646 path_length_to_node: u8,
649 impl cmp::Ord for RouteGraphNode {
650 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
651 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
652 .saturating_add(other.path_penalty_msat);
653 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
654 .saturating_add(self.path_penalty_msat);
655 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
659 impl cmp::PartialOrd for RouteGraphNode {
660 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
661 Some(self.cmp(other))
665 /// A wrapper around the various hop representations.
667 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
668 #[derive(Clone, Debug)]
669 enum CandidateRouteHop<'a> {
670 /// A hop from the payer, where the outbound liquidity is known.
672 details: &'a ChannelDetails,
674 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
676 info: DirectedChannelInfo<'a>,
677 short_channel_id: u64,
679 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
681 hint: &'a RouteHintHop,
685 impl<'a> CandidateRouteHop<'a> {
686 fn short_channel_id(&self) -> u64 {
688 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
689 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
690 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
694 // NOTE: This may alloc memory so avoid calling it in a hot code path.
695 fn features(&self) -> ChannelFeatures {
697 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
698 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
699 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
703 fn cltv_expiry_delta(&self) -> u32 {
705 CandidateRouteHop::FirstHop { .. } => 0,
706 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
707 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
711 fn htlc_minimum_msat(&self) -> u64 {
713 CandidateRouteHop::FirstHop { .. } => 0,
714 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
715 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
719 fn fees(&self) -> RoutingFees {
721 CandidateRouteHop::FirstHop { .. } => RoutingFees {
722 base_msat: 0, proportional_millionths: 0,
724 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
725 CandidateRouteHop::PrivateHop { hint } => hint.fees,
729 fn effective_capacity(&self) -> EffectiveCapacity {
731 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
732 liquidity_msat: details.next_outbound_htlc_limit_msat,
734 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
735 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
741 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
742 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
744 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
745 EffectiveCapacity::Infinite => u64::max_value(),
746 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
747 EffectiveCapacity::MaximumHTLC { amount_msat } =>
748 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
749 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
750 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
754 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
755 -> bool where I1::Item: PartialEq<I2::Item> {
757 let a = iter_a.next();
758 let b = iter_b.next();
759 if a.is_none() && b.is_none() { return true; }
760 if a.is_none() || b.is_none() { return false; }
761 if a.unwrap().ne(&b.unwrap()) { return false; }
765 /// It's useful to keep track of the hops associated with the fees required to use them,
766 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
767 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
768 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
770 struct PathBuildingHop<'a> {
771 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
772 // is a larger refactor and will require careful performance analysis.
774 candidate: CandidateRouteHop<'a>,
777 /// All the fees paid *after* this channel on the way to the destination
778 next_hops_fee_msat: u64,
779 /// Fee paid for the use of the current channel (see candidate.fees()).
780 /// The value will be actually deducted from the counterparty balance on the previous link.
781 hop_use_fee_msat: u64,
782 /// Used to compare channels when choosing the for routing.
783 /// Includes paying for the use of a hop and the following hops, as well as
784 /// an estimated cost of reaching this hop.
785 /// Might get stale when fees are recomputed. Primarily for internal use.
787 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
788 /// walk and may be invalid thereafter.
789 path_htlc_minimum_msat: u64,
790 /// All penalties incurred from this channel on the way to the destination, as calculated using
792 path_penalty_msat: u64,
793 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
794 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
795 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
796 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
797 /// avoid processing them again.
799 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
800 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
801 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
802 // value_contribution_msat, which requires tracking it here. See comments below where it is
803 // used for more info.
804 value_contribution_msat: u64,
807 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
808 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
809 let mut debug_struct = f.debug_struct("PathBuildingHop");
811 .field("node_id", &self.node_id)
812 .field("short_channel_id", &self.candidate.short_channel_id())
813 .field("total_fee_msat", &self.total_fee_msat)
814 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
815 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
816 .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)))
817 .field("path_penalty_msat", &self.path_penalty_msat)
818 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
819 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
820 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
821 let debug_struct = debug_struct
822 .field("value_contribution_msat", &self.value_contribution_msat);
823 debug_struct.finish()
827 // Instantiated with a list of hops with correct data in them collected during path finding,
828 // an instance of this struct should be further modified only via given methods.
830 struct PaymentPath<'a> {
831 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
834 impl<'a> PaymentPath<'a> {
835 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
836 fn get_value_msat(&self) -> u64 {
837 self.hops.last().unwrap().0.fee_msat
840 fn get_path_penalty_msat(&self) -> u64 {
841 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
844 fn get_total_fee_paid_msat(&self) -> u64 {
845 if self.hops.len() < 1 {
849 // Can't use next_hops_fee_msat because it gets outdated.
850 for (i, (hop, _)) in self.hops.iter().enumerate() {
851 if i != self.hops.len() - 1 {
852 result += hop.fee_msat;
858 fn get_cost_msat(&self) -> u64 {
859 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
862 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
863 // to change fees may result in an inconsistency.
865 // Sometimes we call this function right after constructing a path which is inconsistent in
866 // that it the value being transferred has decreased while we were doing path finding, leading
867 // to the fees being paid not lining up with the actual limits.
869 // Note that this function is not aware of the available_liquidity limit, and thus does not
870 // support increasing the value being transferred beyond what was selected during the initial
872 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
873 let mut total_fee_paid_msat = 0 as u64;
874 for i in (0..self.hops.len()).rev() {
875 let last_hop = i == self.hops.len() - 1;
877 // For non-last-hop, this value will represent the fees paid on the current hop. It
878 // will consist of the fees for the use of the next hop, and extra fees to match
879 // htlc_minimum_msat of the current channel. Last hop is handled separately.
880 let mut cur_hop_fees_msat = 0;
882 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
885 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
886 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
887 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
888 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
889 // set it too high just to maliciously take more fees by exploiting this
890 // match htlc_minimum_msat logic.
891 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
892 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
893 // Note that there is a risk that *previous hops* (those closer to us, as we go
894 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
896 // This might make us end up with a broken route, although this should be super-rare
897 // in practice, both because of how healthy channels look like, and how we pick
898 // channels in add_entry.
899 // Also, this can't be exploited more heavily than *announce a free path and fail
901 cur_hop_transferred_amount_msat += extra_fees_msat;
902 total_fee_paid_msat += extra_fees_msat;
903 cur_hop_fees_msat += extra_fees_msat;
907 // Final hop is a special case: it usually has just value_msat (by design), but also
908 // it still could overpay for the htlc_minimum_msat.
909 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
911 // Propagate updated fees for the use of the channels to one hop back, where they
912 // will be actually paid (fee_msat). The last hop is handled above separately.
913 cur_hop.fee_msat = cur_hop_fees_msat;
916 // Fee for the use of the current hop which will be deducted on the previous hop.
917 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
918 // this channel is free for us.
920 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
921 cur_hop.hop_use_fee_msat = new_fee;
922 total_fee_paid_msat += new_fee;
924 // It should not be possible because this function is called only to reduce the
925 // value. In that case, compute_fee was already called with the same fees for
926 // larger amount and there was no overflow.
935 /// Calculate the fees required to route the given amount over a channel with the given fees.
936 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
937 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
938 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
942 /// Calculate the fees required to route the given amount over a channel with the given fees,
943 /// saturating to [`u64::max_value`].
944 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
945 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
946 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
947 .saturating_add(channel_fees.base_msat as u64)
950 /// The default `features` we assume for a node in a route, when no `features` are known about that
953 /// Default features are:
954 /// * variable_length_onion_optional
955 fn default_node_features() -> NodeFeatures {
956 let mut features = NodeFeatures::empty();
957 features.set_variable_length_onion_optional();
961 /// Finds a route from us (payer) to the given target node (payee).
963 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
964 /// Without this, MPP will only be used if the payee's features are available in the network graph.
966 /// Private routing paths between a public node and the target may be included in `params.payee`.
968 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
969 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
970 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
972 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
973 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
974 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
978 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
979 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
984 /// Panics if first_hops contains channels without short_channel_ids;
985 /// [`ChannelManager::list_usable_channels`] will never include such channels.
987 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
988 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
989 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
990 pub fn find_route<L: Deref, GL: Deref, S: Score>(
991 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
992 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
993 scorer: &S, random_seed_bytes: &[u8; 32]
994 ) -> Result<Route, LightningError>
995 where L::Target: Logger, GL::Target: Logger {
996 let graph_lock = network_graph.read_only();
997 let final_cltv_expiry_delta = route_params.payment_params.final_cltv_expiry_delta;
998 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
999 route_params.final_value_msat, final_cltv_expiry_delta, logger, scorer,
1000 random_seed_bytes)?;
1001 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1005 pub(crate) fn get_route<L: Deref, S: Score>(
1006 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1007 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
1008 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
1009 ) -> Result<Route, LightningError>
1010 where L::Target: Logger {
1011 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
1012 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1014 if payee_node_id == our_node_id {
1015 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1018 if final_value_msat > MAX_VALUE_MSAT {
1019 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1022 if final_value_msat == 0 {
1023 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1026 for route in payment_params.route_hints.iter() {
1027 for hop in &route.0 {
1028 if hop.src_node_id == payment_params.payee_pubkey {
1029 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1033 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1034 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});
1037 // TODO: Remove the explicit final_cltv_expiry_delta parameter
1038 debug_assert_eq!(final_cltv_expiry_delta, payment_params.final_cltv_expiry_delta);
1040 // The general routing idea is the following:
1041 // 1. Fill first/last hops communicated by the caller.
1042 // 2. Attempt to construct a path from payer to payee for transferring
1043 // any ~sufficient (described later) value.
1044 // If succeed, remember which channels were used and how much liquidity they have available,
1045 // so that future paths don't rely on the same liquidity.
1046 // 3. Proceed to the next step if:
1047 // - we hit the recommended target value;
1048 // - OR if we could not construct a new path. Any next attempt will fail too.
1049 // Otherwise, repeat step 2.
1050 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1051 // (not recommended value).
1052 // 5. If yes, proceed. If not, fail routing.
1053 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1054 // transferred up to the transfer target value.
1055 // 7. Reduce the value of the last path until we are sending only the target value.
1056 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1057 // them so that we're not sending two HTLCs along the same path.
1059 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1060 // distance from the payee
1062 // We are not a faithful Dijkstra's implementation because we can change values which impact
1063 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1064 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1065 // the value we are currently attempting to send over a path, we simply reduce the value being
1066 // sent along the path for any hops after that channel. This may imply that later fees (which
1067 // we've already tabulated) are lower because a smaller value is passing through the channels
1068 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1069 // channels which were selected earlier (and which may still be used for other paths without a
1070 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1073 // One potentially problematic case for this algorithm would be if there are many
1074 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1075 // graph walking), we may never find a path which is not liquidity-limited and has lower
1076 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1077 // Because we only consider paths with at least 5% of the total value being sent, the damage
1078 // from such a case should be limited, however this could be further reduced in the future by
1079 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1080 // limits for the purposes of fee calculation.
1082 // Alternatively, we could store more detailed path information in the heap (targets, below)
1083 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1084 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1085 // and practically (as we would need to store dynamically-allocated path information in heap
1086 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1087 // results of such an algorithm would likely be biased towards lower-value paths.
1089 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1090 // outside of our current search value, running a path search more times to gather candidate
1091 // paths at different values. While this may be acceptable, further path searches may increase
1092 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1093 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1094 // the same time, remaining generic across different payment values.
1096 let network_channels = network_graph.channels();
1097 let network_nodes = network_graph.nodes();
1099 if payment_params.max_path_count == 0 {
1100 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1103 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1104 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1106 let allow_mpp = if payment_params.max_path_count == 1 {
1108 } else if let Some(features) = &payment_params.features {
1109 features.supports_basic_mpp()
1110 } else if let Some(node) = network_nodes.get(&payee_node_id) {
1111 if let Some(node_info) = node.announcement_info.as_ref() {
1112 node_info.features.supports_basic_mpp()
1116 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1117 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
1118 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1121 // Prepare the data we'll use for payee-to-payer search by
1122 // inserting first hops suggested by the caller as targets.
1123 // Our search will then attempt to reach them while traversing from the payee node.
1124 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1125 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1126 if let Some(hops) = first_hops {
1128 if chan.get_outbound_payment_scid().is_none() {
1129 panic!("first_hops should be filled in with usable channels, not pending ones");
1131 if chan.counterparty.node_id == *our_node_pubkey {
1132 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1135 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1136 .or_insert(Vec::new())
1139 if first_hop_targets.is_empty() {
1140 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1144 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1145 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1146 // adding duplicate entries when we find a better path to a given node.
1147 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1149 // Map from node_id to information about the best current path to that node, including feerate
1151 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1153 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1154 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1155 // htlc_minimum with extra fees while still finding a cheaper path.
1156 let mut hit_minimum_limit;
1158 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1159 // We start with a path_value of the exact amount we want, and if that generates a route we may
1160 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1161 // amount we want in total across paths, selecting the best subset at the end.
1162 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1163 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1164 let mut path_value_msat = final_value_msat;
1166 // Routing Fragmentation Mitigation heuristic:
1168 // Routing fragmentation across many payment paths increases the overall routing
1169 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1170 // Taking too many smaller paths also increases the chance of payment failure.
1171 // Thus to avoid this effect, we require from our collected links to provide
1172 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1173 // This requirement is currently set to be 1/max_path_count of the payment
1174 // value to ensure we only ever return routes that do not violate this limit.
1175 let minimal_value_contribution_msat: u64 = if allow_mpp {
1176 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1181 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1182 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1183 // drop the requirement by setting this to 0.
1184 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1186 // Keep track of how much liquidity has been used in selected channels. Used to determine
1187 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1188 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1189 // liquidity used in one direction will not offset any used in the opposite direction.
1190 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1191 HashMap::with_capacity(network_nodes.len());
1193 // Keeping track of how much value we already collected across other paths. Helps to decide
1194 // when we want to stop looking for new paths.
1195 let mut already_collected_value_msat = 0;
1197 for (_, channels) in first_hop_targets.iter_mut() {
1198 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1199 // most like to use.
1201 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1202 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1205 // Second, because simply always sorting in descending order would always use our largest
1206 // available outbound capacity, needlessly fragmenting our available channel capacities,
1207 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1208 // which have enough, but not too much, capacity for the payment.
1209 channels.sort_unstable_by(|chan_a, chan_b| {
1210 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1211 // Sort in descending order
1212 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1214 // Sort in ascending order
1215 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1220 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1222 macro_rules! add_entry {
1223 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1224 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1225 // since that value has to be transferred over this channel.
1226 // Returns whether this channel caused an update to `targets`.
1227 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1228 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1229 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1230 // We "return" whether we updated the path at the end, via this:
1231 let mut did_add_update_path_to_src_node = false;
1232 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1233 // practice these cases should be caught earlier:
1234 // - for regular channels at channel announcement (TODO)
1235 // - for first and last hops early in get_route
1236 if $src_node_id != $dest_node_id {
1237 let short_channel_id = $candidate.short_channel_id();
1238 let effective_capacity = $candidate.effective_capacity();
1239 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1241 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1242 // It may be misleading because we might later choose to reduce the value transferred
1243 // over these channels, and the channel which was insufficient might become sufficient.
1244 // Worst case: we drop a good channel here because it can't cover the high following
1245 // fees caused by one expensive channel, but then this channel could have been used
1246 // if the amount being transferred over this path is lower.
1247 // We do this for now, but this is a subject for removal.
1248 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1249 let used_liquidity_msat = used_channel_liquidities
1250 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1251 .map_or(0, |used_liquidity_msat| {
1252 available_value_contribution_msat = available_value_contribution_msat
1253 .saturating_sub(*used_liquidity_msat);
1254 *used_liquidity_msat
1257 // Verify the liquidity offered by this channel complies to the minimal contribution.
1258 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1259 // Do not consider candidate hops that would exceed the maximum path length.
1260 let path_length_to_node = $next_hops_path_length + 1;
1261 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1263 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1264 // In order to already account for some of the privacy enhancing random CLTV
1265 // expiry delta offset we add on top later, we subtract a rough estimate
1266 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1267 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1268 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1269 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1270 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1271 .saturating_add($candidate.cltv_expiry_delta());
1272 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1274 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1275 // Includes paying fees for the use of the following channels.
1276 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1277 Some(result) => result,
1278 // Can't overflow due to how the values were computed right above.
1279 None => unreachable!(),
1281 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1282 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1283 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1285 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1286 let may_overpay_to_meet_path_minimum_msat =
1287 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1288 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1289 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1290 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1292 let payment_failed_on_this_channel =
1293 payment_params.previously_failed_channels.contains(&short_channel_id);
1295 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1296 // bother considering this channel. If retrying with recommended_value_msat may
1297 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1298 // around again with a higher amount.
1299 if !contributes_sufficient_value || exceeds_max_path_length ||
1300 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1301 // Path isn't useful, ignore it and move on.
1302 } else if may_overpay_to_meet_path_minimum_msat {
1303 hit_minimum_limit = true;
1304 } else if over_path_minimum_msat {
1305 // Note that low contribution here (limited by available_liquidity_msat)
1306 // might violate htlc_minimum_msat on the hops which are next along the
1307 // payment path (upstream to the payee). To avoid that, we recompute
1308 // path fees knowing the final path contribution after constructing it.
1309 let path_htlc_minimum_msat = cmp::max(
1310 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1311 .saturating_add($next_hops_path_htlc_minimum_msat),
1312 $candidate.htlc_minimum_msat());
1313 let hm_entry = dist.entry($src_node_id);
1314 let old_entry = hm_entry.or_insert_with(|| {
1315 // If there was previously no known way to access the source node
1316 // (recall it goes payee-to-payer) of short_channel_id, first add a
1317 // semi-dummy record just to compute the fees to reach the source node.
1318 // This will affect our decision on selecting short_channel_id
1319 // as a way to reach the $dest_node_id.
1321 node_id: $dest_node_id.clone(),
1322 candidate: $candidate.clone(),
1324 next_hops_fee_msat: u64::max_value(),
1325 hop_use_fee_msat: u64::max_value(),
1326 total_fee_msat: u64::max_value(),
1327 path_htlc_minimum_msat,
1328 path_penalty_msat: u64::max_value(),
1329 was_processed: false,
1330 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1331 value_contribution_msat,
1335 #[allow(unused_mut)] // We only use the mut in cfg(test)
1336 let mut should_process = !old_entry.was_processed;
1337 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1339 // In test/fuzzing builds, we do extra checks to make sure the skipping
1340 // of already-seen nodes only happens in cases we expect (see below).
1341 if !should_process { should_process = true; }
1345 let mut hop_use_fee_msat = 0;
1346 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1348 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1349 // will have the same effective-fee
1350 if $src_node_id != our_node_id {
1351 // Note that `u64::max_value` means we'll always fail the
1352 // `old_entry.total_fee_msat > total_fee_msat` check below
1353 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1354 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1357 let channel_usage = ChannelUsage {
1358 amount_msat: amount_to_transfer_over_msat,
1359 inflight_htlc_msat: used_liquidity_msat,
1362 let channel_penalty_msat = scorer.channel_penalty_msat(
1363 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1365 let path_penalty_msat = $next_hops_path_penalty_msat
1366 .saturating_add(channel_penalty_msat);
1367 let new_graph_node = RouteGraphNode {
1368 node_id: $src_node_id,
1369 lowest_fee_to_node: total_fee_msat,
1370 total_cltv_delta: hop_total_cltv_delta,
1371 value_contribution_msat,
1372 path_htlc_minimum_msat,
1374 path_length_to_node,
1377 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1378 // if this way is cheaper than the already known
1379 // (considering the cost to "reach" this channel from the route destination,
1380 // the cost of using this channel,
1381 // and the cost of routing to the source node of this channel).
1382 // Also, consider that htlc_minimum_msat_difference, because we might end up
1383 // paying it. Consider the following exploit:
1384 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1385 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1386 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1387 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1389 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1390 // but it may require additional tracking - we don't want to double-count
1391 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1392 // can't use something that may decrease on future hops.
1393 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1394 .saturating_add(old_entry.path_penalty_msat);
1395 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1396 .saturating_add(path_penalty_msat);
1398 if !old_entry.was_processed && new_cost < old_cost {
1399 targets.push(new_graph_node);
1400 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1401 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1402 old_entry.total_fee_msat = total_fee_msat;
1403 old_entry.node_id = $dest_node_id.clone();
1404 old_entry.candidate = $candidate.clone();
1405 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1406 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1407 old_entry.path_penalty_msat = path_penalty_msat;
1408 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1410 old_entry.value_contribution_msat = value_contribution_msat;
1412 did_add_update_path_to_src_node = true;
1413 } else if old_entry.was_processed && new_cost < old_cost {
1414 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1416 // If we're skipping processing a node which was previously
1417 // processed even though we found another path to it with a
1418 // cheaper fee, check that it was because the second path we
1419 // found (which we are processing now) has a lower value
1420 // contribution due to an HTLC minimum limit.
1422 // e.g. take a graph with two paths from node 1 to node 2, one
1423 // through channel A, and one through channel B. Channel A and
1424 // B are both in the to-process heap, with their scores set by
1425 // a higher htlc_minimum than fee.
1426 // Channel A is processed first, and the channels onwards from
1427 // node 1 are added to the to-process heap. Thereafter, we pop
1428 // Channel B off of the heap, note that it has a much more
1429 // restrictive htlc_maximum_msat, and recalculate the fees for
1430 // all of node 1's channels using the new, reduced, amount.
1432 // This would be bogus - we'd be selecting a higher-fee path
1433 // with a lower htlc_maximum_msat instead of the one we'd
1434 // already decided to use.
1435 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1437 value_contribution_msat + path_penalty_msat <
1438 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1446 did_add_update_path_to_src_node
1450 let default_node_features = default_node_features();
1452 // Find ways (channels with destination) to reach a given node and store them
1453 // in the corresponding data structures (routing graph etc).
1454 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1455 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1456 // This data can later be helpful to optimize routing (pay lower fees).
1457 macro_rules! add_entries_to_cheapest_to_target_node {
1458 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1459 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1460 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1461 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1462 let was_processed = elem.was_processed;
1463 elem.was_processed = true;
1466 // Entries are added to dist in add_entry!() when there is a channel from a node.
1467 // Because there are no channels from payee, it will not have a dist entry at this point.
1468 // If we're processing any other node, it is always be the result of a channel from it.
1469 assert_eq!($node_id, payee_node_id);
1474 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1475 for details in first_channels {
1476 let candidate = CandidateRouteHop::FirstHop { details };
1477 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1478 $next_hops_value_contribution,
1479 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1480 $next_hops_cltv_delta, $next_hops_path_length);
1484 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1487 &default_node_features
1490 if !features.requires_unknown_bits() {
1491 for chan_id in $node.channels.iter() {
1492 let chan = network_channels.get(chan_id).unwrap();
1493 if !chan.features.requires_unknown_bits() {
1494 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1495 if first_hops.is_none() || *source != our_node_id {
1496 if directed_channel.direction().enabled {
1497 let candidate = CandidateRouteHop::PublicHop {
1498 info: directed_channel,
1499 short_channel_id: *chan_id,
1501 add_entry!(candidate, *source, $node_id,
1502 $fee_to_target_msat,
1503 $next_hops_value_contribution,
1504 $next_hops_path_htlc_minimum_msat,
1505 $next_hops_path_penalty_msat,
1506 $next_hops_cltv_delta, $next_hops_path_length);
1517 let mut payment_paths = Vec::<PaymentPath>::new();
1519 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1520 'paths_collection: loop {
1521 // For every new path, start from scratch, except for used_channel_liquidities, which
1522 // helps to avoid reusing previously selected paths in future iterations.
1525 hit_minimum_limit = false;
1527 // If first hop is a private channel and the only way to reach the payee, this is the only
1528 // place where it could be added.
1529 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1530 for details in first_channels {
1531 let candidate = CandidateRouteHop::FirstHop { details };
1532 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1534 log_trace!(logger, "{} direct route to payee via SCID {}",
1535 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1539 // Add the payee as a target, so that the payee-to-payer
1540 // search algorithm knows what to start with.
1541 match network_nodes.get(&payee_node_id) {
1542 // The payee is not in our network graph, so nothing to add here.
1543 // There is still a chance of reaching them via last_hops though,
1544 // so don't yet fail the payment here.
1545 // If not, targets.pop() will not even let us enter the loop in step 2.
1548 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1553 // If a caller provided us with last hops, add them to routing targets. Since this happens
1554 // earlier than general path finding, they will be somewhat prioritized, although currently
1555 // it matters only if the fees are exactly the same.
1556 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1557 let first_hop_in_route = &(route.0)[0];
1558 let have_hop_src_in_graph =
1559 // Only add the hops in this route to our candidate set if either
1560 // we have a direct channel to the first hop or the first hop is
1561 // in the regular network graph.
1562 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1563 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1564 if have_hop_src_in_graph {
1565 // We start building the path from reverse, i.e., from payee
1566 // to the first RouteHintHop in the path.
1567 let hop_iter = route.0.iter().rev();
1568 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1569 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1570 let mut hop_used = true;
1571 let mut aggregate_next_hops_fee_msat: u64 = 0;
1572 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1573 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1574 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1575 let mut aggregate_next_hops_path_length: u8 = 0;
1577 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1578 let source = NodeId::from_pubkey(&hop.src_node_id);
1579 let target = NodeId::from_pubkey(&prev_hop_id);
1580 let candidate = network_channels
1581 .get(&hop.short_channel_id)
1582 .and_then(|channel| channel.as_directed_to(&target))
1583 .map(|(info, _)| CandidateRouteHop::PublicHop {
1585 short_channel_id: hop.short_channel_id,
1587 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1589 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1590 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1591 aggregate_next_hops_path_penalty_msat,
1592 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1593 // If this hop was not used then there is no use checking the preceding
1594 // hops in the RouteHint. We can break by just searching for a direct
1595 // channel between last checked hop and first_hop_targets.
1599 let used_liquidity_msat = used_channel_liquidities
1600 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1601 let channel_usage = ChannelUsage {
1602 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1603 inflight_htlc_msat: used_liquidity_msat,
1604 effective_capacity: candidate.effective_capacity(),
1606 let channel_penalty_msat = scorer.channel_penalty_msat(
1607 hop.short_channel_id, &source, &target, channel_usage
1609 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1610 .saturating_add(channel_penalty_msat);
1612 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1613 .saturating_add(hop.cltv_expiry_delta as u32);
1615 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1618 // Searching for a direct channel between last checked hop and first_hop_targets
1619 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1620 for details in first_channels {
1621 let candidate = CandidateRouteHop::FirstHop { details };
1622 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1623 aggregate_next_hops_fee_msat, path_value_msat,
1624 aggregate_next_hops_path_htlc_minimum_msat,
1625 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1626 aggregate_next_hops_path_length);
1634 // In the next values of the iterator, the aggregate fees already reflects
1635 // the sum of value sent from payer (final_value_msat) and routing fees
1636 // for the last node in the RouteHint. We need to just add the fees to
1637 // route through the current node so that the preceding node (next iteration)
1639 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1640 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1641 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1643 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1644 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1645 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1646 .checked_add(hop_htlc_minimum_msat_inc);
1647 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1649 if idx == route.0.len() - 1 {
1650 // The last hop in this iterator is the first hop in
1651 // overall RouteHint.
1652 // If this hop connects to a node with which we have a direct channel,
1653 // ignore the network graph and, if the last hop was added, add our
1654 // direct channel to the candidate set.
1656 // Note that we *must* check if the last hop was added as `add_entry`
1657 // always assumes that the third argument is a node to which we have a
1659 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1660 for details in first_channels {
1661 let candidate = CandidateRouteHop::FirstHop { details };
1662 add_entry!(candidate, our_node_id,
1663 NodeId::from_pubkey(&hop.src_node_id),
1664 aggregate_next_hops_fee_msat, path_value_msat,
1665 aggregate_next_hops_path_htlc_minimum_msat,
1666 aggregate_next_hops_path_penalty_msat,
1667 aggregate_next_hops_cltv_delta,
1668 aggregate_next_hops_path_length);
1676 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1678 // At this point, targets are filled with the data from first and
1679 // last hops communicated by the caller, and the payment receiver.
1680 let mut found_new_path = false;
1683 // If this loop terminates due the exhaustion of targets, two situations are possible:
1684 // - not enough outgoing liquidity:
1685 // 0 < already_collected_value_msat < final_value_msat
1686 // - enough outgoing liquidity:
1687 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1688 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1689 // paths_collection will be stopped because found_new_path==false.
1690 // This is not necessarily a routing failure.
1691 '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() {
1693 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1694 // traversing the graph and arrange the path out of what we found.
1695 if node_id == our_node_id {
1696 let mut new_entry = dist.remove(&our_node_id).unwrap();
1697 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1700 let mut features_set = false;
1701 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1702 for details in first_channels {
1703 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1704 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1705 features_set = true;
1711 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1712 if let Some(node_info) = node.announcement_info.as_ref() {
1713 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1715 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1718 // We can fill in features for everything except hops which were
1719 // provided via the invoice we're paying. We could guess based on the
1720 // recipient's features but for now we simply avoid guessing at all.
1724 // Means we succesfully traversed from the payer to the payee, now
1725 // save this path for the payment route. Also, update the liquidity
1726 // remaining on the used hops, so that we take them into account
1727 // while looking for more paths.
1728 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1732 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1733 Some(payment_hop) => payment_hop,
1734 // We can't arrive at None because, if we ever add an entry to targets,
1735 // we also fill in the entry in dist (see add_entry!).
1736 None => unreachable!(),
1738 // We "propagate" the fees one hop backward (topologically) here,
1739 // so that fees paid for a HTLC forwarding on the current channel are
1740 // associated with the previous channel (where they will be subtracted).
1741 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1742 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1744 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1745 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1747 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1748 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1750 let mut payment_path = PaymentPath {hops: ordered_hops};
1752 // We could have possibly constructed a slightly inconsistent path: since we reduce
1753 // value being transferred along the way, we could have violated htlc_minimum_msat
1754 // on some channels we already passed (assuming dest->source direction). Here, we
1755 // recompute the fees again, so that if that's the case, we match the currently
1756 // underpaid htlc_minimum_msat with fees.
1757 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1758 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1759 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1761 // Since a path allows to transfer as much value as
1762 // the smallest channel it has ("bottleneck"), we should recompute
1763 // the fees so sender HTLC don't overpay fees when traversing
1764 // larger channels than the bottleneck. This may happen because
1765 // when we were selecting those channels we were not aware how much value
1766 // this path will transfer, and the relative fee for them
1767 // might have been computed considering a larger value.
1768 // Remember that we used these channels so that we don't rely
1769 // on the same liquidity in future paths.
1770 let mut prevented_redundant_path_selection = false;
1771 let prev_hop_iter = core::iter::once(&our_node_id)
1772 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1773 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1774 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1775 let used_liquidity_msat = used_channel_liquidities
1776 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1777 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1778 .or_insert(spent_on_hop_msat);
1779 let hop_capacity = hop.candidate.effective_capacity();
1780 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1781 if *used_liquidity_msat == hop_max_msat {
1782 // If this path used all of this channel's available liquidity, we know
1783 // this path will not be selected again in the next loop iteration.
1784 prevented_redundant_path_selection = true;
1786 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1788 if !prevented_redundant_path_selection {
1789 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1790 // we'll probably end up picking the same path again on the next iteration.
1791 // Decrease the available liquidity of a hop in the middle of the path.
1792 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1793 let exhausted = u64::max_value();
1794 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1795 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1796 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1799 // Track the total amount all our collected paths allow to send so that we know
1800 // when to stop looking for more paths
1801 already_collected_value_msat += value_contribution_msat;
1803 payment_paths.push(payment_path);
1804 found_new_path = true;
1805 break 'path_construction;
1808 // If we found a path back to the payee, we shouldn't try to process it again. This is
1809 // the equivalent of the `elem.was_processed` check in
1810 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1811 if node_id == payee_node_id { continue 'path_construction; }
1813 // Otherwise, since the current target node is not us,
1814 // keep "unrolling" the payment graph from payee to payer by
1815 // finding a way to reach the current target from the payer side.
1816 match network_nodes.get(&node_id) {
1819 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1820 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1821 total_cltv_delta, path_length_to_node);
1827 if !found_new_path && channel_saturation_pow_half != 0 {
1828 channel_saturation_pow_half = 0;
1829 continue 'paths_collection;
1831 // If we don't support MPP, no use trying to gather more value ever.
1832 break 'paths_collection;
1836 // Stop either when the recommended value is reached or if no new path was found in this
1838 // In the latter case, making another path finding attempt won't help,
1839 // because we deterministically terminated the search due to low liquidity.
1840 if !found_new_path && channel_saturation_pow_half != 0 {
1841 channel_saturation_pow_half = 0;
1842 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1843 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1844 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1845 break 'paths_collection;
1846 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1847 // Further, if this was our first walk of the graph, and we weren't limited by an
1848 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1849 // limited by an htlc_minimum_msat value, find another path with a higher value,
1850 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1851 // still keeping a lower total fee than this path.
1852 if !hit_minimum_limit {
1853 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1854 break 'paths_collection;
1856 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1857 path_value_msat = recommended_value_msat;
1862 if payment_paths.len() == 0 {
1863 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1866 if already_collected_value_msat < final_value_msat {
1867 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1871 let mut selected_route = payment_paths;
1873 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1874 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1876 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1877 // the value they contribute towards the payment amount.
1878 // We sort in descending order as we will remove from the front in `retain`, next.
1879 selected_route.sort_unstable_by(|a, b|
1880 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1881 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1884 // We should make sure that at least 1 path left.
1885 let mut paths_left = selected_route.len();
1886 selected_route.retain(|path| {
1887 if paths_left == 1 {
1890 let path_value_msat = path.get_value_msat();
1891 if path_value_msat <= overpaid_value_msat {
1892 overpaid_value_msat -= path_value_msat;
1898 debug_assert!(selected_route.len() > 0);
1900 if overpaid_value_msat != 0 {
1902 // Now, subtract the remaining overpaid value from the most-expensive path.
1903 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1904 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1905 selected_route.sort_unstable_by(|a, b| {
1906 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1907 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
1908 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
1910 let expensive_payment_path = selected_route.first_mut().unwrap();
1912 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
1913 // can't go negative.
1914 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1915 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1919 // Sort by the path itself and combine redundant paths.
1920 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
1921 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
1923 selected_route.sort_unstable_by_key(|path| {
1924 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
1925 debug_assert!(path.hops.len() <= key.len());
1926 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
1931 for idx in 0..(selected_route.len() - 1) {
1932 if idx + 1 >= selected_route.len() { break; }
1933 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
1934 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
1935 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
1936 selected_route[idx].update_value_and_recompute_fees(new_value);
1937 selected_route.remove(idx + 1);
1941 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1942 for payment_path in selected_route {
1943 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1945 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)})?,
1946 node_features: node_features.clone(),
1947 short_channel_id: payment_hop.candidate.short_channel_id(),
1948 channel_features: payment_hop.candidate.features(),
1949 fee_msat: payment_hop.fee_msat,
1950 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1952 }).collect::<Vec<_>>();
1953 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1954 // applicable for the previous hop.
1955 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1956 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1958 selected_paths.push(path);
1960 // Make sure we would never create a route with more paths than we allow.
1961 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
1963 if let Some(features) = &payment_params.features {
1964 for path in selected_paths.iter_mut() {
1965 if let Ok(route_hop) = path.last_mut().unwrap() {
1966 route_hop.node_features = features.to_context();
1972 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1973 payment_params: Some(payment_params.clone()),
1975 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1979 // When an adversarial intermediary node observes a payment, it may be able to infer its
1980 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
1981 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
1982 // payment path by adding a randomized 'shadow route' offset to the final hop.
1983 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
1984 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
1986 let network_channels = network_graph.channels();
1987 let network_nodes = network_graph.nodes();
1989 for path in route.paths.iter_mut() {
1990 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
1992 // Remember the last three nodes of the random walk and avoid looping back on them.
1993 // Init with the last three nodes from the actual path, if possible.
1994 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.last().unwrap().pubkey),
1995 NodeId::from_pubkey(&path.get(path.len().saturating_sub(2)).unwrap().pubkey),
1996 NodeId::from_pubkey(&path.get(path.len().saturating_sub(3)).unwrap().pubkey)];
1998 // Choose the last publicly known node as the starting point for the random walk.
1999 let mut cur_hop: Option<NodeId> = None;
2000 let mut path_nonce = [0u8; 12];
2001 if let Some(starting_hop) = path.iter().rev()
2002 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2003 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2004 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2007 // Init PRNG with the path-dependant nonce, which is static for private paths.
2008 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2009 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2011 // Pick a random path length in [1 .. 3]
2012 prng.process_in_place(&mut random_path_bytes);
2013 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2015 for random_hop in 0..random_walk_length {
2016 // If we don't find a suitable offset in the public network graph, we default to
2017 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2018 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2020 if let Some(cur_node_id) = cur_hop {
2021 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2022 // Randomly choose the next unvisited hop.
2023 prng.process_in_place(&mut random_path_bytes);
2024 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2025 .checked_rem(cur_node.channels.len())
2026 .and_then(|index| cur_node.channels.get(index))
2027 .and_then(|id| network_channels.get(id)) {
2028 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2029 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2030 nodes_to_avoid[random_hop] = *next_id;
2031 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2032 cur_hop = Some(*next_id);
2039 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2040 .checked_add(random_hop_offset)
2041 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2044 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2045 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2046 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2048 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2049 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2050 let path_total_cltv_expiry_delta: u32 = path.iter().map(|h| h.cltv_expiry_delta).sum();
2051 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2052 max_path_offset = cmp::max(
2053 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2054 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2055 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2057 // Add 'shadow' CLTV offset to the final hop
2058 if let Some(last_hop) = path.last_mut() {
2059 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2060 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2065 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2066 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2068 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2069 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2070 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2071 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2072 ) -> Result<Route, LightningError>
2073 where L::Target: Logger, GL::Target: Logger {
2074 let graph_lock = network_graph.read_only();
2075 let mut route = build_route_from_hops_internal(
2076 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2077 route_params.final_value_msat, route_params.payment_params.final_cltv_expiry_delta,
2078 logger, random_seed_bytes)?;
2079 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2083 fn build_route_from_hops_internal<L: Deref>(
2084 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2085 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
2086 logger: L, random_seed_bytes: &[u8; 32]
2087 ) -> Result<Route, LightningError> where L::Target: Logger {
2090 our_node_id: NodeId,
2091 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2094 impl Score for HopScorer {
2095 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2096 _usage: ChannelUsage) -> u64
2098 let mut cur_id = self.our_node_id;
2099 for i in 0..self.hop_ids.len() {
2100 if let Some(next_id) = self.hop_ids[i] {
2101 if cur_id == *source && next_id == *target {
2112 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2114 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
2116 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
2118 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
2121 impl<'a> Writeable for HopScorer {
2123 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2128 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2129 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2132 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2133 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2134 for i in 0..hops.len() {
2135 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2138 let scorer = HopScorer { our_node_id, hop_ids };
2140 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2141 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
2146 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2147 use crate::routing::utxo::UtxoResult;
2148 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2149 PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2150 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2151 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
2152 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2153 use crate::chain::transaction::OutPoint;
2154 use crate::chain::keysinterface::EntropySource;
2155 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2156 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2157 use crate::ln::channelmanager;
2158 use crate::util::config::UserConfig;
2159 use crate::util::test_utils as ln_test_utils;
2160 use crate::util::chacha20::ChaCha20;
2162 use crate::util::ser::{Writeable, Writer};
2164 use bitcoin::hashes::Hash;
2165 use bitcoin::network::constants::Network;
2166 use bitcoin::blockdata::constants::genesis_block;
2167 use bitcoin::blockdata::script::Builder;
2168 use bitcoin::blockdata::opcodes;
2169 use bitcoin::blockdata::transaction::TxOut;
2173 use bitcoin::secp256k1::{PublicKey,SecretKey};
2174 use bitcoin::secp256k1::Secp256k1;
2176 use crate::prelude::*;
2177 use crate::sync::Arc;
2179 use core::convert::TryInto;
2181 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2182 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2183 channelmanager::ChannelDetails {
2184 channel_id: [0; 32],
2185 counterparty: channelmanager::ChannelCounterparty {
2188 unspendable_punishment_reserve: 0,
2189 forwarding_info: None,
2190 outbound_htlc_minimum_msat: None,
2191 outbound_htlc_maximum_msat: None,
2193 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2196 outbound_scid_alias: None,
2197 inbound_scid_alias: None,
2198 channel_value_satoshis: 0,
2201 outbound_capacity_msat,
2202 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2203 inbound_capacity_msat: 42,
2204 unspendable_punishment_reserve: None,
2205 confirmations_required: None,
2206 confirmations: None,
2207 force_close_spend_delay: None,
2208 is_outbound: true, is_channel_ready: true,
2209 is_usable: true, is_public: true,
2210 inbound_htlc_minimum_msat: None,
2211 inbound_htlc_maximum_msat: None,
2217 fn simple_route_test() {
2218 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2219 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2220 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2221 let scorer = ln_test_utils::TestScorer::new();
2222 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2223 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2225 // Simple route to 2 via 1
2227 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) {
2228 assert_eq!(err, "Cannot send a payment of 0 msat");
2229 } else { panic!(); }
2231 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2232 assert_eq!(route.paths[0].len(), 2);
2234 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2235 assert_eq!(route.paths[0][0].short_channel_id, 2);
2236 assert_eq!(route.paths[0][0].fee_msat, 100);
2237 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2238 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2239 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2241 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2242 assert_eq!(route.paths[0][1].short_channel_id, 4);
2243 assert_eq!(route.paths[0][1].fee_msat, 100);
2244 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2245 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2246 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2250 fn invalid_first_hop_test() {
2251 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2252 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2253 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2254 let scorer = ln_test_utils::TestScorer::new();
2255 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2256 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2258 // Simple route to 2 via 1
2260 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2262 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2263 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) {
2264 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2265 } else { panic!(); }
2267 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2268 assert_eq!(route.paths[0].len(), 2);
2272 fn htlc_minimum_test() {
2273 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2274 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2275 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2276 let scorer = ln_test_utils::TestScorer::new();
2277 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2278 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2280 // Simple route to 2 via 1
2282 // Disable other paths
2283 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2285 short_channel_id: 12,
2287 flags: 2, // to disable
2288 cltv_expiry_delta: 0,
2289 htlc_minimum_msat: 0,
2290 htlc_maximum_msat: MAX_VALUE_MSAT,
2292 fee_proportional_millionths: 0,
2293 excess_data: Vec::new()
2295 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2297 short_channel_id: 3,
2299 flags: 2, // to disable
2300 cltv_expiry_delta: 0,
2301 htlc_minimum_msat: 0,
2302 htlc_maximum_msat: MAX_VALUE_MSAT,
2304 fee_proportional_millionths: 0,
2305 excess_data: Vec::new()
2307 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2309 short_channel_id: 13,
2311 flags: 2, // to disable
2312 cltv_expiry_delta: 0,
2313 htlc_minimum_msat: 0,
2314 htlc_maximum_msat: MAX_VALUE_MSAT,
2316 fee_proportional_millionths: 0,
2317 excess_data: Vec::new()
2319 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2321 short_channel_id: 6,
2323 flags: 2, // to disable
2324 cltv_expiry_delta: 0,
2325 htlc_minimum_msat: 0,
2326 htlc_maximum_msat: MAX_VALUE_MSAT,
2328 fee_proportional_millionths: 0,
2329 excess_data: Vec::new()
2331 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2333 short_channel_id: 7,
2335 flags: 2, // to disable
2336 cltv_expiry_delta: 0,
2337 htlc_minimum_msat: 0,
2338 htlc_maximum_msat: MAX_VALUE_MSAT,
2340 fee_proportional_millionths: 0,
2341 excess_data: Vec::new()
2344 // Check against amount_to_transfer_over_msat.
2345 // Set minimal HTLC of 200_000_000 msat.
2346 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2348 short_channel_id: 2,
2351 cltv_expiry_delta: 0,
2352 htlc_minimum_msat: 200_000_000,
2353 htlc_maximum_msat: MAX_VALUE_MSAT,
2355 fee_proportional_millionths: 0,
2356 excess_data: Vec::new()
2359 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2361 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2363 short_channel_id: 4,
2366 cltv_expiry_delta: 0,
2367 htlc_minimum_msat: 0,
2368 htlc_maximum_msat: 199_999_999,
2370 fee_proportional_millionths: 0,
2371 excess_data: Vec::new()
2374 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2375 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) {
2376 assert_eq!(err, "Failed to find a path to the given destination");
2377 } else { panic!(); }
2379 // Lift the restriction on the first hop.
2380 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2382 short_channel_id: 2,
2385 cltv_expiry_delta: 0,
2386 htlc_minimum_msat: 0,
2387 htlc_maximum_msat: MAX_VALUE_MSAT,
2389 fee_proportional_millionths: 0,
2390 excess_data: Vec::new()
2393 // A payment above the minimum should pass
2394 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();
2395 assert_eq!(route.paths[0].len(), 2);
2399 fn htlc_minimum_overpay_test() {
2400 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2401 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2402 let config = UserConfig::default();
2403 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
2404 let scorer = ln_test_utils::TestScorer::new();
2405 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2406 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2408 // A route to node#2 via two paths.
2409 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2410 // Thus, they can't send 60 without overpaying.
2411 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2412 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2413 short_channel_id: 2,
2416 cltv_expiry_delta: 0,
2417 htlc_minimum_msat: 35_000,
2418 htlc_maximum_msat: 40_000,
2420 fee_proportional_millionths: 0,
2421 excess_data: Vec::new()
2423 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2424 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2425 short_channel_id: 12,
2428 cltv_expiry_delta: 0,
2429 htlc_minimum_msat: 35_000,
2430 htlc_maximum_msat: 40_000,
2432 fee_proportional_millionths: 0,
2433 excess_data: Vec::new()
2437 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2438 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2439 short_channel_id: 13,
2442 cltv_expiry_delta: 0,
2443 htlc_minimum_msat: 0,
2444 htlc_maximum_msat: MAX_VALUE_MSAT,
2446 fee_proportional_millionths: 0,
2447 excess_data: Vec::new()
2449 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2451 short_channel_id: 4,
2454 cltv_expiry_delta: 0,
2455 htlc_minimum_msat: 0,
2456 htlc_maximum_msat: MAX_VALUE_MSAT,
2458 fee_proportional_millionths: 0,
2459 excess_data: Vec::new()
2462 // Disable other paths
2463 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2465 short_channel_id: 1,
2467 flags: 2, // to disable
2468 cltv_expiry_delta: 0,
2469 htlc_minimum_msat: 0,
2470 htlc_maximum_msat: MAX_VALUE_MSAT,
2472 fee_proportional_millionths: 0,
2473 excess_data: Vec::new()
2476 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2477 // Overpay fees to hit htlc_minimum_msat.
2478 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2479 // TODO: this could be better balanced to overpay 10k and not 15k.
2480 assert_eq!(overpaid_fees, 15_000);
2482 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2483 // while taking even more fee to match htlc_minimum_msat.
2484 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2485 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2486 short_channel_id: 12,
2489 cltv_expiry_delta: 0,
2490 htlc_minimum_msat: 65_000,
2491 htlc_maximum_msat: 80_000,
2493 fee_proportional_millionths: 0,
2494 excess_data: Vec::new()
2496 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2497 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2498 short_channel_id: 2,
2501 cltv_expiry_delta: 0,
2502 htlc_minimum_msat: 0,
2503 htlc_maximum_msat: MAX_VALUE_MSAT,
2505 fee_proportional_millionths: 0,
2506 excess_data: Vec::new()
2508 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2510 short_channel_id: 4,
2513 cltv_expiry_delta: 0,
2514 htlc_minimum_msat: 0,
2515 htlc_maximum_msat: MAX_VALUE_MSAT,
2517 fee_proportional_millionths: 100_000,
2518 excess_data: Vec::new()
2521 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2522 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2523 assert_eq!(route.paths.len(), 1);
2524 assert_eq!(route.paths[0][0].short_channel_id, 12);
2525 let fees = route.paths[0][0].fee_msat;
2526 assert_eq!(fees, 5_000);
2528 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2529 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2530 // the other channel.
2531 assert_eq!(route.paths.len(), 1);
2532 assert_eq!(route.paths[0][0].short_channel_id, 2);
2533 let fees = route.paths[0][0].fee_msat;
2534 assert_eq!(fees, 5_000);
2538 fn disable_channels_test() {
2539 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2540 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2541 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2542 let scorer = ln_test_utils::TestScorer::new();
2543 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2544 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2546 // // Disable channels 4 and 12 by flags=2
2547 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2548 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2549 short_channel_id: 4,
2551 flags: 2, // to disable
2552 cltv_expiry_delta: 0,
2553 htlc_minimum_msat: 0,
2554 htlc_maximum_msat: MAX_VALUE_MSAT,
2556 fee_proportional_millionths: 0,
2557 excess_data: Vec::new()
2559 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2560 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2561 short_channel_id: 12,
2563 flags: 2, // to disable
2564 cltv_expiry_delta: 0,
2565 htlc_minimum_msat: 0,
2566 htlc_maximum_msat: MAX_VALUE_MSAT,
2568 fee_proportional_millionths: 0,
2569 excess_data: Vec::new()
2572 // If all the channels require some features we don't understand, route should fail
2573 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) {
2574 assert_eq!(err, "Failed to find a path to the given destination");
2575 } else { panic!(); }
2577 // If we specify a channel to node7, that overrides our local channel view and that gets used
2578 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2579 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();
2580 assert_eq!(route.paths[0].len(), 2);
2582 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2583 assert_eq!(route.paths[0][0].short_channel_id, 42);
2584 assert_eq!(route.paths[0][0].fee_msat, 200);
2585 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2586 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2587 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2589 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2590 assert_eq!(route.paths[0][1].short_channel_id, 13);
2591 assert_eq!(route.paths[0][1].fee_msat, 100);
2592 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2593 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2594 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2598 fn disable_node_test() {
2599 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2600 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2601 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2602 let scorer = ln_test_utils::TestScorer::new();
2603 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2604 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2606 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2607 let mut unknown_features = NodeFeatures::empty();
2608 unknown_features.set_unknown_feature_required();
2609 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2610 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2611 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2613 // If all nodes require some features we don't understand, route should fail
2614 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) {
2615 assert_eq!(err, "Failed to find a path to the given destination");
2616 } else { panic!(); }
2618 // If we specify a channel to node7, that overrides our local channel view and that gets used
2619 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2620 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();
2621 assert_eq!(route.paths[0].len(), 2);
2623 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2624 assert_eq!(route.paths[0][0].short_channel_id, 42);
2625 assert_eq!(route.paths[0][0].fee_msat, 200);
2626 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2627 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2628 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2630 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2631 assert_eq!(route.paths[0][1].short_channel_id, 13);
2632 assert_eq!(route.paths[0][1].fee_msat, 100);
2633 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2634 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2635 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2637 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2638 // naively) assume that the user checked the feature bits on the invoice, which override
2639 // the node_announcement.
2643 fn our_chans_test() {
2644 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2645 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2646 let scorer = ln_test_utils::TestScorer::new();
2647 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2648 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2650 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2651 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
2652 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2653 assert_eq!(route.paths[0].len(), 3);
2655 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2656 assert_eq!(route.paths[0][0].short_channel_id, 2);
2657 assert_eq!(route.paths[0][0].fee_msat, 200);
2658 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2659 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2660 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2662 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2663 assert_eq!(route.paths[0][1].short_channel_id, 4);
2664 assert_eq!(route.paths[0][1].fee_msat, 100);
2665 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2666 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2667 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2669 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2670 assert_eq!(route.paths[0][2].short_channel_id, 3);
2671 assert_eq!(route.paths[0][2].fee_msat, 100);
2672 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2673 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2674 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2676 // If we specify a channel to node7, that overrides our local channel view and that gets used
2677 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2678 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2679 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();
2680 assert_eq!(route.paths[0].len(), 2);
2682 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2683 assert_eq!(route.paths[0][0].short_channel_id, 42);
2684 assert_eq!(route.paths[0][0].fee_msat, 200);
2685 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2686 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2687 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2689 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2690 assert_eq!(route.paths[0][1].short_channel_id, 13);
2691 assert_eq!(route.paths[0][1].fee_msat, 100);
2692 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2693 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2694 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2697 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2698 let zero_fees = RoutingFees {
2700 proportional_millionths: 0,
2702 vec![RouteHint(vec![RouteHintHop {
2703 src_node_id: nodes[3],
2704 short_channel_id: 8,
2706 cltv_expiry_delta: (8 << 4) | 1,
2707 htlc_minimum_msat: None,
2708 htlc_maximum_msat: None,
2710 ]), RouteHint(vec![RouteHintHop {
2711 src_node_id: nodes[4],
2712 short_channel_id: 9,
2715 proportional_millionths: 0,
2717 cltv_expiry_delta: (9 << 4) | 1,
2718 htlc_minimum_msat: None,
2719 htlc_maximum_msat: None,
2720 }]), RouteHint(vec![RouteHintHop {
2721 src_node_id: nodes[5],
2722 short_channel_id: 10,
2724 cltv_expiry_delta: (10 << 4) | 1,
2725 htlc_minimum_msat: None,
2726 htlc_maximum_msat: None,
2730 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2731 let zero_fees = RoutingFees {
2733 proportional_millionths: 0,
2735 vec![RouteHint(vec![RouteHintHop {
2736 src_node_id: nodes[2],
2737 short_channel_id: 5,
2740 proportional_millionths: 0,
2742 cltv_expiry_delta: (5 << 4) | 1,
2743 htlc_minimum_msat: None,
2744 htlc_maximum_msat: None,
2746 src_node_id: nodes[3],
2747 short_channel_id: 8,
2749 cltv_expiry_delta: (8 << 4) | 1,
2750 htlc_minimum_msat: None,
2751 htlc_maximum_msat: None,
2753 ]), RouteHint(vec![RouteHintHop {
2754 src_node_id: nodes[4],
2755 short_channel_id: 9,
2758 proportional_millionths: 0,
2760 cltv_expiry_delta: (9 << 4) | 1,
2761 htlc_minimum_msat: None,
2762 htlc_maximum_msat: None,
2763 }]), RouteHint(vec![RouteHintHop {
2764 src_node_id: nodes[5],
2765 short_channel_id: 10,
2767 cltv_expiry_delta: (10 << 4) | 1,
2768 htlc_minimum_msat: None,
2769 htlc_maximum_msat: None,
2774 fn partial_route_hint_test() {
2775 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2776 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2777 let scorer = ln_test_utils::TestScorer::new();
2778 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2779 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2781 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2782 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2783 // RouteHint may be partially used by the algo to build the best path.
2785 // First check that last hop can't have its source as the payee.
2786 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2787 src_node_id: nodes[6],
2788 short_channel_id: 8,
2791 proportional_millionths: 0,
2793 cltv_expiry_delta: (8 << 4) | 1,
2794 htlc_minimum_msat: None,
2795 htlc_maximum_msat: None,
2798 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2799 invalid_last_hops.push(invalid_last_hop);
2801 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops);
2802 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) {
2803 assert_eq!(err, "Route hint cannot have the payee as the source.");
2804 } else { panic!(); }
2807 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes));
2808 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2809 assert_eq!(route.paths[0].len(), 5);
2811 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2812 assert_eq!(route.paths[0][0].short_channel_id, 2);
2813 assert_eq!(route.paths[0][0].fee_msat, 100);
2814 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2815 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2816 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2818 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2819 assert_eq!(route.paths[0][1].short_channel_id, 4);
2820 assert_eq!(route.paths[0][1].fee_msat, 0);
2821 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2822 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2823 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2825 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2826 assert_eq!(route.paths[0][2].short_channel_id, 6);
2827 assert_eq!(route.paths[0][2].fee_msat, 0);
2828 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2829 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2830 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2832 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2833 assert_eq!(route.paths[0][3].short_channel_id, 11);
2834 assert_eq!(route.paths[0][3].fee_msat, 0);
2835 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2836 // If we have a peer in the node map, we'll use their features here since we don't have
2837 // a way of figuring out their features from the invoice:
2838 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2839 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2841 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2842 assert_eq!(route.paths[0][4].short_channel_id, 8);
2843 assert_eq!(route.paths[0][4].fee_msat, 100);
2844 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2845 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2846 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2849 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2850 let zero_fees = RoutingFees {
2852 proportional_millionths: 0,
2854 vec![RouteHint(vec![RouteHintHop {
2855 src_node_id: nodes[3],
2856 short_channel_id: 8,
2858 cltv_expiry_delta: (8 << 4) | 1,
2859 htlc_minimum_msat: None,
2860 htlc_maximum_msat: None,
2861 }]), RouteHint(vec![
2863 ]), RouteHint(vec![RouteHintHop {
2864 src_node_id: nodes[5],
2865 short_channel_id: 10,
2867 cltv_expiry_delta: (10 << 4) | 1,
2868 htlc_minimum_msat: None,
2869 htlc_maximum_msat: None,
2874 fn ignores_empty_last_hops_test() {
2875 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2876 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2877 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes));
2878 let scorer = ln_test_utils::TestScorer::new();
2879 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2880 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2882 // Test handling of an empty RouteHint passed in Invoice.
2884 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2885 assert_eq!(route.paths[0].len(), 5);
2887 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2888 assert_eq!(route.paths[0][0].short_channel_id, 2);
2889 assert_eq!(route.paths[0][0].fee_msat, 100);
2890 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2891 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2892 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2894 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2895 assert_eq!(route.paths[0][1].short_channel_id, 4);
2896 assert_eq!(route.paths[0][1].fee_msat, 0);
2897 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2898 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2899 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2901 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2902 assert_eq!(route.paths[0][2].short_channel_id, 6);
2903 assert_eq!(route.paths[0][2].fee_msat, 0);
2904 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2905 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2906 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2908 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2909 assert_eq!(route.paths[0][3].short_channel_id, 11);
2910 assert_eq!(route.paths[0][3].fee_msat, 0);
2911 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2912 // If we have a peer in the node map, we'll use their features here since we don't have
2913 // a way of figuring out their features from the invoice:
2914 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2915 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2917 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2918 assert_eq!(route.paths[0][4].short_channel_id, 8);
2919 assert_eq!(route.paths[0][4].fee_msat, 100);
2920 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2921 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2922 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2925 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2927 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2928 let zero_fees = RoutingFees {
2930 proportional_millionths: 0,
2932 vec![RouteHint(vec![RouteHintHop {
2933 src_node_id: hint_hops[0],
2934 short_channel_id: 0xff00,
2937 proportional_millionths: 0,
2939 cltv_expiry_delta: (5 << 4) | 1,
2940 htlc_minimum_msat: None,
2941 htlc_maximum_msat: None,
2943 src_node_id: hint_hops[1],
2944 short_channel_id: 0xff01,
2946 cltv_expiry_delta: (8 << 4) | 1,
2947 htlc_minimum_msat: None,
2948 htlc_maximum_msat: None,
2953 fn multi_hint_last_hops_test() {
2954 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2955 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2956 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2957 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
2958 let scorer = ln_test_utils::TestScorer::new();
2959 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2960 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2961 // Test through channels 2, 3, 0xff00, 0xff01.
2962 // Test shows that multiple hop hints are considered.
2964 // Disabling channels 6 & 7 by flags=2
2965 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2967 short_channel_id: 6,
2969 flags: 2, // to disable
2970 cltv_expiry_delta: 0,
2971 htlc_minimum_msat: 0,
2972 htlc_maximum_msat: MAX_VALUE_MSAT,
2974 fee_proportional_millionths: 0,
2975 excess_data: Vec::new()
2977 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2979 short_channel_id: 7,
2981 flags: 2, // to disable
2982 cltv_expiry_delta: 0,
2983 htlc_minimum_msat: 0,
2984 htlc_maximum_msat: MAX_VALUE_MSAT,
2986 fee_proportional_millionths: 0,
2987 excess_data: Vec::new()
2990 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2991 assert_eq!(route.paths[0].len(), 4);
2993 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2994 assert_eq!(route.paths[0][0].short_channel_id, 2);
2995 assert_eq!(route.paths[0][0].fee_msat, 200);
2996 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2997 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2998 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3000 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3001 assert_eq!(route.paths[0][1].short_channel_id, 4);
3002 assert_eq!(route.paths[0][1].fee_msat, 100);
3003 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3004 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3005 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3007 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
3008 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3009 assert_eq!(route.paths[0][2].fee_msat, 0);
3010 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3011 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
3012 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3014 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3015 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3016 assert_eq!(route.paths[0][3].fee_msat, 100);
3017 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3018 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3019 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3023 fn private_multi_hint_last_hops_test() {
3024 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3025 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3027 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3028 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3030 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3031 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3032 let scorer = ln_test_utils::TestScorer::new();
3033 // Test through channels 2, 3, 0xff00, 0xff01.
3034 // Test shows that multiple hop hints are considered.
3036 // Disabling channels 6 & 7 by flags=2
3037 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3039 short_channel_id: 6,
3041 flags: 2, // to disable
3042 cltv_expiry_delta: 0,
3043 htlc_minimum_msat: 0,
3044 htlc_maximum_msat: MAX_VALUE_MSAT,
3046 fee_proportional_millionths: 0,
3047 excess_data: Vec::new()
3049 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3050 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3051 short_channel_id: 7,
3053 flags: 2, // to disable
3054 cltv_expiry_delta: 0,
3055 htlc_minimum_msat: 0,
3056 htlc_maximum_msat: MAX_VALUE_MSAT,
3058 fee_proportional_millionths: 0,
3059 excess_data: Vec::new()
3062 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3063 assert_eq!(route.paths[0].len(), 4);
3065 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3066 assert_eq!(route.paths[0][0].short_channel_id, 2);
3067 assert_eq!(route.paths[0][0].fee_msat, 200);
3068 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
3069 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3070 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3072 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3073 assert_eq!(route.paths[0][1].short_channel_id, 4);
3074 assert_eq!(route.paths[0][1].fee_msat, 100);
3075 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
3076 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3077 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3079 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
3080 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
3081 assert_eq!(route.paths[0][2].fee_msat, 0);
3082 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
3083 assert_eq!(route.paths[0][2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3084 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3086 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3087 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
3088 assert_eq!(route.paths[0][3].fee_msat, 100);
3089 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3090 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3091 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3094 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3095 let zero_fees = RoutingFees {
3097 proportional_millionths: 0,
3099 vec![RouteHint(vec![RouteHintHop {
3100 src_node_id: nodes[4],
3101 short_channel_id: 11,
3103 cltv_expiry_delta: (11 << 4) | 1,
3104 htlc_minimum_msat: None,
3105 htlc_maximum_msat: None,
3107 src_node_id: nodes[3],
3108 short_channel_id: 8,
3110 cltv_expiry_delta: (8 << 4) | 1,
3111 htlc_minimum_msat: None,
3112 htlc_maximum_msat: None,
3113 }]), RouteHint(vec![RouteHintHop {
3114 src_node_id: nodes[4],
3115 short_channel_id: 9,
3118 proportional_millionths: 0,
3120 cltv_expiry_delta: (9 << 4) | 1,
3121 htlc_minimum_msat: None,
3122 htlc_maximum_msat: None,
3123 }]), RouteHint(vec![RouteHintHop {
3124 src_node_id: nodes[5],
3125 short_channel_id: 10,
3127 cltv_expiry_delta: (10 << 4) | 1,
3128 htlc_minimum_msat: None,
3129 htlc_maximum_msat: None,
3134 fn last_hops_with_public_channel_test() {
3135 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3136 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3137 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes));
3138 let scorer = ln_test_utils::TestScorer::new();
3139 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3140 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3141 // This test shows that public routes can be present in the invoice
3142 // which would be handled in the same manner.
3144 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3145 assert_eq!(route.paths[0].len(), 5);
3147 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3148 assert_eq!(route.paths[0][0].short_channel_id, 2);
3149 assert_eq!(route.paths[0][0].fee_msat, 100);
3150 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3151 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3152 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3154 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3155 assert_eq!(route.paths[0][1].short_channel_id, 4);
3156 assert_eq!(route.paths[0][1].fee_msat, 0);
3157 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3158 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3159 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3161 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3162 assert_eq!(route.paths[0][2].short_channel_id, 6);
3163 assert_eq!(route.paths[0][2].fee_msat, 0);
3164 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3165 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3166 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3168 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3169 assert_eq!(route.paths[0][3].short_channel_id, 11);
3170 assert_eq!(route.paths[0][3].fee_msat, 0);
3171 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3172 // If we have a peer in the node map, we'll use their features here since we don't have
3173 // a way of figuring out their features from the invoice:
3174 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3175 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3177 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3178 assert_eq!(route.paths[0][4].short_channel_id, 8);
3179 assert_eq!(route.paths[0][4].fee_msat, 100);
3180 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3181 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3182 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3186 fn our_chans_last_hop_connect_test() {
3187 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3188 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3189 let scorer = ln_test_utils::TestScorer::new();
3190 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3191 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3193 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3194 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3195 let mut last_hops = last_hops(&nodes);
3196 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3197 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();
3198 assert_eq!(route.paths[0].len(), 2);
3200 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
3201 assert_eq!(route.paths[0][0].short_channel_id, 42);
3202 assert_eq!(route.paths[0][0].fee_msat, 0);
3203 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3204 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
3205 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3207 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
3208 assert_eq!(route.paths[0][1].short_channel_id, 8);
3209 assert_eq!(route.paths[0][1].fee_msat, 100);
3210 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3211 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3212 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3214 last_hops[0].0[0].fees.base_msat = 1000;
3216 // Revert to via 6 as the fee on 8 goes up
3217 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops);
3218 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3219 assert_eq!(route.paths[0].len(), 4);
3221 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3222 assert_eq!(route.paths[0][0].short_channel_id, 2);
3223 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
3224 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3225 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3226 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3228 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3229 assert_eq!(route.paths[0][1].short_channel_id, 4);
3230 assert_eq!(route.paths[0][1].fee_msat, 100);
3231 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3232 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3233 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3235 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3236 assert_eq!(route.paths[0][2].short_channel_id, 7);
3237 assert_eq!(route.paths[0][2].fee_msat, 0);
3238 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3239 // If we have a peer in the node map, we'll use their features here since we don't have
3240 // a way of figuring out their features from the invoice:
3241 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3242 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3244 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3245 assert_eq!(route.paths[0][3].short_channel_id, 10);
3246 assert_eq!(route.paths[0][3].fee_msat, 100);
3247 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3248 assert_eq!(route.paths[0][3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3249 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3251 // ...but still use 8 for larger payments as 6 has a variable feerate
3252 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3253 assert_eq!(route.paths[0].len(), 5);
3255 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3256 assert_eq!(route.paths[0][0].short_channel_id, 2);
3257 assert_eq!(route.paths[0][0].fee_msat, 3000);
3258 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3259 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3260 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3262 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3263 assert_eq!(route.paths[0][1].short_channel_id, 4);
3264 assert_eq!(route.paths[0][1].fee_msat, 0);
3265 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3266 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3267 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3269 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3270 assert_eq!(route.paths[0][2].short_channel_id, 6);
3271 assert_eq!(route.paths[0][2].fee_msat, 0);
3272 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3273 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3274 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3276 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3277 assert_eq!(route.paths[0][3].short_channel_id, 11);
3278 assert_eq!(route.paths[0][3].fee_msat, 1000);
3279 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3280 // If we have a peer in the node map, we'll use their features here since we don't have
3281 // a way of figuring out their features from the invoice:
3282 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3283 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3285 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3286 assert_eq!(route.paths[0][4].short_channel_id, 8);
3287 assert_eq!(route.paths[0][4].fee_msat, 2000);
3288 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3289 assert_eq!(route.paths[0][4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3290 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3293 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> {
3294 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3295 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3296 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3298 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3299 let last_hops = RouteHint(vec![RouteHintHop {
3300 src_node_id: middle_node_id,
3301 short_channel_id: 8,
3304 proportional_millionths: last_hop_fee_prop,
3306 cltv_expiry_delta: (8 << 4) | 1,
3307 htlc_minimum_msat: None,
3308 htlc_maximum_msat: last_hop_htlc_max,
3310 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]);
3311 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3312 let scorer = ln_test_utils::TestScorer::new();
3313 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3314 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3315 let logger = ln_test_utils::TestLogger::new();
3316 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3317 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3318 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3323 fn unannounced_path_test() {
3324 // We should be able to send a payment to a destination without any help of a routing graph
3325 // if we have a channel with a common counterparty that appears in the first and last hop
3327 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3329 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3330 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3331 assert_eq!(route.paths[0].len(), 2);
3333 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3334 assert_eq!(route.paths[0][0].short_channel_id, 42);
3335 assert_eq!(route.paths[0][0].fee_msat, 1001);
3336 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3337 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3338 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3340 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3341 assert_eq!(route.paths[0][1].short_channel_id, 8);
3342 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3343 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3344 assert_eq!(route.paths[0][1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3345 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3349 fn overflow_unannounced_path_test_liquidity_underflow() {
3350 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3351 // the last-hop had a fee which overflowed a u64, we'd panic.
3352 // This was due to us adding the first-hop from us unconditionally, causing us to think
3353 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3354 // In this test, we previously hit a subtraction underflow due to having less available
3355 // liquidity at the last hop than 0.
3356 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());
3360 fn overflow_unannounced_path_test_feerate_overflow() {
3361 // This tests for the same case as above, except instead of hitting a subtraction
3362 // underflow, we hit a case where the fee charged at a hop overflowed.
3363 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());
3367 fn available_amount_while_routing_test() {
3368 // Tests whether we choose the correct available channel amount while routing.
3370 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3371 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3372 let scorer = ln_test_utils::TestScorer::new();
3373 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3374 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3375 let config = UserConfig::default();
3376 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
3378 // We will use a simple single-path route from
3379 // our node to node2 via node0: channels {1, 3}.
3381 // First disable all other paths.
3382 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3384 short_channel_id: 2,
3387 cltv_expiry_delta: 0,
3388 htlc_minimum_msat: 0,
3389 htlc_maximum_msat: 100_000,
3391 fee_proportional_millionths: 0,
3392 excess_data: Vec::new()
3394 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3396 short_channel_id: 12,
3399 cltv_expiry_delta: 0,
3400 htlc_minimum_msat: 0,
3401 htlc_maximum_msat: 100_000,
3403 fee_proportional_millionths: 0,
3404 excess_data: Vec::new()
3407 // Make the first channel (#1) very permissive,
3408 // and we will be testing all limits on the second channel.
3409 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3411 short_channel_id: 1,
3414 cltv_expiry_delta: 0,
3415 htlc_minimum_msat: 0,
3416 htlc_maximum_msat: 1_000_000_000,
3418 fee_proportional_millionths: 0,
3419 excess_data: Vec::new()
3422 // First, let's see if routing works if we have absolutely no idea about the available amount.
3423 // In this case, it should be set to 250_000 sats.
3424 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3425 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3426 short_channel_id: 3,
3429 cltv_expiry_delta: 0,
3430 htlc_minimum_msat: 0,
3431 htlc_maximum_msat: 250_000_000,
3433 fee_proportional_millionths: 0,
3434 excess_data: Vec::new()
3438 // Attempt to route more than available results in a failure.
3439 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3440 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3441 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3442 } else { panic!(); }
3446 // Now, attempt to route an exact amount we have should be fine.
3447 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();
3448 assert_eq!(route.paths.len(), 1);
3449 let path = route.paths.last().unwrap();
3450 assert_eq!(path.len(), 2);
3451 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3452 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3455 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3456 // Disable channel #1 and use another first hop.
3457 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3458 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3459 short_channel_id: 1,
3462 cltv_expiry_delta: 0,
3463 htlc_minimum_msat: 0,
3464 htlc_maximum_msat: 1_000_000_000,
3466 fee_proportional_millionths: 0,
3467 excess_data: Vec::new()
3470 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3471 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3474 // Attempt to route more than available results in a failure.
3475 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3476 &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) {
3477 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3478 } else { panic!(); }
3482 // Now, attempt to route an exact amount we have should be fine.
3483 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();
3484 assert_eq!(route.paths.len(), 1);
3485 let path = route.paths.last().unwrap();
3486 assert_eq!(path.len(), 2);
3487 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3488 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3491 // Enable channel #1 back.
3492 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3493 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3494 short_channel_id: 1,
3497 cltv_expiry_delta: 0,
3498 htlc_minimum_msat: 0,
3499 htlc_maximum_msat: 1_000_000_000,
3501 fee_proportional_millionths: 0,
3502 excess_data: Vec::new()
3506 // Now let's see if routing works if we know only htlc_maximum_msat.
3507 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3508 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3509 short_channel_id: 3,
3512 cltv_expiry_delta: 0,
3513 htlc_minimum_msat: 0,
3514 htlc_maximum_msat: 15_000,
3516 fee_proportional_millionths: 0,
3517 excess_data: Vec::new()
3521 // Attempt to route more than available results in a failure.
3522 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3523 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3524 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3525 } else { panic!(); }
3529 // Now, attempt to route an exact amount we have should be fine.
3530 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3531 assert_eq!(route.paths.len(), 1);
3532 let path = route.paths.last().unwrap();
3533 assert_eq!(path.len(), 2);
3534 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3535 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3538 // Now let's see if routing works if we know only capacity from the UTXO.
3540 // We can't change UTXO capacity on the fly, so we'll disable
3541 // the existing channel and add another one with the capacity we need.
3542 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3544 short_channel_id: 3,
3547 cltv_expiry_delta: 0,
3548 htlc_minimum_msat: 0,
3549 htlc_maximum_msat: MAX_VALUE_MSAT,
3551 fee_proportional_millionths: 0,
3552 excess_data: Vec::new()
3555 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3556 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3557 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3558 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3559 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3561 *chain_monitor.utxo_ret.lock().unwrap() =
3562 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
3563 gossip_sync.add_utxo_lookup(Some(chain_monitor));
3565 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3566 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3568 short_channel_id: 333,
3571 cltv_expiry_delta: (3 << 4) | 1,
3572 htlc_minimum_msat: 0,
3573 htlc_maximum_msat: 15_000,
3575 fee_proportional_millionths: 0,
3576 excess_data: Vec::new()
3578 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3580 short_channel_id: 333,
3583 cltv_expiry_delta: (3 << 4) | 2,
3584 htlc_minimum_msat: 0,
3585 htlc_maximum_msat: 15_000,
3587 fee_proportional_millionths: 0,
3588 excess_data: Vec::new()
3592 // Attempt to route more than available results in a failure.
3593 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3594 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3595 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3596 } else { panic!(); }
3600 // Now, attempt to route an exact amount we have should be fine.
3601 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3602 assert_eq!(route.paths.len(), 1);
3603 let path = route.paths.last().unwrap();
3604 assert_eq!(path.len(), 2);
3605 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3606 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3609 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3610 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3612 short_channel_id: 333,
3615 cltv_expiry_delta: 0,
3616 htlc_minimum_msat: 0,
3617 htlc_maximum_msat: 10_000,
3619 fee_proportional_millionths: 0,
3620 excess_data: Vec::new()
3624 // Attempt to route more than available results in a failure.
3625 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3626 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3627 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3628 } else { panic!(); }
3632 // Now, attempt to route an exact amount we have should be fine.
3633 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3634 assert_eq!(route.paths.len(), 1);
3635 let path = route.paths.last().unwrap();
3636 assert_eq!(path.len(), 2);
3637 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3638 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3643 fn available_liquidity_last_hop_test() {
3644 // Check that available liquidity properly limits the path even when only
3645 // one of the latter hops is limited.
3646 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3647 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3648 let scorer = ln_test_utils::TestScorer::new();
3649 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3650 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3651 let config = UserConfig::default();
3652 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
3654 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3655 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3656 // Total capacity: 50 sats.
3658 // Disable other potential paths.
3659 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3661 short_channel_id: 2,
3664 cltv_expiry_delta: 0,
3665 htlc_minimum_msat: 0,
3666 htlc_maximum_msat: 100_000,
3668 fee_proportional_millionths: 0,
3669 excess_data: Vec::new()
3671 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3673 short_channel_id: 7,
3676 cltv_expiry_delta: 0,
3677 htlc_minimum_msat: 0,
3678 htlc_maximum_msat: 100_000,
3680 fee_proportional_millionths: 0,
3681 excess_data: Vec::new()
3686 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3687 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3688 short_channel_id: 12,
3691 cltv_expiry_delta: 0,
3692 htlc_minimum_msat: 0,
3693 htlc_maximum_msat: 100_000,
3695 fee_proportional_millionths: 0,
3696 excess_data: Vec::new()
3698 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3699 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3700 short_channel_id: 13,
3703 cltv_expiry_delta: 0,
3704 htlc_minimum_msat: 0,
3705 htlc_maximum_msat: 100_000,
3707 fee_proportional_millionths: 0,
3708 excess_data: Vec::new()
3711 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3713 short_channel_id: 6,
3716 cltv_expiry_delta: 0,
3717 htlc_minimum_msat: 0,
3718 htlc_maximum_msat: 50_000,
3720 fee_proportional_millionths: 0,
3721 excess_data: Vec::new()
3723 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3725 short_channel_id: 11,
3728 cltv_expiry_delta: 0,
3729 htlc_minimum_msat: 0,
3730 htlc_maximum_msat: 100_000,
3732 fee_proportional_millionths: 0,
3733 excess_data: Vec::new()
3736 // Attempt to route more than available results in a failure.
3737 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3738 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3739 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3740 } else { panic!(); }
3744 // Now, attempt to route 49 sats (just a bit below the capacity).
3745 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3746 assert_eq!(route.paths.len(), 1);
3747 let mut total_amount_paid_msat = 0;
3748 for path in &route.paths {
3749 assert_eq!(path.len(), 4);
3750 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3751 total_amount_paid_msat += path.last().unwrap().fee_msat;
3753 assert_eq!(total_amount_paid_msat, 49_000);
3757 // Attempt to route an exact amount is also fine
3758 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3759 assert_eq!(route.paths.len(), 1);
3760 let mut total_amount_paid_msat = 0;
3761 for path in &route.paths {
3762 assert_eq!(path.len(), 4);
3763 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3764 total_amount_paid_msat += path.last().unwrap().fee_msat;
3766 assert_eq!(total_amount_paid_msat, 50_000);
3771 fn ignore_fee_first_hop_test() {
3772 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3773 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3774 let scorer = ln_test_utils::TestScorer::new();
3775 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3776 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3777 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3779 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3780 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3781 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3782 short_channel_id: 1,
3785 cltv_expiry_delta: 0,
3786 htlc_minimum_msat: 0,
3787 htlc_maximum_msat: 100_000,
3788 fee_base_msat: 1_000_000,
3789 fee_proportional_millionths: 0,
3790 excess_data: Vec::new()
3792 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3794 short_channel_id: 3,
3797 cltv_expiry_delta: 0,
3798 htlc_minimum_msat: 0,
3799 htlc_maximum_msat: 50_000,
3801 fee_proportional_millionths: 0,
3802 excess_data: Vec::new()
3806 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3807 assert_eq!(route.paths.len(), 1);
3808 let mut total_amount_paid_msat = 0;
3809 for path in &route.paths {
3810 assert_eq!(path.len(), 2);
3811 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3812 total_amount_paid_msat += path.last().unwrap().fee_msat;
3814 assert_eq!(total_amount_paid_msat, 50_000);
3819 fn simple_mpp_route_test() {
3820 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3821 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3822 let scorer = ln_test_utils::TestScorer::new();
3823 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3824 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3825 let config = UserConfig::default();
3826 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3827 .with_features(channelmanager::provided_invoice_features(&config));
3829 // We need a route consisting of 3 paths:
3830 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3831 // To achieve this, the amount being transferred should be around
3832 // the total capacity of these 3 paths.
3834 // First, we set limits on these (previously unlimited) channels.
3835 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3837 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3838 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3840 short_channel_id: 1,
3843 cltv_expiry_delta: 0,
3844 htlc_minimum_msat: 0,
3845 htlc_maximum_msat: 100_000,
3847 fee_proportional_millionths: 0,
3848 excess_data: Vec::new()
3850 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3851 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3852 short_channel_id: 3,
3855 cltv_expiry_delta: 0,
3856 htlc_minimum_msat: 0,
3857 htlc_maximum_msat: 50_000,
3859 fee_proportional_millionths: 0,
3860 excess_data: Vec::new()
3863 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3864 // (total limit 60).
3865 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3867 short_channel_id: 12,
3870 cltv_expiry_delta: 0,
3871 htlc_minimum_msat: 0,
3872 htlc_maximum_msat: 60_000,
3874 fee_proportional_millionths: 0,
3875 excess_data: Vec::new()
3877 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3879 short_channel_id: 13,
3882 cltv_expiry_delta: 0,
3883 htlc_minimum_msat: 0,
3884 htlc_maximum_msat: 60_000,
3886 fee_proportional_millionths: 0,
3887 excess_data: Vec::new()
3890 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3891 // (total capacity 180 sats).
3892 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3893 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3894 short_channel_id: 2,
3897 cltv_expiry_delta: 0,
3898 htlc_minimum_msat: 0,
3899 htlc_maximum_msat: 200_000,
3901 fee_proportional_millionths: 0,
3902 excess_data: Vec::new()
3904 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3905 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3906 short_channel_id: 4,
3909 cltv_expiry_delta: 0,
3910 htlc_minimum_msat: 0,
3911 htlc_maximum_msat: 180_000,
3913 fee_proportional_millionths: 0,
3914 excess_data: Vec::new()
3918 // Attempt to route more than available results in a failure.
3919 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3920 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
3921 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3922 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3923 } else { panic!(); }
3927 // Attempt to route while setting max_path_count to 0 results in a failure.
3928 let zero_payment_params = payment_params.clone().with_max_path_count(0);
3929 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3930 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
3931 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3932 assert_eq!(err, "Can't find a route with no paths allowed.");
3933 } else { panic!(); }
3937 // Attempt to route while setting max_path_count to 3 results in a failure.
3938 // This is the case because the minimal_value_contribution_msat would require each path
3939 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
3940 let fail_payment_params = payment_params.clone().with_max_path_count(3);
3941 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3942 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
3943 Arc::clone(&logger), &scorer, &random_seed_bytes) {
3944 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3945 } else { panic!(); }
3949 // Now, attempt to route 250 sats (just a bit below the capacity).
3950 // Our algorithm should provide us with these 3 paths.
3951 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3952 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3953 assert_eq!(route.paths.len(), 3);
3954 let mut total_amount_paid_msat = 0;
3955 for path in &route.paths {
3956 assert_eq!(path.len(), 2);
3957 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3958 total_amount_paid_msat += path.last().unwrap().fee_msat;
3960 assert_eq!(total_amount_paid_msat, 250_000);
3964 // Attempt to route an exact amount is also fine
3965 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
3966 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3967 assert_eq!(route.paths.len(), 3);
3968 let mut total_amount_paid_msat = 0;
3969 for path in &route.paths {
3970 assert_eq!(path.len(), 2);
3971 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3972 total_amount_paid_msat += path.last().unwrap().fee_msat;
3974 assert_eq!(total_amount_paid_msat, 290_000);
3979 fn long_mpp_route_test() {
3980 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3981 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3982 let scorer = ln_test_utils::TestScorer::new();
3983 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3984 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3985 let config = UserConfig::default();
3986 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
3988 // We need a route consisting of 3 paths:
3989 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3990 // Note that these paths overlap (channels 5, 12, 13).
3991 // We will route 300 sats.
3992 // Each path will have 100 sats capacity, those channels which
3993 // are used twice will have 200 sats capacity.
3995 // Disable other potential paths.
3996 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3998 short_channel_id: 2,
4001 cltv_expiry_delta: 0,
4002 htlc_minimum_msat: 0,
4003 htlc_maximum_msat: 100_000,
4005 fee_proportional_millionths: 0,
4006 excess_data: Vec::new()
4008 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4009 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4010 short_channel_id: 7,
4013 cltv_expiry_delta: 0,
4014 htlc_minimum_msat: 0,
4015 htlc_maximum_msat: 100_000,
4017 fee_proportional_millionths: 0,
4018 excess_data: Vec::new()
4021 // Path via {node0, node2} is channels {1, 3, 5}.
4022 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4024 short_channel_id: 1,
4027 cltv_expiry_delta: 0,
4028 htlc_minimum_msat: 0,
4029 htlc_maximum_msat: 100_000,
4031 fee_proportional_millionths: 0,
4032 excess_data: Vec::new()
4034 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4036 short_channel_id: 3,
4039 cltv_expiry_delta: 0,
4040 htlc_minimum_msat: 0,
4041 htlc_maximum_msat: 100_000,
4043 fee_proportional_millionths: 0,
4044 excess_data: Vec::new()
4047 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4048 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4049 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4050 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4051 short_channel_id: 5,
4054 cltv_expiry_delta: 0,
4055 htlc_minimum_msat: 0,
4056 htlc_maximum_msat: 200_000,
4058 fee_proportional_millionths: 0,
4059 excess_data: Vec::new()
4062 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4063 // Add 100 sats to the capacities of {12, 13}, because these channels
4064 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4065 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4067 short_channel_id: 12,
4070 cltv_expiry_delta: 0,
4071 htlc_minimum_msat: 0,
4072 htlc_maximum_msat: 200_000,
4074 fee_proportional_millionths: 0,
4075 excess_data: Vec::new()
4077 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4079 short_channel_id: 13,
4082 cltv_expiry_delta: 0,
4083 htlc_minimum_msat: 0,
4084 htlc_maximum_msat: 200_000,
4086 fee_proportional_millionths: 0,
4087 excess_data: Vec::new()
4090 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4092 short_channel_id: 6,
4095 cltv_expiry_delta: 0,
4096 htlc_minimum_msat: 0,
4097 htlc_maximum_msat: 100_000,
4099 fee_proportional_millionths: 0,
4100 excess_data: Vec::new()
4102 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4104 short_channel_id: 11,
4107 cltv_expiry_delta: 0,
4108 htlc_minimum_msat: 0,
4109 htlc_maximum_msat: 100_000,
4111 fee_proportional_millionths: 0,
4112 excess_data: Vec::new()
4115 // Path via {node7, node2} is channels {12, 13, 5}.
4116 // We already limited them to 200 sats (they are used twice for 100 sats).
4117 // Nothing to do here.
4120 // Attempt to route more than available results in a failure.
4121 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4122 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4123 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4124 } else { panic!(); }
4128 // Now, attempt to route 300 sats (exact amount we can route).
4129 // Our algorithm should provide us with these 3 paths, 100 sats each.
4130 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4131 assert_eq!(route.paths.len(), 3);
4133 let mut total_amount_paid_msat = 0;
4134 for path in &route.paths {
4135 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4136 total_amount_paid_msat += path.last().unwrap().fee_msat;
4138 assert_eq!(total_amount_paid_msat, 300_000);
4144 fn mpp_cheaper_route_test() {
4145 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4146 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4147 let scorer = ln_test_utils::TestScorer::new();
4148 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4149 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4150 let config = UserConfig::default();
4151 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4153 // This test checks that if we have two cheaper paths and one more expensive path,
4154 // so that liquidity-wise any 2 of 3 combination is sufficient,
4155 // two cheaper paths will be taken.
4156 // These paths have equal available liquidity.
4158 // We need a combination of 3 paths:
4159 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4160 // Note that these paths overlap (channels 5, 12, 13).
4161 // Each path will have 100 sats capacity, those channels which
4162 // are used twice will have 200 sats capacity.
4164 // Disable other potential paths.
4165 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4166 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4167 short_channel_id: 2,
4170 cltv_expiry_delta: 0,
4171 htlc_minimum_msat: 0,
4172 htlc_maximum_msat: 100_000,
4174 fee_proportional_millionths: 0,
4175 excess_data: Vec::new()
4177 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4178 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4179 short_channel_id: 7,
4182 cltv_expiry_delta: 0,
4183 htlc_minimum_msat: 0,
4184 htlc_maximum_msat: 100_000,
4186 fee_proportional_millionths: 0,
4187 excess_data: Vec::new()
4190 // Path via {node0, node2} is channels {1, 3, 5}.
4191 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4192 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4193 short_channel_id: 1,
4196 cltv_expiry_delta: 0,
4197 htlc_minimum_msat: 0,
4198 htlc_maximum_msat: 100_000,
4200 fee_proportional_millionths: 0,
4201 excess_data: Vec::new()
4203 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4204 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4205 short_channel_id: 3,
4208 cltv_expiry_delta: 0,
4209 htlc_minimum_msat: 0,
4210 htlc_maximum_msat: 100_000,
4212 fee_proportional_millionths: 0,
4213 excess_data: Vec::new()
4216 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4217 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4218 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4220 short_channel_id: 5,
4223 cltv_expiry_delta: 0,
4224 htlc_minimum_msat: 0,
4225 htlc_maximum_msat: 200_000,
4227 fee_proportional_millionths: 0,
4228 excess_data: Vec::new()
4231 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4232 // Add 100 sats to the capacities of {12, 13}, because these channels
4233 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4234 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4236 short_channel_id: 12,
4239 cltv_expiry_delta: 0,
4240 htlc_minimum_msat: 0,
4241 htlc_maximum_msat: 200_000,
4243 fee_proportional_millionths: 0,
4244 excess_data: Vec::new()
4246 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4248 short_channel_id: 13,
4251 cltv_expiry_delta: 0,
4252 htlc_minimum_msat: 0,
4253 htlc_maximum_msat: 200_000,
4255 fee_proportional_millionths: 0,
4256 excess_data: Vec::new()
4259 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4261 short_channel_id: 6,
4264 cltv_expiry_delta: 0,
4265 htlc_minimum_msat: 0,
4266 htlc_maximum_msat: 100_000,
4267 fee_base_msat: 1_000,
4268 fee_proportional_millionths: 0,
4269 excess_data: Vec::new()
4271 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4273 short_channel_id: 11,
4276 cltv_expiry_delta: 0,
4277 htlc_minimum_msat: 0,
4278 htlc_maximum_msat: 100_000,
4280 fee_proportional_millionths: 0,
4281 excess_data: Vec::new()
4284 // Path via {node7, node2} is channels {12, 13, 5}.
4285 // We already limited them to 200 sats (they are used twice for 100 sats).
4286 // Nothing to do here.
4289 // Now, attempt to route 180 sats.
4290 // Our algorithm should provide us with these 2 paths.
4291 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4292 assert_eq!(route.paths.len(), 2);
4294 let mut total_value_transferred_msat = 0;
4295 let mut total_paid_msat = 0;
4296 for path in &route.paths {
4297 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4298 total_value_transferred_msat += path.last().unwrap().fee_msat;
4300 total_paid_msat += hop.fee_msat;
4303 // If we paid fee, this would be higher.
4304 assert_eq!(total_value_transferred_msat, 180_000);
4305 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4306 assert_eq!(total_fees_paid, 0);
4311 fn fees_on_mpp_route_test() {
4312 // This test makes sure that MPP algorithm properly takes into account
4313 // fees charged on the channels, by making the fees impactful:
4314 // if the fee is not properly accounted for, the behavior is different.
4315 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4316 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4317 let scorer = ln_test_utils::TestScorer::new();
4318 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4319 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4320 let config = UserConfig::default();
4321 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4323 // We need a route consisting of 2 paths:
4324 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4325 // We will route 200 sats, Each path will have 100 sats capacity.
4327 // This test is not particularly stable: e.g.,
4328 // there's a way to route via {node0, node2, node4}.
4329 // It works while pathfinding is deterministic, but can be broken otherwise.
4330 // It's fine to ignore this concern for now.
4332 // Disable other potential paths.
4333 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4334 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4335 short_channel_id: 2,
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 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4348 short_channel_id: 7,
4351 cltv_expiry_delta: 0,
4352 htlc_minimum_msat: 0,
4353 htlc_maximum_msat: 100_000,
4355 fee_proportional_millionths: 0,
4356 excess_data: Vec::new()
4359 // Path via {node0, node2} is channels {1, 3, 5}.
4360 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4362 short_channel_id: 1,
4365 cltv_expiry_delta: 0,
4366 htlc_minimum_msat: 0,
4367 htlc_maximum_msat: 100_000,
4369 fee_proportional_millionths: 0,
4370 excess_data: Vec::new()
4372 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4373 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4374 short_channel_id: 3,
4377 cltv_expiry_delta: 0,
4378 htlc_minimum_msat: 0,
4379 htlc_maximum_msat: 100_000,
4381 fee_proportional_millionths: 0,
4382 excess_data: Vec::new()
4385 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4386 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4388 short_channel_id: 5,
4391 cltv_expiry_delta: 0,
4392 htlc_minimum_msat: 0,
4393 htlc_maximum_msat: 100_000,
4395 fee_proportional_millionths: 0,
4396 excess_data: Vec::new()
4399 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4400 // All channels should be 100 sats capacity. But for the fee experiment,
4401 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4402 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4403 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4404 // so no matter how large are other channels,
4405 // the whole path will be limited by 100 sats with just these 2 conditions:
4406 // - channel 12 capacity is 250 sats
4407 // - fee for channel 6 is 150 sats
4408 // Let's test this by enforcing these 2 conditions and removing other limits.
4409 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4411 short_channel_id: 12,
4414 cltv_expiry_delta: 0,
4415 htlc_minimum_msat: 0,
4416 htlc_maximum_msat: 250_000,
4418 fee_proportional_millionths: 0,
4419 excess_data: Vec::new()
4421 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4422 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4423 short_channel_id: 13,
4426 cltv_expiry_delta: 0,
4427 htlc_minimum_msat: 0,
4428 htlc_maximum_msat: MAX_VALUE_MSAT,
4430 fee_proportional_millionths: 0,
4431 excess_data: Vec::new()
4434 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4436 short_channel_id: 6,
4439 cltv_expiry_delta: 0,
4440 htlc_minimum_msat: 0,
4441 htlc_maximum_msat: MAX_VALUE_MSAT,
4442 fee_base_msat: 150_000,
4443 fee_proportional_millionths: 0,
4444 excess_data: Vec::new()
4446 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4447 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4448 short_channel_id: 11,
4451 cltv_expiry_delta: 0,
4452 htlc_minimum_msat: 0,
4453 htlc_maximum_msat: MAX_VALUE_MSAT,
4455 fee_proportional_millionths: 0,
4456 excess_data: Vec::new()
4460 // Attempt to route more than available results in a failure.
4461 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4462 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4463 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4464 } else { panic!(); }
4468 // Now, attempt to route 200 sats (exact amount we can route).
4469 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4470 assert_eq!(route.paths.len(), 2);
4472 let mut total_amount_paid_msat = 0;
4473 for path in &route.paths {
4474 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4475 total_amount_paid_msat += path.last().unwrap().fee_msat;
4477 assert_eq!(total_amount_paid_msat, 200_000);
4478 assert_eq!(route.get_total_fees(), 150_000);
4483 fn mpp_with_last_hops() {
4484 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4485 // via a single last-hop route hint, we'd fail to route if we first collected routes
4486 // totaling close but not quite enough to fund the full payment.
4488 // This was because we considered last-hop hints to have exactly the sought payment amount
4489 // instead of the amount we were trying to collect, needlessly limiting our path searching
4490 // at the very first hop.
4492 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4493 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4494 // to only have the remaining to-collect amount in available liquidity.
4496 // This bug appeared in production in some specific channel configurations.
4497 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4498 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4499 let scorer = ln_test_utils::TestScorer::new();
4500 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4501 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4502 let config = UserConfig::default();
4503 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_features(channelmanager::provided_invoice_features(&config))
4504 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4505 src_node_id: nodes[2],
4506 short_channel_id: 42,
4507 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4508 cltv_expiry_delta: 42,
4509 htlc_minimum_msat: None,
4510 htlc_maximum_msat: None,
4511 }])]).with_max_channel_saturation_power_of_half(0);
4513 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4514 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4515 // would first use the no-fee route and then fail to find a path along the second route as
4516 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4517 // under 5% of our payment amount.
4518 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4519 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4520 short_channel_id: 1,
4523 cltv_expiry_delta: (5 << 4) | 5,
4524 htlc_minimum_msat: 0,
4525 htlc_maximum_msat: 99_000,
4526 fee_base_msat: u32::max_value(),
4527 fee_proportional_millionths: u32::max_value(),
4528 excess_data: Vec::new()
4530 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4532 short_channel_id: 2,
4535 cltv_expiry_delta: (5 << 4) | 3,
4536 htlc_minimum_msat: 0,
4537 htlc_maximum_msat: 99_000,
4538 fee_base_msat: u32::max_value(),
4539 fee_proportional_millionths: u32::max_value(),
4540 excess_data: Vec::new()
4542 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4544 short_channel_id: 4,
4547 cltv_expiry_delta: (4 << 4) | 1,
4548 htlc_minimum_msat: 0,
4549 htlc_maximum_msat: MAX_VALUE_MSAT,
4551 fee_proportional_millionths: 0,
4552 excess_data: Vec::new()
4554 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4556 short_channel_id: 13,
4558 flags: 0|2, // Channel disabled
4559 cltv_expiry_delta: (13 << 4) | 1,
4560 htlc_minimum_msat: 0,
4561 htlc_maximum_msat: MAX_VALUE_MSAT,
4563 fee_proportional_millionths: 2000000,
4564 excess_data: Vec::new()
4567 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4569 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();
4570 assert_eq!(route.paths.len(), 2);
4571 route.paths.sort_by_key(|path| path[0].short_channel_id);
4572 // Paths are manually ordered ordered by SCID, so:
4573 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4574 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4575 assert_eq!(route.paths[0][0].short_channel_id, 1);
4576 assert_eq!(route.paths[0][0].fee_msat, 0);
4577 assert_eq!(route.paths[0][2].fee_msat, 99_000);
4578 assert_eq!(route.paths[1][0].short_channel_id, 2);
4579 assert_eq!(route.paths[1][0].fee_msat, 1);
4580 assert_eq!(route.paths[1][2].fee_msat, 1_000);
4581 assert_eq!(route.get_total_fees(), 1);
4582 assert_eq!(route.get_total_amount(), 100_000);
4586 fn drop_lowest_channel_mpp_route_test() {
4587 // This test checks that low-capacity channel is dropped when after
4588 // path finding we realize that we found more capacity than we need.
4589 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4590 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4591 let scorer = ln_test_utils::TestScorer::new();
4592 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4593 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4594 let config = UserConfig::default();
4595 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config))
4596 .with_max_channel_saturation_power_of_half(0);
4598 // We need a route consisting of 3 paths:
4599 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4601 // The first and the second paths should be sufficient, but the third should be
4602 // cheaper, so that we select it but drop later.
4604 // First, we set limits on these (previously unlimited) channels.
4605 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4607 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4608 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4609 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4610 short_channel_id: 1,
4613 cltv_expiry_delta: 0,
4614 htlc_minimum_msat: 0,
4615 htlc_maximum_msat: 100_000,
4617 fee_proportional_millionths: 0,
4618 excess_data: Vec::new()
4620 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4621 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4622 short_channel_id: 3,
4625 cltv_expiry_delta: 0,
4626 htlc_minimum_msat: 0,
4627 htlc_maximum_msat: 50_000,
4629 fee_proportional_millionths: 0,
4630 excess_data: Vec::new()
4633 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4634 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4636 short_channel_id: 12,
4639 cltv_expiry_delta: 0,
4640 htlc_minimum_msat: 0,
4641 htlc_maximum_msat: 60_000,
4643 fee_proportional_millionths: 0,
4644 excess_data: Vec::new()
4646 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4648 short_channel_id: 13,
4651 cltv_expiry_delta: 0,
4652 htlc_minimum_msat: 0,
4653 htlc_maximum_msat: 60_000,
4655 fee_proportional_millionths: 0,
4656 excess_data: Vec::new()
4659 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4660 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4662 short_channel_id: 2,
4665 cltv_expiry_delta: 0,
4666 htlc_minimum_msat: 0,
4667 htlc_maximum_msat: 20_000,
4669 fee_proportional_millionths: 0,
4670 excess_data: Vec::new()
4672 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4674 short_channel_id: 4,
4677 cltv_expiry_delta: 0,
4678 htlc_minimum_msat: 0,
4679 htlc_maximum_msat: 20_000,
4681 fee_proportional_millionths: 0,
4682 excess_data: Vec::new()
4686 // Attempt to route more than available results in a failure.
4687 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4688 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4689 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4690 } else { panic!(); }
4694 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4695 // Our algorithm should provide us with these 3 paths.
4696 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4697 assert_eq!(route.paths.len(), 3);
4698 let mut total_amount_paid_msat = 0;
4699 for path in &route.paths {
4700 assert_eq!(path.len(), 2);
4701 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4702 total_amount_paid_msat += path.last().unwrap().fee_msat;
4704 assert_eq!(total_amount_paid_msat, 125_000);
4708 // Attempt to route without the last small cheap channel
4709 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4710 assert_eq!(route.paths.len(), 2);
4711 let mut total_amount_paid_msat = 0;
4712 for path in &route.paths {
4713 assert_eq!(path.len(), 2);
4714 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4715 total_amount_paid_msat += path.last().unwrap().fee_msat;
4717 assert_eq!(total_amount_paid_msat, 90_000);
4722 fn min_criteria_consistency() {
4723 // Test that we don't use an inconsistent metric between updating and walking nodes during
4724 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4725 // was updated with a different criterion from the heap sorting, resulting in loops in
4726 // calculated paths. We test for that specific case here.
4728 // We construct a network that looks like this:
4730 // node2 -1(3)2- node3
4734 // node1 -1(5)2- node4 -1(1)2- node6
4740 // We create a loop on the side of our real path - our destination is node 6, with a
4741 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4742 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4743 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4744 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4745 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4746 // "previous hop" being set to node 3, creating a loop in the path.
4747 let secp_ctx = Secp256k1::new();
4748 let logger = Arc::new(ln_test_utils::TestLogger::new());
4749 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
4750 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4751 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4752 let scorer = ln_test_utils::TestScorer::new();
4753 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4754 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4755 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
4757 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4758 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4760 short_channel_id: 6,
4763 cltv_expiry_delta: (6 << 4) | 0,
4764 htlc_minimum_msat: 0,
4765 htlc_maximum_msat: MAX_VALUE_MSAT,
4767 fee_proportional_millionths: 0,
4768 excess_data: Vec::new()
4770 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4772 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4773 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4775 short_channel_id: 5,
4778 cltv_expiry_delta: (5 << 4) | 0,
4779 htlc_minimum_msat: 0,
4780 htlc_maximum_msat: MAX_VALUE_MSAT,
4782 fee_proportional_millionths: 0,
4783 excess_data: Vec::new()
4785 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4787 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4788 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4790 short_channel_id: 4,
4793 cltv_expiry_delta: (4 << 4) | 0,
4794 htlc_minimum_msat: 0,
4795 htlc_maximum_msat: MAX_VALUE_MSAT,
4797 fee_proportional_millionths: 0,
4798 excess_data: Vec::new()
4800 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4802 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4803 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4804 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4805 short_channel_id: 3,
4808 cltv_expiry_delta: (3 << 4) | 0,
4809 htlc_minimum_msat: 0,
4810 htlc_maximum_msat: MAX_VALUE_MSAT,
4812 fee_proportional_millionths: 0,
4813 excess_data: Vec::new()
4815 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4817 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4818 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4820 short_channel_id: 2,
4823 cltv_expiry_delta: (2 << 4) | 0,
4824 htlc_minimum_msat: 0,
4825 htlc_maximum_msat: MAX_VALUE_MSAT,
4827 fee_proportional_millionths: 0,
4828 excess_data: Vec::new()
4831 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4832 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4833 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4834 short_channel_id: 1,
4837 cltv_expiry_delta: (1 << 4) | 0,
4838 htlc_minimum_msat: 100,
4839 htlc_maximum_msat: MAX_VALUE_MSAT,
4841 fee_proportional_millionths: 0,
4842 excess_data: Vec::new()
4844 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4847 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4848 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4849 assert_eq!(route.paths.len(), 1);
4850 assert_eq!(route.paths[0].len(), 3);
4852 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4853 assert_eq!(route.paths[0][0].short_channel_id, 6);
4854 assert_eq!(route.paths[0][0].fee_msat, 100);
4855 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4856 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4857 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4859 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4860 assert_eq!(route.paths[0][1].short_channel_id, 5);
4861 assert_eq!(route.paths[0][1].fee_msat, 0);
4862 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4863 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4864 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4866 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4867 assert_eq!(route.paths[0][2].short_channel_id, 1);
4868 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4869 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4870 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4871 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4877 fn exact_fee_liquidity_limit() {
4878 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4879 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4880 // we calculated fees on a higher value, resulting in us ignoring such paths.
4881 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4882 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4883 let scorer = ln_test_utils::TestScorer::new();
4884 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4885 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4886 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4888 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4890 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4892 short_channel_id: 2,
4895 cltv_expiry_delta: 0,
4896 htlc_minimum_msat: 0,
4897 htlc_maximum_msat: 85_000,
4899 fee_proportional_millionths: 0,
4900 excess_data: Vec::new()
4903 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4904 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4905 short_channel_id: 12,
4908 cltv_expiry_delta: (4 << 4) | 1,
4909 htlc_minimum_msat: 0,
4910 htlc_maximum_msat: 270_000,
4912 fee_proportional_millionths: 1000000,
4913 excess_data: Vec::new()
4917 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4918 // 200% fee charged channel 13 in the 1-to-2 direction.
4919 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4920 assert_eq!(route.paths.len(), 1);
4921 assert_eq!(route.paths[0].len(), 2);
4923 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4924 assert_eq!(route.paths[0][0].short_channel_id, 12);
4925 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4926 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4927 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4928 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4930 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4931 assert_eq!(route.paths[0][1].short_channel_id, 13);
4932 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4933 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4934 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4935 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4940 fn htlc_max_reduction_below_min() {
4941 // Test that if, while walking the graph, we reduce the value being sent to meet an
4942 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4943 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4944 // resulting in us thinking there is no possible path, even if other paths exist.
4945 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4946 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4947 let scorer = ln_test_utils::TestScorer::new();
4948 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4949 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4950 let config = UserConfig::default();
4951 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
4953 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4954 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4955 // then try to send 90_000.
4956 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4958 short_channel_id: 2,
4961 cltv_expiry_delta: 0,
4962 htlc_minimum_msat: 0,
4963 htlc_maximum_msat: 80_000,
4965 fee_proportional_millionths: 0,
4966 excess_data: Vec::new()
4968 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4970 short_channel_id: 4,
4973 cltv_expiry_delta: (4 << 4) | 1,
4974 htlc_minimum_msat: 90_000,
4975 htlc_maximum_msat: MAX_VALUE_MSAT,
4977 fee_proportional_millionths: 0,
4978 excess_data: Vec::new()
4982 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4983 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4984 // expensive) channels 12-13 path.
4985 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4986 assert_eq!(route.paths.len(), 1);
4987 assert_eq!(route.paths[0].len(), 2);
4989 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4990 assert_eq!(route.paths[0][0].short_channel_id, 12);
4991 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4992 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4993 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4994 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4996 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4997 assert_eq!(route.paths[0][1].short_channel_id, 13);
4998 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4999 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
5000 assert_eq!(route.paths[0][1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5001 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
5006 fn multiple_direct_first_hops() {
5007 // Previously we'd only ever considered one first hop path per counterparty.
5008 // However, as we don't restrict users to one channel per peer, we really need to support
5009 // looking at all first hop paths.
5010 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5011 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5012 // route over multiple channels with the same first hop.
5013 let secp_ctx = Secp256k1::new();
5014 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5015 let logger = Arc::new(ln_test_utils::TestLogger::new());
5016 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5017 let scorer = ln_test_utils::TestScorer::new();
5018 let config = UserConfig::default();
5019 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_features(channelmanager::provided_invoice_features(&config));
5020 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5021 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5024 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5025 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5026 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5027 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5028 assert_eq!(route.paths.len(), 1);
5029 assert_eq!(route.paths[0].len(), 1);
5031 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5032 assert_eq!(route.paths[0][0].short_channel_id, 3);
5033 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5036 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5037 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5038 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5039 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5040 assert_eq!(route.paths.len(), 2);
5041 assert_eq!(route.paths[0].len(), 1);
5042 assert_eq!(route.paths[1].len(), 1);
5044 assert!((route.paths[0][0].short_channel_id == 3 && route.paths[1][0].short_channel_id == 2) ||
5045 (route.paths[0][0].short_channel_id == 2 && route.paths[1][0].short_channel_id == 3));
5047 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5048 assert_eq!(route.paths[0][0].fee_msat, 50_000);
5050 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
5051 assert_eq!(route.paths[1][0].fee_msat, 50_000);
5055 // If we have a bunch of outbound channels to the same node, where most are not
5056 // sufficient to pay the full payment, but one is, we should default to just using the
5057 // one single channel that has sufficient balance, avoiding MPP.
5059 // If we have several options above the 3xpayment value threshold, we should pick the
5060 // smallest of them, avoiding further fragmenting our available outbound balance to
5062 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5063 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5064 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5065 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5066 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5067 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5068 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5069 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5070 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5071 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5072 assert_eq!(route.paths.len(), 1);
5073 assert_eq!(route.paths[0].len(), 1);
5075 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
5076 assert_eq!(route.paths[0][0].short_channel_id, 6);
5077 assert_eq!(route.paths[0][0].fee_msat, 100_000);
5082 fn prefers_shorter_route_with_higher_fees() {
5083 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5084 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5085 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5087 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5088 let scorer = ln_test_utils::TestScorer::new();
5089 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5090 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5091 let route = get_route(
5092 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5093 Arc::clone(&logger), &scorer, &random_seed_bytes
5095 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5097 assert_eq!(route.get_total_fees(), 100);
5098 assert_eq!(route.get_total_amount(), 100);
5099 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5101 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5102 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5103 let scorer = FixedPenaltyScorer::with_penalty(100);
5104 let route = get_route(
5105 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5106 Arc::clone(&logger), &scorer, &random_seed_bytes
5108 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5110 assert_eq!(route.get_total_fees(), 300);
5111 assert_eq!(route.get_total_amount(), 100);
5112 assert_eq!(path, vec![2, 4, 7, 10]);
5115 struct BadChannelScorer {
5116 short_channel_id: u64,
5120 impl Writeable for BadChannelScorer {
5121 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5123 impl Score for BadChannelScorer {
5124 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5125 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5128 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5129 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5130 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5131 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5134 struct BadNodeScorer {
5139 impl Writeable for BadNodeScorer {
5140 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5143 impl Score for BadNodeScorer {
5144 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5145 if *target == self.node_id { u64::max_value() } else { 0 }
5148 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5149 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5150 fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5151 fn probe_successful(&mut self, _path: &[&RouteHop]) {}
5155 fn avoids_routing_through_bad_channels_and_nodes() {
5156 let (secp_ctx, network, _, _, logger) = build_graph();
5157 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5158 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5159 let network_graph = network.read_only();
5161 // A path to nodes[6] exists when no penalties are applied to any channel.
5162 let scorer = ln_test_utils::TestScorer::new();
5163 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5164 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5165 let route = get_route(
5166 &our_id, &payment_params, &network_graph, None, 100, 42,
5167 Arc::clone(&logger), &scorer, &random_seed_bytes
5169 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5171 assert_eq!(route.get_total_fees(), 100);
5172 assert_eq!(route.get_total_amount(), 100);
5173 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5175 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5176 let scorer = BadChannelScorer { short_channel_id: 6 };
5177 let route = get_route(
5178 &our_id, &payment_params, &network_graph, None, 100, 42,
5179 Arc::clone(&logger), &scorer, &random_seed_bytes
5181 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5183 assert_eq!(route.get_total_fees(), 300);
5184 assert_eq!(route.get_total_amount(), 100);
5185 assert_eq!(path, vec![2, 4, 7, 10]);
5187 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5188 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5190 &our_id, &payment_params, &network_graph, None, 100, 42,
5191 Arc::clone(&logger), &scorer, &random_seed_bytes
5193 Err(LightningError { err, .. } ) => {
5194 assert_eq!(err, "Failed to find a path to the given destination");
5196 Ok(_) => panic!("Expected error"),
5201 fn total_fees_single_path() {
5205 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5206 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5207 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5210 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5211 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5212 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5215 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5216 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5217 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5220 payment_params: None,
5223 assert_eq!(route.get_total_fees(), 250);
5224 assert_eq!(route.get_total_amount(), 225);
5228 fn total_fees_multi_path() {
5232 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5233 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5234 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5237 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5238 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5239 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5243 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5244 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5245 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5248 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5249 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5250 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5253 payment_params: None,
5256 assert_eq!(route.get_total_fees(), 200);
5257 assert_eq!(route.get_total_amount(), 300);
5261 fn total_empty_route_no_panic() {
5262 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5263 // would both panic if the route was completely empty. We test to ensure they return 0
5264 // here, even though its somewhat nonsensical as a route.
5265 let route = Route { paths: Vec::new(), payment_params: None };
5267 assert_eq!(route.get_total_fees(), 0);
5268 assert_eq!(route.get_total_amount(), 0);
5272 fn limits_total_cltv_delta() {
5273 let (secp_ctx, network, _, _, logger) = build_graph();
5274 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5275 let network_graph = network.read_only();
5277 let scorer = ln_test_utils::TestScorer::new();
5279 // Make sure that generally there is at least one route available
5280 let feasible_max_total_cltv_delta = 1008;
5281 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5282 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5283 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5284 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5285 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5286 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5287 assert_ne!(path.len(), 0);
5289 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5290 let fail_max_total_cltv_delta = 23;
5291 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5292 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5293 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5295 Err(LightningError { err, .. } ) => {
5296 assert_eq!(err, "Failed to find a path to the given destination");
5298 Ok(_) => panic!("Expected error"),
5303 fn avoids_recently_failed_paths() {
5304 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5305 // randomly inserting channels into it until we can't find a route anymore.
5306 let (secp_ctx, network, _, _, logger) = build_graph();
5307 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5308 let network_graph = network.read_only();
5310 let scorer = ln_test_utils::TestScorer::new();
5311 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5312 .with_max_path_count(1);
5313 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5314 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5316 // We should be able to find a route initially, and then after we fail a few random
5317 // channels eventually we won't be able to any longer.
5318 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5320 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5321 for chan in route.paths[0].iter() {
5322 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5324 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5325 % route.paths[0].len();
5326 payment_params.previously_failed_channels.push(route.paths[0][victim].short_channel_id);
5332 fn limits_path_length() {
5333 let (secp_ctx, network, _, _, logger) = build_line_graph();
5334 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5335 let network_graph = network.read_only();
5337 let scorer = ln_test_utils::TestScorer::new();
5338 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5339 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5341 // First check we can actually create a long route on this graph.
5342 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5343 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5344 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5345 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5346 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5348 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5349 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5350 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5351 Arc::clone(&logger), &scorer, &random_seed_bytes)
5353 Err(LightningError { err, .. } ) => {
5354 assert_eq!(err, "Failed to find a path to the given destination");
5356 Ok(_) => panic!("Expected error"),
5361 fn adds_and_limits_cltv_offset() {
5362 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5363 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5365 let scorer = ln_test_utils::TestScorer::new();
5367 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5368 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5369 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5370 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5371 assert_eq!(route.paths.len(), 1);
5373 let cltv_expiry_deltas_before = route.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5375 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5376 let mut route_default = route.clone();
5377 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5378 let cltv_expiry_deltas_default = route_default.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5379 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5380 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5381 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5383 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5384 let mut route_limited = route.clone();
5385 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5386 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5387 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5388 let cltv_expiry_deltas_limited = route_limited.paths[0].iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5389 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5393 fn adds_plausible_cltv_offset() {
5394 let (secp_ctx, network, _, _, logger) = build_graph();
5395 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5396 let network_graph = network.read_only();
5397 let network_nodes = network_graph.nodes();
5398 let network_channels = network_graph.channels();
5399 let scorer = ln_test_utils::TestScorer::new();
5400 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5401 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5402 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5404 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5405 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5406 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5408 let mut path_plausibility = vec![];
5410 for p in route.paths {
5411 // 1. Select random observation point
5412 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5413 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5415 prng.process_in_place(&mut random_bytes);
5416 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.len());
5417 let observation_point = NodeId::from_pubkey(&p.get(random_path_index).unwrap().pubkey);
5419 // 2. Calculate what CLTV expiry delta we would observe there
5420 let observed_cltv_expiry_delta: u32 = p[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5422 // 3. Starting from the observation point, find candidate paths
5423 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5424 candidates.push_back((observation_point, vec![]));
5426 let mut found_plausible_candidate = false;
5428 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5429 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5430 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5431 found_plausible_candidate = true;
5432 break 'candidate_loop;
5436 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5437 for channel_id in &cur_node.channels {
5438 if let Some(channel_info) = network_channels.get(&channel_id) {
5439 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5440 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5441 if cur_path_cltv_deltas.iter().sum::<u32>()
5442 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5443 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5444 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5445 candidates.push_back((*next_id, new_path_cltv_deltas));
5453 path_plausibility.push(found_plausible_candidate);
5455 assert!(path_plausibility.iter().all(|x| *x));
5459 fn builds_correct_path_from_hops() {
5460 let (secp_ctx, network, _, _, logger) = build_graph();
5461 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5462 let network_graph = network.read_only();
5464 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5465 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5467 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5468 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5469 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5470 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5471 let route_hop_pubkeys = route.paths[0].iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5472 assert_eq!(hops.len(), route.paths[0].len());
5473 for (idx, hop_pubkey) in hops.iter().enumerate() {
5474 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5479 fn avoids_saturating_channels() {
5480 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5481 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5483 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5485 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5486 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5487 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5489 short_channel_id: 4,
5492 cltv_expiry_delta: (4 << 4) | 1,
5493 htlc_minimum_msat: 0,
5494 htlc_maximum_msat: 250_000_000,
5496 fee_proportional_millionths: 0,
5497 excess_data: Vec::new()
5499 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5501 short_channel_id: 13,
5504 cltv_expiry_delta: (13 << 4) | 1,
5505 htlc_minimum_msat: 0,
5506 htlc_maximum_msat: 250_000_000,
5508 fee_proportional_millionths: 0,
5509 excess_data: Vec::new()
5512 let config = UserConfig::default();
5513 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
5514 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5515 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5516 // 100,000 sats is less than the available liquidity on each channel, set above.
5517 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();
5518 assert_eq!(route.paths.len(), 2);
5519 assert!((route.paths[0][1].short_channel_id == 4 && route.paths[1][1].short_channel_id == 13) ||
5520 (route.paths[1][1].short_channel_id == 4 && route.paths[0][1].short_channel_id == 13));
5523 #[cfg(not(feature = "no-std"))]
5524 pub(super) fn random_init_seed() -> u64 {
5525 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5526 use core::hash::{BuildHasher, Hasher};
5527 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5528 println!("Using seed of {}", seed);
5531 #[cfg(not(feature = "no-std"))]
5532 use crate::util::ser::ReadableArgs;
5535 #[cfg(not(feature = "no-std"))]
5536 fn generate_routes() {
5537 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5539 let mut d = match super::bench_utils::get_route_file() {
5546 let logger = ln_test_utils::TestLogger::new();
5547 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5548 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5549 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5551 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5552 let mut seed = random_init_seed() as usize;
5553 let nodes = graph.read_only().nodes().clone();
5554 'load_endpoints: for _ in 0..10 {
5556 seed = seed.overflowing_mul(0xdeadbeef).0;
5557 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5558 seed = seed.overflowing_mul(0xdeadbeef).0;
5559 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5560 let payment_params = PaymentParameters::from_node_id(dst, 42);
5561 let amt = seed as u64 % 200_000_000;
5562 let params = ProbabilisticScoringParameters::default();
5563 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5564 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5565 continue 'load_endpoints;
5572 #[cfg(not(feature = "no-std"))]
5573 fn generate_routes_mpp() {
5574 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5576 let mut d = match super::bench_utils::get_route_file() {
5583 let logger = ln_test_utils::TestLogger::new();
5584 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5585 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5586 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5587 let config = UserConfig::default();
5589 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5590 let mut seed = random_init_seed() as usize;
5591 let nodes = graph.read_only().nodes().clone();
5592 'load_endpoints: for _ in 0..10 {
5594 seed = seed.overflowing_mul(0xdeadbeef).0;
5595 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5596 seed = seed.overflowing_mul(0xdeadbeef).0;
5597 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5598 let payment_params = PaymentParameters::from_node_id(dst, 42).with_features(channelmanager::provided_invoice_features(&config));
5599 let amt = seed as u64 % 200_000_000;
5600 let params = ProbabilisticScoringParameters::default();
5601 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5602 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5603 continue 'load_endpoints;
5610 fn honors_manual_penalties() {
5611 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5612 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5614 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5615 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5617 let scorer_params = ProbabilisticScoringParameters::default();
5618 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5620 // First check set manual penalties are returned by the scorer.
5621 let usage = ChannelUsage {
5623 inflight_htlc_msat: 0,
5624 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5626 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5627 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5628 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5630 // Then check we can get a normal route
5631 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
5632 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5633 assert!(route.is_ok());
5635 // Then check that we can't get a route if we ban an intermediate node.
5636 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5637 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5638 assert!(route.is_err());
5640 // Finally make sure we can route again, when we remove the ban.
5641 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5642 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5643 assert!(route.is_ok());
5647 #[cfg(all(test, not(feature = "no-std")))]
5648 pub(crate) mod bench_utils {
5650 /// Tries to open a network graph file, or panics with a URL to fetch it.
5651 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5652 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
5653 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
5654 .or_else(|_| { // Fall back to guessing based on the binary location
5655 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5656 let mut path = std::env::current_exe().unwrap();
5657 path.pop(); // lightning-...
5659 path.pop(); // debug
5660 path.pop(); // target
5661 path.push("lightning");
5662 path.push("net_graph-2023-01-18.bin");
5663 eprintln!("{}", path.to_str().unwrap());
5666 .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");
5667 #[cfg(require_route_graph_test)]
5668 return Ok(res.unwrap());
5669 #[cfg(not(require_route_graph_test))]
5674 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5677 use bitcoin::hashes::Hash;
5678 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5679 use crate::chain::transaction::OutPoint;
5680 use crate::chain::keysinterface::{EntropySource, KeysManager};
5681 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5682 use crate::ln::features::InvoiceFeatures;
5683 use crate::routing::gossip::NetworkGraph;
5684 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5685 use crate::util::config::UserConfig;
5686 use crate::util::logger::{Logger, Record};
5687 use crate::util::ser::ReadableArgs;
5691 struct DummyLogger {}
5692 impl Logger for DummyLogger {
5693 fn log(&self, _record: &Record) {}
5696 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5697 let mut d = bench_utils::get_route_file().unwrap();
5698 NetworkGraph::read(&mut d, logger).unwrap()
5701 fn payer_pubkey() -> PublicKey {
5702 let secp_ctx = Secp256k1::new();
5703 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5707 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5709 channel_id: [0; 32],
5710 counterparty: ChannelCounterparty {
5711 features: channelmanager::provided_init_features(&UserConfig::default()),
5713 unspendable_punishment_reserve: 0,
5714 forwarding_info: None,
5715 outbound_htlc_minimum_msat: None,
5716 outbound_htlc_maximum_msat: None,
5718 funding_txo: Some(OutPoint {
5719 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5722 short_channel_id: Some(1),
5723 inbound_scid_alias: None,
5724 outbound_scid_alias: None,
5725 channel_value_satoshis: 10_000_000,
5727 balance_msat: 10_000_000,
5728 outbound_capacity_msat: 10_000_000,
5729 next_outbound_htlc_limit_msat: 10_000_000,
5730 inbound_capacity_msat: 0,
5731 unspendable_punishment_reserve: None,
5732 confirmations_required: None,
5733 confirmations: None,
5734 force_close_spend_delay: None,
5736 is_channel_ready: true,
5739 inbound_htlc_minimum_msat: None,
5740 inbound_htlc_maximum_msat: None,
5746 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5747 let logger = DummyLogger {};
5748 let network_graph = read_network_graph(&logger);
5749 let scorer = FixedPenaltyScorer::with_penalty(0);
5750 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5754 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5755 let logger = DummyLogger {};
5756 let network_graph = read_network_graph(&logger);
5757 let scorer = FixedPenaltyScorer::with_penalty(0);
5758 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5762 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5763 let logger = DummyLogger {};
5764 let network_graph = read_network_graph(&logger);
5765 let params = ProbabilisticScoringParameters::default();
5766 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5767 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5771 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5772 let logger = DummyLogger {};
5773 let network_graph = read_network_graph(&logger);
5774 let params = ProbabilisticScoringParameters::default();
5775 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5776 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5779 fn generate_routes<S: Score>(
5780 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5781 features: InvoiceFeatures
5783 let nodes = graph.read_only().nodes().clone();
5784 let payer = payer_pubkey();
5785 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5786 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5788 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5789 let mut routes = Vec::new();
5790 let mut route_endpoints = Vec::new();
5791 let mut seed: usize = 0xdeadbeef;
5792 'load_endpoints: for _ in 0..150 {
5795 let src = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5797 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5798 let params = PaymentParameters::from_node_id(dst, 42).with_features(features.clone());
5799 let first_hop = first_hop(src);
5800 let amt = seed as u64 % 1_000_000;
5801 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5803 route_endpoints.push((first_hop, params, amt));
5804 continue 'load_endpoints;
5809 // ...and seed the scorer with success and failure data...
5810 for route in routes {
5811 let amount = route.get_total_amount();
5812 if amount < 250_000 {
5813 for path in route.paths {
5814 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5816 } else if amount > 750_000 {
5817 for path in route.paths {
5818 let short_channel_id = path[path.len() / 2].short_channel_id;
5819 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5824 // Because we've changed channel scores, its possible we'll take different routes to the
5825 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5826 // requires a too-high CLTV delta.
5827 route_endpoints.retain(|(first_hop, params, amt)| {
5828 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5830 route_endpoints.truncate(100);
5831 assert_eq!(route_endpoints.len(), 100);
5833 // ...then benchmark finding paths between the nodes we learned.
5836 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5837 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());