1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::BlindedPayInfo;
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
29 use crate::prelude::*;
30 use crate::sync::Mutex;
31 use alloc::collections::BinaryHeap;
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> where
38 S::Target: for <'a> LockableScore<'a>,
42 random_seed_bytes: Mutex<[u8; 32]>,
46 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> DefaultRouter<G, L, S> where
48 S::Target: for <'a> LockableScore<'a>,
50 /// Creates a new router.
51 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S) -> Self {
52 let random_seed_bytes = Mutex::new(random_seed_bytes);
53 Self { network_graph, logger, random_seed_bytes, scorer }
57 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> Router for DefaultRouter<G, L, S> where
59 S::Target: for <'a> LockableScore<'a>,
62 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
63 inflight_htlcs: &InFlightHtlcs
64 ) -> Result<Route, LightningError> {
65 let random_seed_bytes = {
66 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
67 *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
68 *locked_random_seed_bytes
72 payer, params, &self.network_graph, first_hops, &*self.logger,
73 &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock(), inflight_htlcs),
79 /// A trait defining behavior for routing a payment.
81 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
83 &self, payer: &PublicKey, route_params: &RouteParameters,
84 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
85 ) -> Result<Route, LightningError>;
86 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
87 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
88 fn find_route_with_id(
89 &self, payer: &PublicKey, route_params: &RouteParameters,
90 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
91 _payment_hash: PaymentHash, _payment_id: PaymentId
92 ) -> Result<Route, LightningError> {
93 self.find_route(payer, route_params, first_hops, inflight_htlcs)
97 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
99 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
102 /// [`Score`]: crate::routing::scoring::Score
103 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score> {
105 // Maps a channel's short channel id and its direction to the liquidity used up.
106 inflight_htlcs: &'a InFlightHtlcs,
109 impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> {
110 /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
111 pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
112 ScorerAccountingForInFlightHtlcs {
120 impl<'a, S: Score> Writeable for ScorerAccountingForInFlightHtlcs<'a, S> {
121 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
124 impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> {
125 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage) -> u64 {
126 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
127 source, target, short_channel_id
129 let usage = ChannelUsage {
130 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
134 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
136 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
140 fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64) {
141 self.scorer.payment_path_failed(path, short_channel_id)
144 fn payment_path_successful(&mut self, path: &Path) {
145 self.scorer.payment_path_successful(path)
148 fn probe_failed(&mut self, path: &Path, short_channel_id: u64) {
149 self.scorer.probe_failed(path, short_channel_id)
152 fn probe_successful(&mut self, path: &Path) {
153 self.scorer.probe_successful(path)
157 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
158 /// in-use channel liquidity.
160 pub struct InFlightHtlcs(
161 // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
162 // is traveling in. The direction boolean is determined by checking if the HTLC source's public
163 // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
165 HashMap<(u64, bool), u64>
169 /// Constructs an empty `InFlightHtlcs`.
170 pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
172 /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
173 pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
174 if path.hops.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.hops.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.hops.iter().rev().zip(reversed_hops_with_payer) {
189 cumulative_msat += next_hop.fee_msat;
191 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
192 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
193 .or_insert(cumulative_msat);
197 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
199 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
200 self.0.get(&(channel_scid, source < target)).map(|v| *v)
204 impl Writeable for InFlightHtlcs {
205 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
208 impl Readable for InFlightHtlcs {
209 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
210 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
211 Ok(Self(infight_map))
215 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
216 /// that leads to it.
217 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
218 pub struct RouteHop {
219 /// The node_id of the node at this hop.
220 pub pubkey: PublicKey,
221 /// The node_announcement features of the node at this hop. For the last hop, these may be
222 /// amended to match the features present in the invoice this node generated.
223 pub node_features: NodeFeatures,
224 /// The channel that should be used from the previous hop to reach this node.
225 pub short_channel_id: u64,
226 /// The channel_announcement features of the channel that should be used from the previous hop
227 /// to reach this node.
228 pub channel_features: ChannelFeatures,
229 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
230 /// If this is the last hop in [`Path::hops`]:
231 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
232 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
234 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
236 /// The CLTV delta added for this hop.
237 /// If this is the last hop in [`Path::hops`]:
238 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
239 /// * otherwise, this is the CLTV delta expected at the destination
241 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
242 pub cltv_expiry_delta: u32,
245 impl_writeable_tlv_based!(RouteHop, {
246 (0, pubkey, required),
247 (2, node_features, required),
248 (4, short_channel_id, required),
249 (6, channel_features, required),
250 (8, fee_msat, required),
251 (10, cltv_expiry_delta, required),
254 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
255 /// their BOLT12 [`Invoice`].
257 /// [`Invoice`]: crate::offers::invoice::Invoice
258 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
259 pub struct BlindedTail {
260 /// The hops of the [`BlindedPath`] provided by the recipient.
262 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
263 pub hops: Vec<BlindedHop>,
264 /// The blinding point of the [`BlindedPath`] provided by the recipient.
266 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
267 pub blinding_point: PublicKey,
268 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
269 /// inferring the destination. May be 0.
270 pub excess_final_cltv_expiry_delta: u32,
271 /// The total amount paid on this [`Path`], excluding the fees.
272 pub final_value_msat: u64,
275 impl_writeable_tlv_based!(BlindedTail, {
277 (2, blinding_point, required),
278 (4, excess_final_cltv_expiry_delta, required),
279 (6, final_value_msat, required),
282 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
283 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
284 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
286 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
287 pub hops: Vec<RouteHop>,
288 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
289 pub blinded_tail: Option<BlindedTail>,
293 /// Gets the fees for a given path, excluding any excess paid to the recipient.
294 pub fn fee_msat(&self) -> u64 {
295 match &self.blinded_tail {
296 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
298 // Do not count last hop of each path since that's the full value of the payment
299 self.hops.split_last().map_or(0,
300 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
305 /// Gets the total amount paid on this [`Path`], excluding the fees.
306 pub fn final_value_msat(&self) -> u64 {
307 match &self.blinded_tail {
308 Some(blinded_tail) => blinded_tail.final_value_msat,
309 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
313 /// Gets the final hop's CLTV expiry delta.
314 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
315 match &self.blinded_tail {
317 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
322 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
323 /// it can take multiple paths. Each path is composed of one or more hops through the network.
324 #[derive(Clone, Hash, PartialEq, Eq)]
326 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
327 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
329 pub paths: Vec<Path>,
330 /// The `payment_params` parameter passed to [`find_route`].
331 /// This is used by `ChannelManager` to track information which may be required for retries,
332 /// provided back to you via [`Event::PaymentPathFailed`].
334 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
335 pub payment_params: Option<PaymentParameters>,
339 /// Returns the total amount of fees paid on this [`Route`].
341 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
342 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
343 pub fn get_total_fees(&self) -> u64 {
344 self.paths.iter().map(|path| path.fee_msat()).sum()
347 /// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
348 /// requested if we had to reach htlc_minimum_msat.
349 pub fn get_total_amount(&self) -> u64 {
350 self.paths.iter().map(|path| path.final_value_msat()).sum()
354 const SERIALIZATION_VERSION: u8 = 1;
355 const MIN_SERIALIZATION_VERSION: u8 = 1;
357 impl Writeable for Route {
358 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
359 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
360 (self.paths.len() as u64).write(writer)?;
361 for path in self.paths.iter() {
362 (path.hops.len() as u8).write(writer)?;
363 for hop in path.hops.iter() {
367 write_tlv_fields!(writer, {
368 (1, self.payment_params, option),
374 impl Readable for Route {
375 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
376 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
377 let path_count: u64 = Readable::read(reader)?;
378 if path_count == 0 { return Err(DecodeError::InvalidValue); }
379 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
380 let mut min_final_cltv_expiry_delta = u32::max_value();
381 for _ in 0..path_count {
382 let hop_count: u8 = Readable::read(reader)?;
383 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
384 for _ in 0..hop_count {
385 hops.push(Readable::read(reader)?);
387 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
388 min_final_cltv_expiry_delta =
389 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
390 paths.push(Path { hops, blinded_tail: None });
392 let mut payment_params = None;
393 read_tlv_fields!(reader, {
394 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
396 Ok(Route { paths, payment_params })
400 /// Parameters needed to find a [`Route`].
402 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
403 /// [`Event::PaymentPathFailed`].
405 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
406 #[derive(Clone, Debug, PartialEq, Eq)]
407 pub struct RouteParameters {
408 /// The parameters of the failed payment path.
409 pub payment_params: PaymentParameters,
411 /// The amount in msats sent on the failed payment path.
412 pub final_value_msat: u64,
415 impl Writeable for RouteParameters {
416 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
417 write_tlv_fields!(writer, {
418 (0, self.payment_params, required),
419 (2, self.final_value_msat, required),
420 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
421 // `RouteParameters` directly. For compatibility, we write it here.
422 (4, self.payment_params.final_cltv_expiry_delta, required),
428 impl Readable for RouteParameters {
429 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
430 _init_and_read_tlv_fields!(reader, {
431 (0, payment_params, (required: ReadableArgs, 0)),
432 (2, final_value_msat, required),
433 (4, final_cltv_expiry_delta, required),
435 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
436 if payment_params.final_cltv_expiry_delta == 0 {
437 payment_params.final_cltv_expiry_delta = final_cltv_expiry_delta.0.unwrap();
441 final_value_msat: final_value_msat.0.unwrap(),
446 /// Maximum total CTLV difference we allow for a full payment path.
447 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
449 /// Maximum number of paths we allow an (MPP) payment to have.
450 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
451 // limits, but for now more than 10 paths likely carries too much one-path failure.
452 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
454 // The median hop CLTV expiry delta currently seen in the network.
455 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
457 // During routing, we only consider paths shorter than our maximum length estimate.
458 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
459 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
460 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
462 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
463 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
464 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
465 // (payment_secret and total_msat) = 93 bytes for the final hop.
466 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
467 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
468 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
470 /// The recipient of a payment.
471 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
472 pub struct PaymentParameters {
473 /// The node id of the payee.
474 pub payee_pubkey: PublicKey,
476 /// Features supported by the payee.
478 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
479 /// does not contain any features.
481 /// [`for_keysend`]: Self::for_keysend
482 pub features: Option<InvoiceFeatures>,
484 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
485 pub route_hints: Hints,
487 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
488 pub expiry_time: Option<u64>,
490 /// The maximum total CLTV delta we accept for the route.
491 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
492 pub max_total_cltv_expiry_delta: u32,
494 /// The maximum number of paths that may be used by (MPP) payments.
495 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
496 pub max_path_count: u8,
498 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
499 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
500 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
501 /// increasing failure probability for those paths.
503 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
504 /// restriction have been found. While paths which meet this criteria will be searched for, it
505 /// is ultimately up to the scorer to select them over other paths.
507 /// A value of 0 will allow payments up to and including a channel's total announced usable
508 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
511 pub max_channel_saturation_power_of_half: u8,
513 /// A list of SCIDs which this payment was previously attempted over and which caused the
514 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
516 pub previously_failed_channels: Vec<u64>,
518 /// The minimum CLTV delta at the end of the route. This value must not be zero.
519 pub final_cltv_expiry_delta: u32,
522 impl Writeable for PaymentParameters {
523 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
524 let mut clear_hints = &vec![];
525 let mut blinded_hints = &vec![];
526 match &self.route_hints {
527 Hints::Clear(hints) => clear_hints = hints,
528 Hints::Blinded(hints) => blinded_hints = hints,
530 write_tlv_fields!(writer, {
531 (0, self.payee_pubkey, required),
532 (1, self.max_total_cltv_expiry_delta, required),
533 (2, self.features, option),
534 (3, self.max_path_count, required),
535 (4, *clear_hints, vec_type),
536 (5, self.max_channel_saturation_power_of_half, required),
537 (6, self.expiry_time, option),
538 (7, self.previously_failed_channels, vec_type),
539 (8, *blinded_hints, optional_vec),
540 (9, self.final_cltv_expiry_delta, required),
546 impl ReadableArgs<u32> for PaymentParameters {
547 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
548 _init_and_read_tlv_fields!(reader, {
549 (0, payee_pubkey, required),
550 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
551 (2, features, option),
552 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
553 (4, route_hints, vec_type),
554 (5, max_channel_saturation_power_of_half, (default_value, 2)),
555 (6, expiry_time, option),
556 (7, previously_failed_channels, vec_type),
557 (8, blinded_route_hints, optional_vec),
558 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
560 let clear_route_hints = route_hints.unwrap_or(vec![]);
561 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
562 let route_hints = if blinded_route_hints.len() != 0 {
563 if clear_route_hints.len() != 0 { return Err(DecodeError::InvalidValue) }
564 Hints::Blinded(blinded_route_hints)
566 Hints::Clear(clear_route_hints)
569 payee_pubkey: _init_tlv_based_struct_field!(payee_pubkey, required),
570 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
572 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
574 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
576 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
577 final_cltv_expiry_delta: _init_tlv_based_struct_field!(final_cltv_expiry_delta, (default_value, unused)),
583 impl PaymentParameters {
584 /// Creates a payee with the node id of the given `pubkey`.
586 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
588 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
592 route_hints: Hints::Clear(vec![]),
594 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
595 max_path_count: DEFAULT_MAX_PATH_COUNT,
596 max_channel_saturation_power_of_half: 2,
597 previously_failed_channels: Vec::new(),
598 final_cltv_expiry_delta,
602 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
604 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
606 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
607 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta).with_features(InvoiceFeatures::for_keysend())
610 /// Includes the payee's features.
612 /// This is not exported to bindings users since bindings don't support move semantics
613 pub fn with_features(self, features: InvoiceFeatures) -> Self {
614 Self { features: Some(features), ..self }
617 /// Includes hints for routing to the payee.
619 /// This is not exported to bindings users since bindings don't support move semantics
620 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
621 Self { route_hints: Hints::Clear(route_hints), ..self }
624 /// Includes a payment expiration in seconds relative to the UNIX epoch.
626 /// This is not exported to bindings users since bindings don't support move semantics
627 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
628 Self { expiry_time: Some(expiry_time), ..self }
631 /// Includes a limit for the total CLTV expiry delta which is considered during routing
633 /// This is not exported to bindings users since bindings don't support move semantics
634 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
635 Self { max_total_cltv_expiry_delta, ..self }
638 /// Includes a limit for the maximum number of payment paths that may be used.
640 /// This is not exported to bindings users since bindings don't support move semantics
641 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
642 Self { max_path_count, ..self }
645 /// Includes a limit for the maximum number of payment paths that may be used.
647 /// This is not exported to bindings users since bindings don't support move semantics
648 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
649 Self { max_channel_saturation_power_of_half, ..self }
653 /// Routing hints for the tail of the route.
654 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
656 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
657 /// will be included in the final [`Route`].
658 Blinded(Vec<(BlindedPayInfo, BlindedPath)>),
659 /// The recipient included these route hints in their BOLT11 invoice.
660 Clear(Vec<RouteHint>),
663 /// A list of hops along a payment path terminating with a channel to the recipient.
664 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
665 pub struct RouteHint(pub Vec<RouteHintHop>);
667 impl Writeable for RouteHint {
668 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
669 (self.0.len() as u64).write(writer)?;
670 for hop in self.0.iter() {
677 impl Readable for RouteHint {
678 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
679 let hop_count: u64 = Readable::read(reader)?;
680 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
681 for _ in 0..hop_count {
682 hops.push(Readable::read(reader)?);
688 /// A channel descriptor for a hop along a payment path.
689 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
690 pub struct RouteHintHop {
691 /// The node_id of the non-target end of the route
692 pub src_node_id: PublicKey,
693 /// The short_channel_id of this channel
694 pub short_channel_id: u64,
695 /// The fees which must be paid to use this channel
696 pub fees: RoutingFees,
697 /// The difference in CLTV values between this node and the next node.
698 pub cltv_expiry_delta: u16,
699 /// The minimum value, in msat, which must be relayed to the next hop.
700 pub htlc_minimum_msat: Option<u64>,
701 /// The maximum value in msat available for routing with a single HTLC.
702 pub htlc_maximum_msat: Option<u64>,
705 impl_writeable_tlv_based!(RouteHintHop, {
706 (0, src_node_id, required),
707 (1, htlc_minimum_msat, option),
708 (2, short_channel_id, required),
709 (3, htlc_maximum_msat, option),
711 (6, cltv_expiry_delta, required),
714 #[derive(Eq, PartialEq)]
715 struct RouteGraphNode {
717 lowest_fee_to_node: u64,
718 total_cltv_delta: u32,
719 // The maximum value a yet-to-be-constructed payment path might flow through this node.
720 // This value is upper-bounded by us by:
721 // - how much is needed for a path being constructed
722 // - how much value can channels following this node (up to the destination) can contribute,
723 // considering their capacity and fees
724 value_contribution_msat: u64,
725 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
726 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
727 path_htlc_minimum_msat: u64,
728 /// All penalties incurred from this hop on the way to the destination, as calculated using
730 path_penalty_msat: u64,
731 /// The number of hops walked up to this node.
732 path_length_to_node: u8,
735 impl cmp::Ord for RouteGraphNode {
736 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
737 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
738 .saturating_add(other.path_penalty_msat);
739 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
740 .saturating_add(self.path_penalty_msat);
741 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
745 impl cmp::PartialOrd for RouteGraphNode {
746 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
747 Some(self.cmp(other))
751 /// A wrapper around the various hop representations.
753 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
754 #[derive(Clone, Debug)]
755 enum CandidateRouteHop<'a> {
756 /// A hop from the payer, where the outbound liquidity is known.
758 details: &'a ChannelDetails,
760 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
762 info: DirectedChannelInfo<'a>,
763 short_channel_id: u64,
765 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
767 hint: &'a RouteHintHop,
771 impl<'a> CandidateRouteHop<'a> {
772 fn short_channel_id(&self) -> u64 {
774 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
775 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
776 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
780 // NOTE: This may alloc memory so avoid calling it in a hot code path.
781 fn features(&self) -> ChannelFeatures {
783 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
784 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
785 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
789 fn cltv_expiry_delta(&self) -> u32 {
791 CandidateRouteHop::FirstHop { .. } => 0,
792 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
793 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
797 fn htlc_minimum_msat(&self) -> u64 {
799 CandidateRouteHop::FirstHop { .. } => 0,
800 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
801 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
805 fn fees(&self) -> RoutingFees {
807 CandidateRouteHop::FirstHop { .. } => RoutingFees {
808 base_msat: 0, proportional_millionths: 0,
810 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
811 CandidateRouteHop::PrivateHop { hint } => hint.fees,
815 fn effective_capacity(&self) -> EffectiveCapacity {
817 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
818 liquidity_msat: details.next_outbound_htlc_limit_msat,
820 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
821 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
827 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
828 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
830 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
831 EffectiveCapacity::Infinite => u64::max_value(),
832 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
833 EffectiveCapacity::MaximumHTLC { amount_msat } =>
834 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
835 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
836 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
840 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
841 -> bool where I1::Item: PartialEq<I2::Item> {
843 let a = iter_a.next();
844 let b = iter_b.next();
845 if a.is_none() && b.is_none() { return true; }
846 if a.is_none() || b.is_none() { return false; }
847 if a.unwrap().ne(&b.unwrap()) { return false; }
851 /// It's useful to keep track of the hops associated with the fees required to use them,
852 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
853 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
854 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
856 struct PathBuildingHop<'a> {
857 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
858 // is a larger refactor and will require careful performance analysis.
860 candidate: CandidateRouteHop<'a>,
863 /// All the fees paid *after* this channel on the way to the destination
864 next_hops_fee_msat: u64,
865 /// Fee paid for the use of the current channel (see candidate.fees()).
866 /// The value will be actually deducted from the counterparty balance on the previous link.
867 hop_use_fee_msat: u64,
868 /// Used to compare channels when choosing the for routing.
869 /// Includes paying for the use of a hop and the following hops, as well as
870 /// an estimated cost of reaching this hop.
871 /// Might get stale when fees are recomputed. Primarily for internal use.
873 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
874 /// walk and may be invalid thereafter.
875 path_htlc_minimum_msat: u64,
876 /// All penalties incurred from this channel on the way to the destination, as calculated using
878 path_penalty_msat: u64,
879 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
880 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
881 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
882 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
883 /// avoid processing them again.
885 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
886 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
887 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
888 // value_contribution_msat, which requires tracking it here. See comments below where it is
889 // used for more info.
890 value_contribution_msat: u64,
893 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
894 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
895 let mut debug_struct = f.debug_struct("PathBuildingHop");
897 .field("node_id", &self.node_id)
898 .field("short_channel_id", &self.candidate.short_channel_id())
899 .field("total_fee_msat", &self.total_fee_msat)
900 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
901 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
902 .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)))
903 .field("path_penalty_msat", &self.path_penalty_msat)
904 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
905 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
906 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
907 let debug_struct = debug_struct
908 .field("value_contribution_msat", &self.value_contribution_msat);
909 debug_struct.finish()
913 // Instantiated with a list of hops with correct data in them collected during path finding,
914 // an instance of this struct should be further modified only via given methods.
916 struct PaymentPath<'a> {
917 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
920 impl<'a> PaymentPath<'a> {
921 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
922 fn get_value_msat(&self) -> u64 {
923 self.hops.last().unwrap().0.fee_msat
926 fn get_path_penalty_msat(&self) -> u64 {
927 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
930 fn get_total_fee_paid_msat(&self) -> u64 {
931 if self.hops.len() < 1 {
935 // Can't use next_hops_fee_msat because it gets outdated.
936 for (i, (hop, _)) in self.hops.iter().enumerate() {
937 if i != self.hops.len() - 1 {
938 result += hop.fee_msat;
944 fn get_cost_msat(&self) -> u64 {
945 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
948 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
949 // to change fees may result in an inconsistency.
951 // Sometimes we call this function right after constructing a path which is inconsistent in
952 // that it the value being transferred has decreased while we were doing path finding, leading
953 // to the fees being paid not lining up with the actual limits.
955 // Note that this function is not aware of the available_liquidity limit, and thus does not
956 // support increasing the value being transferred beyond what was selected during the initial
958 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
959 let mut total_fee_paid_msat = 0 as u64;
960 for i in (0..self.hops.len()).rev() {
961 let last_hop = i == self.hops.len() - 1;
963 // For non-last-hop, this value will represent the fees paid on the current hop. It
964 // will consist of the fees for the use of the next hop, and extra fees to match
965 // htlc_minimum_msat of the current channel. Last hop is handled separately.
966 let mut cur_hop_fees_msat = 0;
968 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
971 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
972 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
973 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
974 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
975 // set it too high just to maliciously take more fees by exploiting this
976 // match htlc_minimum_msat logic.
977 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
978 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
979 // Note that there is a risk that *previous hops* (those closer to us, as we go
980 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
982 // This might make us end up with a broken route, although this should be super-rare
983 // in practice, both because of how healthy channels look like, and how we pick
984 // channels in add_entry.
985 // Also, this can't be exploited more heavily than *announce a free path and fail
987 cur_hop_transferred_amount_msat += extra_fees_msat;
988 total_fee_paid_msat += extra_fees_msat;
989 cur_hop_fees_msat += extra_fees_msat;
993 // Final hop is a special case: it usually has just value_msat (by design), but also
994 // it still could overpay for the htlc_minimum_msat.
995 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
997 // Propagate updated fees for the use of the channels to one hop back, where they
998 // will be actually paid (fee_msat). The last hop is handled above separately.
999 cur_hop.fee_msat = cur_hop_fees_msat;
1002 // Fee for the use of the current hop which will be deducted on the previous hop.
1003 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1004 // this channel is free for us.
1006 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1007 cur_hop.hop_use_fee_msat = new_fee;
1008 total_fee_paid_msat += new_fee;
1010 // It should not be possible because this function is called only to reduce the
1011 // value. In that case, compute_fee was already called with the same fees for
1012 // larger amount and there was no overflow.
1021 /// Calculate the fees required to route the given amount over a channel with the given fees.
1022 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1023 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1024 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1028 /// Calculate the fees required to route the given amount over a channel with the given fees,
1029 /// saturating to [`u64::max_value`].
1030 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1031 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1032 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1033 .saturating_add(channel_fees.base_msat as u64)
1036 /// The default `features` we assume for a node in a route, when no `features` are known about that
1039 /// Default features are:
1040 /// * variable_length_onion_optional
1041 fn default_node_features() -> NodeFeatures {
1042 let mut features = NodeFeatures::empty();
1043 features.set_variable_length_onion_optional();
1047 /// Finds a route from us (payer) to the given target node (payee).
1049 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
1050 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1052 /// Private routing paths between a public node and the target may be included in `params.payee`.
1054 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1055 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1056 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1058 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1059 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1060 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1064 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
1065 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
1070 /// Panics if first_hops contains channels without short_channel_ids;
1071 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1073 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1074 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1075 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1076 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1077 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1078 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1079 scorer: &S, random_seed_bytes: &[u8; 32]
1080 ) -> Result<Route, LightningError>
1081 where L::Target: Logger, GL::Target: Logger {
1082 let graph_lock = network_graph.read_only();
1083 let final_cltv_expiry_delta = route_params.payment_params.final_cltv_expiry_delta;
1084 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1085 route_params.final_value_msat, final_cltv_expiry_delta, logger, scorer,
1086 random_seed_bytes)?;
1087 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1091 pub(crate) fn get_route<L: Deref, S: Score>(
1092 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1093 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
1094 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
1095 ) -> Result<Route, LightningError>
1096 where L::Target: Logger {
1097 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
1098 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1100 if payee_node_id == our_node_id {
1101 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1104 if final_value_msat > MAX_VALUE_MSAT {
1105 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1108 if final_value_msat == 0 {
1109 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1112 match &payment_params.route_hints {
1113 Hints::Clear(hints) => {
1114 for route in hints.iter() {
1115 for hop in &route.0 {
1116 if hop.src_node_id == payment_params.payee_pubkey {
1117 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1122 _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1125 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1126 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});
1129 // TODO: Remove the explicit final_cltv_expiry_delta parameter
1130 debug_assert_eq!(final_cltv_expiry_delta, payment_params.final_cltv_expiry_delta);
1132 // The general routing idea is the following:
1133 // 1. Fill first/last hops communicated by the caller.
1134 // 2. Attempt to construct a path from payer to payee for transferring
1135 // any ~sufficient (described later) value.
1136 // If succeed, remember which channels were used and how much liquidity they have available,
1137 // so that future paths don't rely on the same liquidity.
1138 // 3. Proceed to the next step if:
1139 // - we hit the recommended target value;
1140 // - OR if we could not construct a new path. Any next attempt will fail too.
1141 // Otherwise, repeat step 2.
1142 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1143 // (not recommended value).
1144 // 5. If yes, proceed. If not, fail routing.
1145 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1146 // transferred up to the transfer target value.
1147 // 7. Reduce the value of the last path until we are sending only the target value.
1148 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1149 // them so that we're not sending two HTLCs along the same path.
1151 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1152 // distance from the payee
1154 // We are not a faithful Dijkstra's implementation because we can change values which impact
1155 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1156 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1157 // the value we are currently attempting to send over a path, we simply reduce the value being
1158 // sent along the path for any hops after that channel. This may imply that later fees (which
1159 // we've already tabulated) are lower because a smaller value is passing through the channels
1160 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1161 // channels which were selected earlier (and which may still be used for other paths without a
1162 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1165 // One potentially problematic case for this algorithm would be if there are many
1166 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1167 // graph walking), we may never find a path which is not liquidity-limited and has lower
1168 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1169 // Because we only consider paths with at least 5% of the total value being sent, the damage
1170 // from such a case should be limited, however this could be further reduced in the future by
1171 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1172 // limits for the purposes of fee calculation.
1174 // Alternatively, we could store more detailed path information in the heap (targets, below)
1175 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1176 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1177 // and practically (as we would need to store dynamically-allocated path information in heap
1178 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1179 // results of such an algorithm would likely be biased towards lower-value paths.
1181 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1182 // outside of our current search value, running a path search more times to gather candidate
1183 // paths at different values. While this may be acceptable, further path searches may increase
1184 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1185 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1186 // the same time, remaining generic across different payment values.
1188 let network_channels = network_graph.channels();
1189 let network_nodes = network_graph.nodes();
1191 if payment_params.max_path_count == 0 {
1192 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1195 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1196 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1198 let allow_mpp = if payment_params.max_path_count == 1 {
1200 } else if let Some(features) = &payment_params.features {
1201 features.supports_basic_mpp()
1202 } else if let Some(node) = network_nodes.get(&payee_node_id) {
1203 if let Some(node_info) = node.announcement_info.as_ref() {
1204 node_info.features.supports_basic_mpp()
1208 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1209 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
1210 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1213 // Prepare the data we'll use for payee-to-payer search by
1214 // inserting first hops suggested by the caller as targets.
1215 // Our search will then attempt to reach them while traversing from the payee node.
1216 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1217 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1218 if let Some(hops) = first_hops {
1220 if chan.get_outbound_payment_scid().is_none() {
1221 panic!("first_hops should be filled in with usable channels, not pending ones");
1223 if chan.counterparty.node_id == *our_node_pubkey {
1224 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1227 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1228 .or_insert(Vec::new())
1231 if first_hop_targets.is_empty() {
1232 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1236 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1237 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1238 // adding duplicate entries when we find a better path to a given node.
1239 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1241 // Map from node_id to information about the best current path to that node, including feerate
1243 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1245 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1246 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1247 // htlc_minimum with extra fees while still finding a cheaper path.
1248 let mut hit_minimum_limit;
1250 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1251 // We start with a path_value of the exact amount we want, and if that generates a route we may
1252 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1253 // amount we want in total across paths, selecting the best subset at the end.
1254 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1255 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1256 let mut path_value_msat = final_value_msat;
1258 // Routing Fragmentation Mitigation heuristic:
1260 // Routing fragmentation across many payment paths increases the overall routing
1261 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1262 // Taking too many smaller paths also increases the chance of payment failure.
1263 // Thus to avoid this effect, we require from our collected links to provide
1264 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1265 // This requirement is currently set to be 1/max_path_count of the payment
1266 // value to ensure we only ever return routes that do not violate this limit.
1267 let minimal_value_contribution_msat: u64 = if allow_mpp {
1268 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1273 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1274 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1275 // drop the requirement by setting this to 0.
1276 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1278 // Keep track of how much liquidity has been used in selected channels. Used to determine
1279 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1280 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1281 // liquidity used in one direction will not offset any used in the opposite direction.
1282 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1283 HashMap::with_capacity(network_nodes.len());
1285 // Keeping track of how much value we already collected across other paths. Helps to decide
1286 // when we want to stop looking for new paths.
1287 let mut already_collected_value_msat = 0;
1289 for (_, channels) in first_hop_targets.iter_mut() {
1290 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1291 // most like to use.
1293 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1294 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1297 // Second, because simply always sorting in descending order would always use our largest
1298 // available outbound capacity, needlessly fragmenting our available channel capacities,
1299 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1300 // which have enough, but not too much, capacity for the payment.
1301 channels.sort_unstable_by(|chan_a, chan_b| {
1302 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1303 // Sort in descending order
1304 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1306 // Sort in ascending order
1307 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1312 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1314 macro_rules! add_entry {
1315 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1316 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1317 // since that value has to be transferred over this channel.
1318 // Returns whether this channel caused an update to `targets`.
1319 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1320 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1321 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1322 // We "return" whether we updated the path at the end, via this:
1323 let mut did_add_update_path_to_src_node = false;
1324 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1325 // practice these cases should be caught earlier:
1326 // - for regular channels at channel announcement (TODO)
1327 // - for first and last hops early in get_route
1328 if $src_node_id != $dest_node_id {
1329 let short_channel_id = $candidate.short_channel_id();
1330 let effective_capacity = $candidate.effective_capacity();
1331 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1333 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1334 // It may be misleading because we might later choose to reduce the value transferred
1335 // over these channels, and the channel which was insufficient might become sufficient.
1336 // Worst case: we drop a good channel here because it can't cover the high following
1337 // fees caused by one expensive channel, but then this channel could have been used
1338 // if the amount being transferred over this path is lower.
1339 // We do this for now, but this is a subject for removal.
1340 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1341 let used_liquidity_msat = used_channel_liquidities
1342 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1343 .map_or(0, |used_liquidity_msat| {
1344 available_value_contribution_msat = available_value_contribution_msat
1345 .saturating_sub(*used_liquidity_msat);
1346 *used_liquidity_msat
1349 // Verify the liquidity offered by this channel complies to the minimal contribution.
1350 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1351 // Do not consider candidate hops that would exceed the maximum path length.
1352 let path_length_to_node = $next_hops_path_length + 1;
1353 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1355 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1356 // In order to already account for some of the privacy enhancing random CLTV
1357 // expiry delta offset we add on top later, we subtract a rough estimate
1358 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1359 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1360 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1361 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1362 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1363 .saturating_add($candidate.cltv_expiry_delta());
1364 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1366 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1367 // Includes paying fees for the use of the following channels.
1368 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1369 Some(result) => result,
1370 // Can't overflow due to how the values were computed right above.
1371 None => unreachable!(),
1373 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1374 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1375 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1377 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1378 let may_overpay_to_meet_path_minimum_msat =
1379 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1380 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1381 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1382 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1384 let payment_failed_on_this_channel =
1385 payment_params.previously_failed_channels.contains(&short_channel_id);
1387 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1388 // bother considering this channel. If retrying with recommended_value_msat may
1389 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1390 // around again with a higher amount.
1391 if !contributes_sufficient_value || exceeds_max_path_length ||
1392 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1393 // Path isn't useful, ignore it and move on.
1394 } else if may_overpay_to_meet_path_minimum_msat {
1395 hit_minimum_limit = true;
1396 } else if over_path_minimum_msat {
1397 // Note that low contribution here (limited by available_liquidity_msat)
1398 // might violate htlc_minimum_msat on the hops which are next along the
1399 // payment path (upstream to the payee). To avoid that, we recompute
1400 // path fees knowing the final path contribution after constructing it.
1401 let path_htlc_minimum_msat = cmp::max(
1402 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1403 .saturating_add($next_hops_path_htlc_minimum_msat),
1404 $candidate.htlc_minimum_msat());
1405 let hm_entry = dist.entry($src_node_id);
1406 let old_entry = hm_entry.or_insert_with(|| {
1407 // If there was previously no known way to access the source node
1408 // (recall it goes payee-to-payer) of short_channel_id, first add a
1409 // semi-dummy record just to compute the fees to reach the source node.
1410 // This will affect our decision on selecting short_channel_id
1411 // as a way to reach the $dest_node_id.
1413 node_id: $dest_node_id.clone(),
1414 candidate: $candidate.clone(),
1416 next_hops_fee_msat: u64::max_value(),
1417 hop_use_fee_msat: u64::max_value(),
1418 total_fee_msat: u64::max_value(),
1419 path_htlc_minimum_msat,
1420 path_penalty_msat: u64::max_value(),
1421 was_processed: false,
1422 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1423 value_contribution_msat,
1427 #[allow(unused_mut)] // We only use the mut in cfg(test)
1428 let mut should_process = !old_entry.was_processed;
1429 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1431 // In test/fuzzing builds, we do extra checks to make sure the skipping
1432 // of already-seen nodes only happens in cases we expect (see below).
1433 if !should_process { should_process = true; }
1437 let mut hop_use_fee_msat = 0;
1438 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1440 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1441 // will have the same effective-fee
1442 if $src_node_id != our_node_id {
1443 // Note that `u64::max_value` means we'll always fail the
1444 // `old_entry.total_fee_msat > total_fee_msat` check below
1445 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1446 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1449 let channel_usage = ChannelUsage {
1450 amount_msat: amount_to_transfer_over_msat,
1451 inflight_htlc_msat: used_liquidity_msat,
1454 let channel_penalty_msat = scorer.channel_penalty_msat(
1455 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1457 let path_penalty_msat = $next_hops_path_penalty_msat
1458 .saturating_add(channel_penalty_msat);
1459 let new_graph_node = RouteGraphNode {
1460 node_id: $src_node_id,
1461 lowest_fee_to_node: total_fee_msat,
1462 total_cltv_delta: hop_total_cltv_delta,
1463 value_contribution_msat,
1464 path_htlc_minimum_msat,
1466 path_length_to_node,
1469 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1470 // if this way is cheaper than the already known
1471 // (considering the cost to "reach" this channel from the route destination,
1472 // the cost of using this channel,
1473 // and the cost of routing to the source node of this channel).
1474 // Also, consider that htlc_minimum_msat_difference, because we might end up
1475 // paying it. Consider the following exploit:
1476 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1477 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1478 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1479 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1481 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1482 // but it may require additional tracking - we don't want to double-count
1483 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1484 // can't use something that may decrease on future hops.
1485 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1486 .saturating_add(old_entry.path_penalty_msat);
1487 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1488 .saturating_add(path_penalty_msat);
1490 if !old_entry.was_processed && new_cost < old_cost {
1491 targets.push(new_graph_node);
1492 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1493 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1494 old_entry.total_fee_msat = total_fee_msat;
1495 old_entry.node_id = $dest_node_id.clone();
1496 old_entry.candidate = $candidate.clone();
1497 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1498 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1499 old_entry.path_penalty_msat = path_penalty_msat;
1500 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1502 old_entry.value_contribution_msat = value_contribution_msat;
1504 did_add_update_path_to_src_node = true;
1505 } else if old_entry.was_processed && new_cost < old_cost {
1506 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1508 // If we're skipping processing a node which was previously
1509 // processed even though we found another path to it with a
1510 // cheaper fee, check that it was because the second path we
1511 // found (which we are processing now) has a lower value
1512 // contribution due to an HTLC minimum limit.
1514 // e.g. take a graph with two paths from node 1 to node 2, one
1515 // through channel A, and one through channel B. Channel A and
1516 // B are both in the to-process heap, with their scores set by
1517 // a higher htlc_minimum than fee.
1518 // Channel A is processed first, and the channels onwards from
1519 // node 1 are added to the to-process heap. Thereafter, we pop
1520 // Channel B off of the heap, note that it has a much more
1521 // restrictive htlc_maximum_msat, and recalculate the fees for
1522 // all of node 1's channels using the new, reduced, amount.
1524 // This would be bogus - we'd be selecting a higher-fee path
1525 // with a lower htlc_maximum_msat instead of the one we'd
1526 // already decided to use.
1527 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1529 value_contribution_msat + path_penalty_msat <
1530 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1538 did_add_update_path_to_src_node
1542 let default_node_features = default_node_features();
1544 // Find ways (channels with destination) to reach a given node and store them
1545 // in the corresponding data structures (routing graph etc).
1546 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1547 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1548 // This data can later be helpful to optimize routing (pay lower fees).
1549 macro_rules! add_entries_to_cheapest_to_target_node {
1550 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1551 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1552 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1553 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1554 let was_processed = elem.was_processed;
1555 elem.was_processed = true;
1558 // Entries are added to dist in add_entry!() when there is a channel from a node.
1559 // Because there are no channels from payee, it will not have a dist entry at this point.
1560 // If we're processing any other node, it is always be the result of a channel from it.
1561 assert_eq!($node_id, payee_node_id);
1566 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1567 for details in first_channels {
1568 let candidate = CandidateRouteHop::FirstHop { details };
1569 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1570 $next_hops_value_contribution,
1571 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1572 $next_hops_cltv_delta, $next_hops_path_length);
1576 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1579 &default_node_features
1582 if !features.requires_unknown_bits() {
1583 for chan_id in $node.channels.iter() {
1584 let chan = network_channels.get(chan_id).unwrap();
1585 if !chan.features.requires_unknown_bits() {
1586 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1587 if first_hops.is_none() || *source != our_node_id {
1588 if directed_channel.direction().enabled {
1589 let candidate = CandidateRouteHop::PublicHop {
1590 info: directed_channel,
1591 short_channel_id: *chan_id,
1593 add_entry!(candidate, *source, $node_id,
1594 $fee_to_target_msat,
1595 $next_hops_value_contribution,
1596 $next_hops_path_htlc_minimum_msat,
1597 $next_hops_path_penalty_msat,
1598 $next_hops_cltv_delta, $next_hops_path_length);
1609 let mut payment_paths = Vec::<PaymentPath>::new();
1611 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1612 'paths_collection: loop {
1613 // For every new path, start from scratch, except for used_channel_liquidities, which
1614 // helps to avoid reusing previously selected paths in future iterations.
1617 hit_minimum_limit = false;
1619 // If first hop is a private channel and the only way to reach the payee, this is the only
1620 // place where it could be added.
1621 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1622 for details in first_channels {
1623 let candidate = CandidateRouteHop::FirstHop { details };
1624 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1626 log_trace!(logger, "{} direct route to payee via SCID {}",
1627 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1631 // Add the payee as a target, so that the payee-to-payer
1632 // search algorithm knows what to start with.
1633 match network_nodes.get(&payee_node_id) {
1634 // The payee is not in our network graph, so nothing to add here.
1635 // There is still a chance of reaching them via last_hops though,
1636 // so don't yet fail the payment here.
1637 // If not, targets.pop() will not even let us enter the loop in step 2.
1640 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1645 // If a caller provided us with last hops, add them to routing targets. Since this happens
1646 // earlier than general path finding, they will be somewhat prioritized, although currently
1647 // it matters only if the fees are exactly the same.
1648 let route_hints = match &payment_params.route_hints {
1649 Hints::Clear(hints) => hints,
1650 _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1652 for route in route_hints.iter().filter(|route| !route.0.is_empty()) {
1653 let first_hop_in_route = &(route.0)[0];
1654 let have_hop_src_in_graph =
1655 // Only add the hops in this route to our candidate set if either
1656 // we have a direct channel to the first hop or the first hop is
1657 // in the regular network graph.
1658 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1659 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1660 if have_hop_src_in_graph {
1661 // We start building the path from reverse, i.e., from payee
1662 // to the first RouteHintHop in the path.
1663 let hop_iter = route.0.iter().rev();
1664 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1665 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1666 let mut hop_used = true;
1667 let mut aggregate_next_hops_fee_msat: u64 = 0;
1668 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1669 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1670 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1671 let mut aggregate_next_hops_path_length: u8 = 0;
1673 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1674 let source = NodeId::from_pubkey(&hop.src_node_id);
1675 let target = NodeId::from_pubkey(&prev_hop_id);
1676 let candidate = network_channels
1677 .get(&hop.short_channel_id)
1678 .and_then(|channel| channel.as_directed_to(&target))
1679 .map(|(info, _)| CandidateRouteHop::PublicHop {
1681 short_channel_id: hop.short_channel_id,
1683 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1685 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1686 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1687 aggregate_next_hops_path_penalty_msat,
1688 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1689 // If this hop was not used then there is no use checking the preceding
1690 // hops in the RouteHint. We can break by just searching for a direct
1691 // channel between last checked hop and first_hop_targets.
1695 let used_liquidity_msat = used_channel_liquidities
1696 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1697 let channel_usage = ChannelUsage {
1698 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1699 inflight_htlc_msat: used_liquidity_msat,
1700 effective_capacity: candidate.effective_capacity(),
1702 let channel_penalty_msat = scorer.channel_penalty_msat(
1703 hop.short_channel_id, &source, &target, channel_usage
1705 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1706 .saturating_add(channel_penalty_msat);
1708 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1709 .saturating_add(hop.cltv_expiry_delta as u32);
1711 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1714 // Searching for a direct channel between last checked hop and first_hop_targets
1715 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1716 for details in first_channels {
1717 let candidate = CandidateRouteHop::FirstHop { details };
1718 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1719 aggregate_next_hops_fee_msat, path_value_msat,
1720 aggregate_next_hops_path_htlc_minimum_msat,
1721 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1722 aggregate_next_hops_path_length);
1730 // In the next values of the iterator, the aggregate fees already reflects
1731 // the sum of value sent from payer (final_value_msat) and routing fees
1732 // for the last node in the RouteHint. We need to just add the fees to
1733 // route through the current node so that the preceding node (next iteration)
1735 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1736 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1737 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1739 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1740 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1741 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1742 .checked_add(hop_htlc_minimum_msat_inc);
1743 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1745 if idx == route.0.len() - 1 {
1746 // The last hop in this iterator is the first hop in
1747 // overall RouteHint.
1748 // If this hop connects to a node with which we have a direct channel,
1749 // ignore the network graph and, if the last hop was added, add our
1750 // direct channel to the candidate set.
1752 // Note that we *must* check if the last hop was added as `add_entry`
1753 // always assumes that the third argument is a node to which we have a
1755 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1756 for details in first_channels {
1757 let candidate = CandidateRouteHop::FirstHop { details };
1758 add_entry!(candidate, our_node_id,
1759 NodeId::from_pubkey(&hop.src_node_id),
1760 aggregate_next_hops_fee_msat, path_value_msat,
1761 aggregate_next_hops_path_htlc_minimum_msat,
1762 aggregate_next_hops_path_penalty_msat,
1763 aggregate_next_hops_cltv_delta,
1764 aggregate_next_hops_path_length);
1772 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1774 // At this point, targets are filled with the data from first and
1775 // last hops communicated by the caller, and the payment receiver.
1776 let mut found_new_path = false;
1779 // If this loop terminates due the exhaustion of targets, two situations are possible:
1780 // - not enough outgoing liquidity:
1781 // 0 < already_collected_value_msat < final_value_msat
1782 // - enough outgoing liquidity:
1783 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1784 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1785 // paths_collection will be stopped because found_new_path==false.
1786 // This is not necessarily a routing failure.
1787 '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() {
1789 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1790 // traversing the graph and arrange the path out of what we found.
1791 if node_id == our_node_id {
1792 let mut new_entry = dist.remove(&our_node_id).unwrap();
1793 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1796 let mut features_set = false;
1797 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1798 for details in first_channels {
1799 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1800 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1801 features_set = true;
1807 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1808 if let Some(node_info) = node.announcement_info.as_ref() {
1809 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1811 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1814 // We can fill in features for everything except hops which were
1815 // provided via the invoice we're paying. We could guess based on the
1816 // recipient's features but for now we simply avoid guessing at all.
1820 // Means we succesfully traversed from the payer to the payee, now
1821 // save this path for the payment route. Also, update the liquidity
1822 // remaining on the used hops, so that we take them into account
1823 // while looking for more paths.
1824 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1828 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1829 Some(payment_hop) => payment_hop,
1830 // We can't arrive at None because, if we ever add an entry to targets,
1831 // we also fill in the entry in dist (see add_entry!).
1832 None => unreachable!(),
1834 // We "propagate" the fees one hop backward (topologically) here,
1835 // so that fees paid for a HTLC forwarding on the current channel are
1836 // associated with the previous channel (where they will be subtracted).
1837 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1838 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1840 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1841 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1843 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1844 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1846 let mut payment_path = PaymentPath {hops: ordered_hops};
1848 // We could have possibly constructed a slightly inconsistent path: since we reduce
1849 // value being transferred along the way, we could have violated htlc_minimum_msat
1850 // on some channels we already passed (assuming dest->source direction). Here, we
1851 // recompute the fees again, so that if that's the case, we match the currently
1852 // underpaid htlc_minimum_msat with fees.
1853 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1854 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1855 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1857 // Since a path allows to transfer as much value as
1858 // the smallest channel it has ("bottleneck"), we should recompute
1859 // the fees so sender HTLC don't overpay fees when traversing
1860 // larger channels than the bottleneck. This may happen because
1861 // when we were selecting those channels we were not aware how much value
1862 // this path will transfer, and the relative fee for them
1863 // might have been computed considering a larger value.
1864 // Remember that we used these channels so that we don't rely
1865 // on the same liquidity in future paths.
1866 let mut prevented_redundant_path_selection = false;
1867 let prev_hop_iter = core::iter::once(&our_node_id)
1868 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1869 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1870 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1871 let used_liquidity_msat = used_channel_liquidities
1872 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1873 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1874 .or_insert(spent_on_hop_msat);
1875 let hop_capacity = hop.candidate.effective_capacity();
1876 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1877 if *used_liquidity_msat == hop_max_msat {
1878 // If this path used all of this channel's available liquidity, we know
1879 // this path will not be selected again in the next loop iteration.
1880 prevented_redundant_path_selection = true;
1882 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1884 if !prevented_redundant_path_selection {
1885 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1886 // we'll probably end up picking the same path again on the next iteration.
1887 // Decrease the available liquidity of a hop in the middle of the path.
1888 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1889 let exhausted = u64::max_value();
1890 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1891 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1892 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1895 // Track the total amount all our collected paths allow to send so that we know
1896 // when to stop looking for more paths
1897 already_collected_value_msat += value_contribution_msat;
1899 payment_paths.push(payment_path);
1900 found_new_path = true;
1901 break 'path_construction;
1904 // If we found a path back to the payee, we shouldn't try to process it again. This is
1905 // the equivalent of the `elem.was_processed` check in
1906 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1907 if node_id == payee_node_id { continue 'path_construction; }
1909 // Otherwise, since the current target node is not us,
1910 // keep "unrolling" the payment graph from payee to payer by
1911 // finding a way to reach the current target from the payer side.
1912 match network_nodes.get(&node_id) {
1915 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1916 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1917 total_cltv_delta, path_length_to_node);
1923 if !found_new_path && channel_saturation_pow_half != 0 {
1924 channel_saturation_pow_half = 0;
1925 continue 'paths_collection;
1927 // If we don't support MPP, no use trying to gather more value ever.
1928 break 'paths_collection;
1932 // Stop either when the recommended value is reached or if no new path was found in this
1934 // In the latter case, making another path finding attempt won't help,
1935 // because we deterministically terminated the search due to low liquidity.
1936 if !found_new_path && channel_saturation_pow_half != 0 {
1937 channel_saturation_pow_half = 0;
1938 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1939 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1940 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1941 break 'paths_collection;
1942 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1943 // Further, if this was our first walk of the graph, and we weren't limited by an
1944 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1945 // limited by an htlc_minimum_msat value, find another path with a higher value,
1946 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1947 // still keeping a lower total fee than this path.
1948 if !hit_minimum_limit {
1949 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1950 break 'paths_collection;
1952 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1953 path_value_msat = recommended_value_msat;
1958 if payment_paths.len() == 0 {
1959 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1962 if already_collected_value_msat < final_value_msat {
1963 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1967 let mut selected_route = payment_paths;
1969 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1970 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1972 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1973 // the value they contribute towards the payment amount.
1974 // We sort in descending order as we will remove from the front in `retain`, next.
1975 selected_route.sort_unstable_by(|a, b|
1976 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
1977 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
1980 // We should make sure that at least 1 path left.
1981 let mut paths_left = selected_route.len();
1982 selected_route.retain(|path| {
1983 if paths_left == 1 {
1986 let path_value_msat = path.get_value_msat();
1987 if path_value_msat <= overpaid_value_msat {
1988 overpaid_value_msat -= path_value_msat;
1994 debug_assert!(selected_route.len() > 0);
1996 if overpaid_value_msat != 0 {
1998 // Now, subtract the remaining overpaid value from the most-expensive path.
1999 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2000 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2001 selected_route.sort_unstable_by(|a, b| {
2002 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2003 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2004 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2006 let expensive_payment_path = selected_route.first_mut().unwrap();
2008 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2009 // can't go negative.
2010 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2011 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2015 // Sort by the path itself and combine redundant paths.
2016 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2017 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2019 selected_route.sort_unstable_by_key(|path| {
2020 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
2021 debug_assert!(path.hops.len() <= key.len());
2022 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
2027 for idx in 0..(selected_route.len() - 1) {
2028 if idx + 1 >= selected_route.len() { break; }
2029 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
2030 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
2031 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2032 selected_route[idx].update_value_and_recompute_fees(new_value);
2033 selected_route.remove(idx + 1);
2037 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
2038 for payment_path in selected_route {
2039 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
2041 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)})?,
2042 node_features: node_features.clone(),
2043 short_channel_id: payment_hop.candidate.short_channel_id(),
2044 channel_features: payment_hop.candidate.features(),
2045 fee_msat: payment_hop.fee_msat,
2046 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
2048 }).collect::<Vec<_>>();
2049 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2050 // applicable for the previous hop.
2051 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
2052 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
2054 selected_paths.push(path);
2056 // Make sure we would never create a route with more paths than we allow.
2057 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
2059 if let Some(features) = &payment_params.features {
2060 for path in selected_paths.iter_mut() {
2061 if let Ok(route_hop) = path.last_mut().unwrap() {
2062 route_hop.node_features = features.to_context();
2067 let mut paths: Vec<Path> = Vec::new();
2068 for results_vec in selected_paths {
2069 let mut hops = Vec::with_capacity(results_vec.len());
2070 for res in results_vec { hops.push(res?); }
2071 paths.push(Path { hops, blinded_tail: None });
2075 payment_params: Some(payment_params.clone()),
2077 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
2081 // When an adversarial intermediary node observes a payment, it may be able to infer its
2082 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2083 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2084 // payment path by adding a randomized 'shadow route' offset to the final hop.
2085 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2086 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2088 let network_channels = network_graph.channels();
2089 let network_nodes = network_graph.nodes();
2091 for path in route.paths.iter_mut() {
2092 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2094 // Remember the last three nodes of the random walk and avoid looping back on them.
2095 // Init with the last three nodes from the actual path, if possible.
2096 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2097 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2098 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2100 // Choose the last publicly known node as the starting point for the random walk.
2101 let mut cur_hop: Option<NodeId> = None;
2102 let mut path_nonce = [0u8; 12];
2103 if let Some(starting_hop) = path.hops.iter().rev()
2104 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2105 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2106 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2109 // Init PRNG with the path-dependant nonce, which is static for private paths.
2110 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2111 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2113 // Pick a random path length in [1 .. 3]
2114 prng.process_in_place(&mut random_path_bytes);
2115 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2117 for random_hop in 0..random_walk_length {
2118 // If we don't find a suitable offset in the public network graph, we default to
2119 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2120 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2122 if let Some(cur_node_id) = cur_hop {
2123 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2124 // Randomly choose the next unvisited hop.
2125 prng.process_in_place(&mut random_path_bytes);
2126 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2127 .checked_rem(cur_node.channels.len())
2128 .and_then(|index| cur_node.channels.get(index))
2129 .and_then(|id| network_channels.get(id)) {
2130 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2131 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2132 nodes_to_avoid[random_hop] = *next_id;
2133 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2134 cur_hop = Some(*next_id);
2141 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2142 .checked_add(random_hop_offset)
2143 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2146 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2147 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2148 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2150 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2151 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2152 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2153 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2154 max_path_offset = cmp::max(
2155 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2156 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2157 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2159 // Add 'shadow' CLTV offset to the final hop
2160 if let Some(last_hop) = path.hops.last_mut() {
2161 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2162 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2167 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2168 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2170 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2171 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2172 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2173 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2174 ) -> Result<Route, LightningError>
2175 where L::Target: Logger, GL::Target: Logger {
2176 let graph_lock = network_graph.read_only();
2177 let mut route = build_route_from_hops_internal(
2178 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2179 route_params.final_value_msat, route_params.payment_params.final_cltv_expiry_delta,
2180 logger, random_seed_bytes)?;
2181 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2185 fn build_route_from_hops_internal<L: Deref>(
2186 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2187 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
2188 logger: L, random_seed_bytes: &[u8; 32]
2189 ) -> Result<Route, LightningError> where L::Target: Logger {
2192 our_node_id: NodeId,
2193 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2196 impl Score for HopScorer {
2197 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2198 _usage: ChannelUsage) -> u64
2200 let mut cur_id = self.our_node_id;
2201 for i in 0..self.hop_ids.len() {
2202 if let Some(next_id) = self.hop_ids[i] {
2203 if cur_id == *source && next_id == *target {
2214 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2216 fn payment_path_successful(&mut self, _path: &Path) {}
2218 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2220 fn probe_successful(&mut self, _path: &Path) {}
2223 impl<'a> Writeable for HopScorer {
2225 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2230 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2231 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2234 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2235 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2236 for i in 0..hops.len() {
2237 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2240 let scorer = HopScorer { our_node_id, hop_ids };
2242 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2243 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
2248 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2249 use crate::routing::utxo::UtxoResult;
2250 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2251 Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2252 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2253 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
2254 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2255 use crate::chain::transaction::OutPoint;
2256 use crate::chain::keysinterface::EntropySource;
2257 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2258 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2259 use crate::ln::channelmanager;
2260 use crate::util::config::UserConfig;
2261 use crate::util::test_utils as ln_test_utils;
2262 use crate::util::chacha20::ChaCha20;
2264 use crate::util::ser::{Writeable, Writer};
2266 use bitcoin::hashes::Hash;
2267 use bitcoin::network::constants::Network;
2268 use bitcoin::blockdata::constants::genesis_block;
2269 use bitcoin::blockdata::script::Builder;
2270 use bitcoin::blockdata::opcodes;
2271 use bitcoin::blockdata::transaction::TxOut;
2275 use bitcoin::secp256k1::{PublicKey,SecretKey};
2276 use bitcoin::secp256k1::Secp256k1;
2278 use crate::prelude::*;
2279 use crate::sync::Arc;
2281 use core::convert::TryInto;
2283 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2284 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2285 channelmanager::ChannelDetails {
2286 channel_id: [0; 32],
2287 counterparty: channelmanager::ChannelCounterparty {
2290 unspendable_punishment_reserve: 0,
2291 forwarding_info: None,
2292 outbound_htlc_minimum_msat: None,
2293 outbound_htlc_maximum_msat: None,
2295 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2298 outbound_scid_alias: None,
2299 inbound_scid_alias: None,
2300 channel_value_satoshis: 0,
2303 outbound_capacity_msat,
2304 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2305 inbound_capacity_msat: 42,
2306 unspendable_punishment_reserve: None,
2307 confirmations_required: None,
2308 confirmations: None,
2309 force_close_spend_delay: None,
2310 is_outbound: true, is_channel_ready: true,
2311 is_usable: true, is_public: true,
2312 inbound_htlc_minimum_msat: None,
2313 inbound_htlc_maximum_msat: None,
2315 feerate_sat_per_1000_weight: None
2320 fn simple_route_test() {
2321 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2322 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2323 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2324 let scorer = ln_test_utils::TestScorer::new();
2325 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2326 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2328 // Simple route to 2 via 1
2330 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) {
2331 assert_eq!(err, "Cannot send a payment of 0 msat");
2332 } else { panic!(); }
2334 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2335 assert_eq!(route.paths[0].hops.len(), 2);
2337 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2338 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2339 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2340 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2341 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2342 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2344 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2345 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2346 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2347 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2348 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2349 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2353 fn invalid_first_hop_test() {
2354 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2355 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2356 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2357 let scorer = ln_test_utils::TestScorer::new();
2358 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2359 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2361 // Simple route to 2 via 1
2363 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2365 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2366 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) {
2367 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2368 } else { panic!(); }
2370 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2371 assert_eq!(route.paths[0].hops.len(), 2);
2375 fn htlc_minimum_test() {
2376 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2377 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2378 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2379 let scorer = ln_test_utils::TestScorer::new();
2380 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2381 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2383 // Simple route to 2 via 1
2385 // Disable other paths
2386 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2388 short_channel_id: 12,
2390 flags: 2, // to disable
2391 cltv_expiry_delta: 0,
2392 htlc_minimum_msat: 0,
2393 htlc_maximum_msat: MAX_VALUE_MSAT,
2395 fee_proportional_millionths: 0,
2396 excess_data: Vec::new()
2398 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2400 short_channel_id: 3,
2402 flags: 2, // to disable
2403 cltv_expiry_delta: 0,
2404 htlc_minimum_msat: 0,
2405 htlc_maximum_msat: MAX_VALUE_MSAT,
2407 fee_proportional_millionths: 0,
2408 excess_data: Vec::new()
2410 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2412 short_channel_id: 13,
2414 flags: 2, // to disable
2415 cltv_expiry_delta: 0,
2416 htlc_minimum_msat: 0,
2417 htlc_maximum_msat: MAX_VALUE_MSAT,
2419 fee_proportional_millionths: 0,
2420 excess_data: Vec::new()
2422 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2424 short_channel_id: 6,
2426 flags: 2, // to disable
2427 cltv_expiry_delta: 0,
2428 htlc_minimum_msat: 0,
2429 htlc_maximum_msat: MAX_VALUE_MSAT,
2431 fee_proportional_millionths: 0,
2432 excess_data: Vec::new()
2434 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2436 short_channel_id: 7,
2438 flags: 2, // to disable
2439 cltv_expiry_delta: 0,
2440 htlc_minimum_msat: 0,
2441 htlc_maximum_msat: MAX_VALUE_MSAT,
2443 fee_proportional_millionths: 0,
2444 excess_data: Vec::new()
2447 // Check against amount_to_transfer_over_msat.
2448 // Set minimal HTLC of 200_000_000 msat.
2449 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2451 short_channel_id: 2,
2454 cltv_expiry_delta: 0,
2455 htlc_minimum_msat: 200_000_000,
2456 htlc_maximum_msat: MAX_VALUE_MSAT,
2458 fee_proportional_millionths: 0,
2459 excess_data: Vec::new()
2462 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2464 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2466 short_channel_id: 4,
2469 cltv_expiry_delta: 0,
2470 htlc_minimum_msat: 0,
2471 htlc_maximum_msat: 199_999_999,
2473 fee_proportional_millionths: 0,
2474 excess_data: Vec::new()
2477 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2478 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) {
2479 assert_eq!(err, "Failed to find a path to the given destination");
2480 } else { panic!(); }
2482 // Lift the restriction on the first hop.
2483 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2485 short_channel_id: 2,
2488 cltv_expiry_delta: 0,
2489 htlc_minimum_msat: 0,
2490 htlc_maximum_msat: MAX_VALUE_MSAT,
2492 fee_proportional_millionths: 0,
2493 excess_data: Vec::new()
2496 // A payment above the minimum should pass
2497 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();
2498 assert_eq!(route.paths[0].hops.len(), 2);
2502 fn htlc_minimum_overpay_test() {
2503 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2504 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2505 let config = UserConfig::default();
2506 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
2507 let scorer = ln_test_utils::TestScorer::new();
2508 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2509 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2511 // A route to node#2 via two paths.
2512 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2513 // Thus, they can't send 60 without overpaying.
2514 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2516 short_channel_id: 2,
2519 cltv_expiry_delta: 0,
2520 htlc_minimum_msat: 35_000,
2521 htlc_maximum_msat: 40_000,
2523 fee_proportional_millionths: 0,
2524 excess_data: Vec::new()
2526 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2528 short_channel_id: 12,
2531 cltv_expiry_delta: 0,
2532 htlc_minimum_msat: 35_000,
2533 htlc_maximum_msat: 40_000,
2535 fee_proportional_millionths: 0,
2536 excess_data: Vec::new()
2540 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2541 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2542 short_channel_id: 13,
2545 cltv_expiry_delta: 0,
2546 htlc_minimum_msat: 0,
2547 htlc_maximum_msat: MAX_VALUE_MSAT,
2549 fee_proportional_millionths: 0,
2550 excess_data: Vec::new()
2552 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2553 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2554 short_channel_id: 4,
2557 cltv_expiry_delta: 0,
2558 htlc_minimum_msat: 0,
2559 htlc_maximum_msat: MAX_VALUE_MSAT,
2561 fee_proportional_millionths: 0,
2562 excess_data: Vec::new()
2565 // Disable other paths
2566 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2567 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2568 short_channel_id: 1,
2570 flags: 2, // to disable
2571 cltv_expiry_delta: 0,
2572 htlc_minimum_msat: 0,
2573 htlc_maximum_msat: MAX_VALUE_MSAT,
2575 fee_proportional_millionths: 0,
2576 excess_data: Vec::new()
2579 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2580 // Overpay fees to hit htlc_minimum_msat.
2581 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2582 // TODO: this could be better balanced to overpay 10k and not 15k.
2583 assert_eq!(overpaid_fees, 15_000);
2585 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2586 // while taking even more fee to match htlc_minimum_msat.
2587 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2588 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2589 short_channel_id: 12,
2592 cltv_expiry_delta: 0,
2593 htlc_minimum_msat: 65_000,
2594 htlc_maximum_msat: 80_000,
2596 fee_proportional_millionths: 0,
2597 excess_data: Vec::new()
2599 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2601 short_channel_id: 2,
2604 cltv_expiry_delta: 0,
2605 htlc_minimum_msat: 0,
2606 htlc_maximum_msat: MAX_VALUE_MSAT,
2608 fee_proportional_millionths: 0,
2609 excess_data: Vec::new()
2611 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2612 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2613 short_channel_id: 4,
2616 cltv_expiry_delta: 0,
2617 htlc_minimum_msat: 0,
2618 htlc_maximum_msat: MAX_VALUE_MSAT,
2620 fee_proportional_millionths: 100_000,
2621 excess_data: Vec::new()
2624 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2625 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2626 assert_eq!(route.paths.len(), 1);
2627 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
2628 let fees = route.paths[0].hops[0].fee_msat;
2629 assert_eq!(fees, 5_000);
2631 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2632 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2633 // the other channel.
2634 assert_eq!(route.paths.len(), 1);
2635 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2636 let fees = route.paths[0].hops[0].fee_msat;
2637 assert_eq!(fees, 5_000);
2641 fn disable_channels_test() {
2642 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2643 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2644 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2645 let scorer = ln_test_utils::TestScorer::new();
2646 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2647 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2649 // // Disable channels 4 and 12 by flags=2
2650 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2652 short_channel_id: 4,
2654 flags: 2, // to disable
2655 cltv_expiry_delta: 0,
2656 htlc_minimum_msat: 0,
2657 htlc_maximum_msat: MAX_VALUE_MSAT,
2659 fee_proportional_millionths: 0,
2660 excess_data: Vec::new()
2662 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2663 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2664 short_channel_id: 12,
2666 flags: 2, // to disable
2667 cltv_expiry_delta: 0,
2668 htlc_minimum_msat: 0,
2669 htlc_maximum_msat: MAX_VALUE_MSAT,
2671 fee_proportional_millionths: 0,
2672 excess_data: Vec::new()
2675 // If all the channels require some features we don't understand, route should fail
2676 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
2677 assert_eq!(err, "Failed to find a path to the given destination");
2678 } else { panic!(); }
2680 // If we specify a channel to node7, that overrides our local channel view and that gets used
2681 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2682 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2683 assert_eq!(route.paths[0].hops.len(), 2);
2685 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
2686 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
2687 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2688 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
2689 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2690 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2692 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2693 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
2694 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2695 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2696 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2697 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
2701 fn disable_node_test() {
2702 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2703 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2704 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2705 let scorer = ln_test_utils::TestScorer::new();
2706 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2707 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2709 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2710 let mut unknown_features = NodeFeatures::empty();
2711 unknown_features.set_unknown_feature_required();
2712 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2713 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2714 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2716 // If all nodes require some features we don't understand, route should fail
2717 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) {
2718 assert_eq!(err, "Failed to find a path to the given destination");
2719 } else { panic!(); }
2721 // If we specify a channel to node7, that overrides our local channel view and that gets used
2722 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2723 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();
2724 assert_eq!(route.paths[0].hops.len(), 2);
2726 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
2727 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
2728 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2729 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
2730 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2731 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2733 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2734 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
2735 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2736 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2737 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2738 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
2740 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2741 // naively) assume that the user checked the feature bits on the invoice, which override
2742 // the node_announcement.
2746 fn our_chans_test() {
2747 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2748 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2749 let scorer = ln_test_utils::TestScorer::new();
2750 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2751 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2753 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2754 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
2755 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2756 assert_eq!(route.paths[0].hops.len(), 3);
2758 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2759 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2760 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2761 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2762 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2763 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2765 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2766 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2767 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2768 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
2769 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2770 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2772 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
2773 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
2774 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
2775 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
2776 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
2777 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
2779 // If we specify a channel to node7, that overrides our local channel view and that gets used
2780 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2781 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2782 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();
2783 assert_eq!(route.paths[0].hops.len(), 2);
2785 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
2786 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
2787 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2788 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
2789 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
2790 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2792 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2793 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
2794 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2795 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2796 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2797 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
2800 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2801 let zero_fees = RoutingFees {
2803 proportional_millionths: 0,
2805 vec![RouteHint(vec![RouteHintHop {
2806 src_node_id: nodes[3],
2807 short_channel_id: 8,
2809 cltv_expiry_delta: (8 << 4) | 1,
2810 htlc_minimum_msat: None,
2811 htlc_maximum_msat: None,
2813 ]), RouteHint(vec![RouteHintHop {
2814 src_node_id: nodes[4],
2815 short_channel_id: 9,
2818 proportional_millionths: 0,
2820 cltv_expiry_delta: (9 << 4) | 1,
2821 htlc_minimum_msat: None,
2822 htlc_maximum_msat: None,
2823 }]), RouteHint(vec![RouteHintHop {
2824 src_node_id: nodes[5],
2825 short_channel_id: 10,
2827 cltv_expiry_delta: (10 << 4) | 1,
2828 htlc_minimum_msat: None,
2829 htlc_maximum_msat: None,
2833 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2834 let zero_fees = RoutingFees {
2836 proportional_millionths: 0,
2838 vec![RouteHint(vec![RouteHintHop {
2839 src_node_id: nodes[2],
2840 short_channel_id: 5,
2843 proportional_millionths: 0,
2845 cltv_expiry_delta: (5 << 4) | 1,
2846 htlc_minimum_msat: None,
2847 htlc_maximum_msat: None,
2849 src_node_id: nodes[3],
2850 short_channel_id: 8,
2852 cltv_expiry_delta: (8 << 4) | 1,
2853 htlc_minimum_msat: None,
2854 htlc_maximum_msat: None,
2856 ]), RouteHint(vec![RouteHintHop {
2857 src_node_id: nodes[4],
2858 short_channel_id: 9,
2861 proportional_millionths: 0,
2863 cltv_expiry_delta: (9 << 4) | 1,
2864 htlc_minimum_msat: None,
2865 htlc_maximum_msat: None,
2866 }]), RouteHint(vec![RouteHintHop {
2867 src_node_id: nodes[5],
2868 short_channel_id: 10,
2870 cltv_expiry_delta: (10 << 4) | 1,
2871 htlc_minimum_msat: None,
2872 htlc_maximum_msat: None,
2877 fn partial_route_hint_test() {
2878 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2879 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2880 let scorer = ln_test_utils::TestScorer::new();
2881 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2882 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2884 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2885 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2886 // RouteHint may be partially used by the algo to build the best path.
2888 // First check that last hop can't have its source as the payee.
2889 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2890 src_node_id: nodes[6],
2891 short_channel_id: 8,
2894 proportional_millionths: 0,
2896 cltv_expiry_delta: (8 << 4) | 1,
2897 htlc_minimum_msat: None,
2898 htlc_maximum_msat: None,
2901 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2902 invalid_last_hops.push(invalid_last_hop);
2904 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops);
2905 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) {
2906 assert_eq!(err, "Route hint cannot have the payee as the source.");
2907 } else { panic!(); }
2910 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes));
2911 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2912 assert_eq!(route.paths[0].hops.len(), 5);
2914 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2915 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2916 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2917 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2918 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2919 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2921 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2922 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2923 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
2924 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
2925 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2926 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2928 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
2929 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
2930 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
2931 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
2932 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
2933 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
2935 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
2936 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
2937 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
2938 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
2939 // If we have a peer in the node map, we'll use their features here since we don't have
2940 // a way of figuring out their features from the invoice:
2941 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
2942 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
2944 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
2945 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
2946 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
2947 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
2948 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2949 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2952 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2953 let zero_fees = RoutingFees {
2955 proportional_millionths: 0,
2957 vec![RouteHint(vec![RouteHintHop {
2958 src_node_id: nodes[3],
2959 short_channel_id: 8,
2961 cltv_expiry_delta: (8 << 4) | 1,
2962 htlc_minimum_msat: None,
2963 htlc_maximum_msat: None,
2964 }]), RouteHint(vec![
2966 ]), RouteHint(vec![RouteHintHop {
2967 src_node_id: nodes[5],
2968 short_channel_id: 10,
2970 cltv_expiry_delta: (10 << 4) | 1,
2971 htlc_minimum_msat: None,
2972 htlc_maximum_msat: None,
2977 fn ignores_empty_last_hops_test() {
2978 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2979 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2980 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes));
2981 let scorer = ln_test_utils::TestScorer::new();
2982 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2983 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2985 // Test handling of an empty RouteHint passed in Invoice.
2987 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2988 assert_eq!(route.paths[0].hops.len(), 5);
2990 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2991 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2992 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2993 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2994 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2995 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2997 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2998 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2999 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3000 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3001 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3002 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3004 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3005 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3006 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3007 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3008 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3009 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3011 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3012 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3013 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3014 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3015 // If we have a peer in the node map, we'll use their features here since we don't have
3016 // a way of figuring out their features from the invoice:
3017 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3018 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3020 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3021 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3022 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3023 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3024 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3025 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3028 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3030 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3031 let zero_fees = RoutingFees {
3033 proportional_millionths: 0,
3035 vec![RouteHint(vec![RouteHintHop {
3036 src_node_id: hint_hops[0],
3037 short_channel_id: 0xff00,
3040 proportional_millionths: 0,
3042 cltv_expiry_delta: (5 << 4) | 1,
3043 htlc_minimum_msat: None,
3044 htlc_maximum_msat: None,
3046 src_node_id: hint_hops[1],
3047 short_channel_id: 0xff01,
3049 cltv_expiry_delta: (8 << 4) | 1,
3050 htlc_minimum_msat: None,
3051 htlc_maximum_msat: None,
3056 fn multi_hint_last_hops_test() {
3057 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3058 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3059 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3060 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3061 let scorer = ln_test_utils::TestScorer::new();
3062 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3063 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3064 // Test through channels 2, 3, 0xff00, 0xff01.
3065 // Test shows that multiple hop hints are considered.
3067 // Disabling channels 6 & 7 by flags=2
3068 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3070 short_channel_id: 6,
3072 flags: 2, // to disable
3073 cltv_expiry_delta: 0,
3074 htlc_minimum_msat: 0,
3075 htlc_maximum_msat: MAX_VALUE_MSAT,
3077 fee_proportional_millionths: 0,
3078 excess_data: Vec::new()
3080 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3082 short_channel_id: 7,
3084 flags: 2, // to disable
3085 cltv_expiry_delta: 0,
3086 htlc_minimum_msat: 0,
3087 htlc_maximum_msat: MAX_VALUE_MSAT,
3089 fee_proportional_millionths: 0,
3090 excess_data: Vec::new()
3093 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3094 assert_eq!(route.paths[0].hops.len(), 4);
3096 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3097 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3098 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3099 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3100 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3101 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3103 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3104 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3105 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3106 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3107 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3108 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3110 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3111 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3112 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3113 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3114 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3115 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3117 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3118 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3119 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3120 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3121 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3122 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3126 fn private_multi_hint_last_hops_test() {
3127 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3128 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3130 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3131 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3133 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3134 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3135 let scorer = ln_test_utils::TestScorer::new();
3136 // Test through channels 2, 3, 0xff00, 0xff01.
3137 // Test shows that multiple hop hints are considered.
3139 // Disabling channels 6 & 7 by flags=2
3140 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3141 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3142 short_channel_id: 6,
3144 flags: 2, // to disable
3145 cltv_expiry_delta: 0,
3146 htlc_minimum_msat: 0,
3147 htlc_maximum_msat: MAX_VALUE_MSAT,
3149 fee_proportional_millionths: 0,
3150 excess_data: Vec::new()
3152 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3153 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3154 short_channel_id: 7,
3156 flags: 2, // to disable
3157 cltv_expiry_delta: 0,
3158 htlc_minimum_msat: 0,
3159 htlc_maximum_msat: MAX_VALUE_MSAT,
3161 fee_proportional_millionths: 0,
3162 excess_data: Vec::new()
3165 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3166 assert_eq!(route.paths[0].hops.len(), 4);
3168 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3169 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3170 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3171 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3172 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3173 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3175 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3176 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3177 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3178 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3179 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3180 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3182 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3183 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3184 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3185 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3186 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3187 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3189 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3190 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3191 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3192 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3193 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3194 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3197 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3198 let zero_fees = RoutingFees {
3200 proportional_millionths: 0,
3202 vec![RouteHint(vec![RouteHintHop {
3203 src_node_id: nodes[4],
3204 short_channel_id: 11,
3206 cltv_expiry_delta: (11 << 4) | 1,
3207 htlc_minimum_msat: None,
3208 htlc_maximum_msat: None,
3210 src_node_id: nodes[3],
3211 short_channel_id: 8,
3213 cltv_expiry_delta: (8 << 4) | 1,
3214 htlc_minimum_msat: None,
3215 htlc_maximum_msat: None,
3216 }]), RouteHint(vec![RouteHintHop {
3217 src_node_id: nodes[4],
3218 short_channel_id: 9,
3221 proportional_millionths: 0,
3223 cltv_expiry_delta: (9 << 4) | 1,
3224 htlc_minimum_msat: None,
3225 htlc_maximum_msat: None,
3226 }]), RouteHint(vec![RouteHintHop {
3227 src_node_id: nodes[5],
3228 short_channel_id: 10,
3230 cltv_expiry_delta: (10 << 4) | 1,
3231 htlc_minimum_msat: None,
3232 htlc_maximum_msat: None,
3237 fn last_hops_with_public_channel_test() {
3238 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3239 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3240 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes));
3241 let scorer = ln_test_utils::TestScorer::new();
3242 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3243 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3244 // This test shows that public routes can be present in the invoice
3245 // which would be handled in the same manner.
3247 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3248 assert_eq!(route.paths[0].hops.len(), 5);
3250 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3251 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3252 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3253 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3254 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3255 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3257 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3258 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3259 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3260 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3261 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3262 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3264 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3265 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3266 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3267 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3268 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3269 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3271 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3272 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3273 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3274 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3275 // If we have a peer in the node map, we'll use their features here since we don't have
3276 // a way of figuring out their features from the invoice:
3277 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3278 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3280 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3281 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3282 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3283 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3284 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3285 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3289 fn our_chans_last_hop_connect_test() {
3290 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3291 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3292 let scorer = ln_test_utils::TestScorer::new();
3293 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3294 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3296 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3297 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3298 let mut last_hops = last_hops(&nodes);
3299 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3300 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();
3301 assert_eq!(route.paths[0].hops.len(), 2);
3303 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3304 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3305 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3306 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3307 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3308 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3310 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3311 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3312 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3313 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3314 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3315 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3317 last_hops[0].0[0].fees.base_msat = 1000;
3319 // Revert to via 6 as the fee on 8 goes up
3320 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops);
3321 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3322 assert_eq!(route.paths[0].hops.len(), 4);
3324 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3325 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3326 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3327 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3328 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3329 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3331 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3332 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3333 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3334 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3335 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3336 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3338 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3339 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3340 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3341 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3342 // If we have a peer in the node map, we'll use their features here since we don't have
3343 // a way of figuring out their features from the invoice:
3344 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3345 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3347 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3348 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3349 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3350 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3351 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3352 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3354 // ...but still use 8 for larger payments as 6 has a variable feerate
3355 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3356 assert_eq!(route.paths[0].hops.len(), 5);
3358 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3359 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3360 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3361 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3362 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3363 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3365 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3366 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3367 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3368 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3369 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3370 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3372 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3373 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3374 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3375 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3376 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3377 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3379 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3380 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3381 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3382 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3383 // If we have a peer in the node map, we'll use their features here since we don't have
3384 // a way of figuring out their features from the invoice:
3385 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3386 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3388 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3389 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3390 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3391 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3392 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3393 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3396 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> {
3397 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3398 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3399 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3401 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3402 let last_hops = RouteHint(vec![RouteHintHop {
3403 src_node_id: middle_node_id,
3404 short_channel_id: 8,
3407 proportional_millionths: last_hop_fee_prop,
3409 cltv_expiry_delta: (8 << 4) | 1,
3410 htlc_minimum_msat: None,
3411 htlc_maximum_msat: last_hop_htlc_max,
3413 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]);
3414 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3415 let scorer = ln_test_utils::TestScorer::new();
3416 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3417 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3418 let logger = ln_test_utils::TestLogger::new();
3419 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3420 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3421 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3426 fn unannounced_path_test() {
3427 // We should be able to send a payment to a destination without any help of a routing graph
3428 // if we have a channel with a common counterparty that appears in the first and last hop
3430 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3432 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3433 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3434 assert_eq!(route.paths[0].hops.len(), 2);
3436 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3437 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3438 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3439 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3440 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3441 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3443 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3444 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3445 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3446 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3447 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3448 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3452 fn overflow_unannounced_path_test_liquidity_underflow() {
3453 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3454 // the last-hop had a fee which overflowed a u64, we'd panic.
3455 // This was due to us adding the first-hop from us unconditionally, causing us to think
3456 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3457 // In this test, we previously hit a subtraction underflow due to having less available
3458 // liquidity at the last hop than 0.
3459 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());
3463 fn overflow_unannounced_path_test_feerate_overflow() {
3464 // This tests for the same case as above, except instead of hitting a subtraction
3465 // underflow, we hit a case where the fee charged at a hop overflowed.
3466 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());
3470 fn available_amount_while_routing_test() {
3471 // Tests whether we choose the correct available channel amount while routing.
3473 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3474 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3475 let scorer = ln_test_utils::TestScorer::new();
3476 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3477 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3478 let config = UserConfig::default();
3479 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
3481 // We will use a simple single-path route from
3482 // our node to node2 via node0: channels {1, 3}.
3484 // First disable all other paths.
3485 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3487 short_channel_id: 2,
3490 cltv_expiry_delta: 0,
3491 htlc_minimum_msat: 0,
3492 htlc_maximum_msat: 100_000,
3494 fee_proportional_millionths: 0,
3495 excess_data: Vec::new()
3497 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3499 short_channel_id: 12,
3502 cltv_expiry_delta: 0,
3503 htlc_minimum_msat: 0,
3504 htlc_maximum_msat: 100_000,
3506 fee_proportional_millionths: 0,
3507 excess_data: Vec::new()
3510 // Make the first channel (#1) very permissive,
3511 // and we will be testing all limits on the second channel.
3512 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3514 short_channel_id: 1,
3517 cltv_expiry_delta: 0,
3518 htlc_minimum_msat: 0,
3519 htlc_maximum_msat: 1_000_000_000,
3521 fee_proportional_millionths: 0,
3522 excess_data: Vec::new()
3525 // First, let's see if routing works if we have absolutely no idea about the available amount.
3526 // In this case, it should be set to 250_000 sats.
3527 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3529 short_channel_id: 3,
3532 cltv_expiry_delta: 0,
3533 htlc_minimum_msat: 0,
3534 htlc_maximum_msat: 250_000_000,
3536 fee_proportional_millionths: 0,
3537 excess_data: Vec::new()
3541 // Attempt to route more than available results in a failure.
3542 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3543 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3544 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3545 } else { panic!(); }
3549 // Now, attempt to route an exact amount we have should be fine.
3550 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();
3551 assert_eq!(route.paths.len(), 1);
3552 let path = route.paths.last().unwrap();
3553 assert_eq!(path.hops.len(), 2);
3554 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3555 assert_eq!(path.final_value_msat(), 250_000_000);
3558 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3559 // Disable channel #1 and use another first hop.
3560 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3561 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3562 short_channel_id: 1,
3565 cltv_expiry_delta: 0,
3566 htlc_minimum_msat: 0,
3567 htlc_maximum_msat: 1_000_000_000,
3569 fee_proportional_millionths: 0,
3570 excess_data: Vec::new()
3573 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3574 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3577 // Attempt to route more than available results in a failure.
3578 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3579 &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) {
3580 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3581 } else { panic!(); }
3585 // Now, attempt to route an exact amount we have should be fine.
3586 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();
3587 assert_eq!(route.paths.len(), 1);
3588 let path = route.paths.last().unwrap();
3589 assert_eq!(path.hops.len(), 2);
3590 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3591 assert_eq!(path.final_value_msat(), 200_000_000);
3594 // Enable channel #1 back.
3595 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3596 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3597 short_channel_id: 1,
3600 cltv_expiry_delta: 0,
3601 htlc_minimum_msat: 0,
3602 htlc_maximum_msat: 1_000_000_000,
3604 fee_proportional_millionths: 0,
3605 excess_data: Vec::new()
3609 // Now let's see if routing works if we know only htlc_maximum_msat.
3610 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3612 short_channel_id: 3,
3615 cltv_expiry_delta: 0,
3616 htlc_minimum_msat: 0,
3617 htlc_maximum_msat: 15_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, 15_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, 15_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.hops.len(), 2);
3637 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3638 assert_eq!(path.final_value_msat(), 15_000);
3641 // Now let's see if routing works if we know only capacity from the UTXO.
3643 // We can't change UTXO capacity on the fly, so we'll disable
3644 // the existing channel and add another one with the capacity we need.
3645 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3646 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3647 short_channel_id: 3,
3650 cltv_expiry_delta: 0,
3651 htlc_minimum_msat: 0,
3652 htlc_maximum_msat: MAX_VALUE_MSAT,
3654 fee_proportional_millionths: 0,
3655 excess_data: Vec::new()
3658 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3659 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3660 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3661 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3662 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3664 *chain_monitor.utxo_ret.lock().unwrap() =
3665 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
3666 gossip_sync.add_utxo_lookup(Some(chain_monitor));
3668 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3669 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3671 short_channel_id: 333,
3674 cltv_expiry_delta: (3 << 4) | 1,
3675 htlc_minimum_msat: 0,
3676 htlc_maximum_msat: 15_000,
3678 fee_proportional_millionths: 0,
3679 excess_data: Vec::new()
3681 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3683 short_channel_id: 333,
3686 cltv_expiry_delta: (3 << 4) | 2,
3687 htlc_minimum_msat: 0,
3688 htlc_maximum_msat: 15_000,
3690 fee_proportional_millionths: 0,
3691 excess_data: Vec::new()
3695 // Attempt to route more than available results in a failure.
3696 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3697 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3698 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3699 } else { panic!(); }
3703 // Now, attempt to route an exact amount we have should be fine.
3704 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3705 assert_eq!(route.paths.len(), 1);
3706 let path = route.paths.last().unwrap();
3707 assert_eq!(path.hops.len(), 2);
3708 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3709 assert_eq!(path.final_value_msat(), 15_000);
3712 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3713 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3714 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3715 short_channel_id: 333,
3718 cltv_expiry_delta: 0,
3719 htlc_minimum_msat: 0,
3720 htlc_maximum_msat: 10_000,
3722 fee_proportional_millionths: 0,
3723 excess_data: Vec::new()
3727 // Attempt to route more than available results in a failure.
3728 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3729 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3730 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3731 } else { panic!(); }
3735 // Now, attempt to route an exact amount we have should be fine.
3736 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3737 assert_eq!(route.paths.len(), 1);
3738 let path = route.paths.last().unwrap();
3739 assert_eq!(path.hops.len(), 2);
3740 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3741 assert_eq!(path.final_value_msat(), 10_000);
3746 fn available_liquidity_last_hop_test() {
3747 // Check that available liquidity properly limits the path even when only
3748 // one of the latter hops is limited.
3749 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3750 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3751 let scorer = ln_test_utils::TestScorer::new();
3752 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3753 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3754 let config = UserConfig::default();
3755 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
3757 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3758 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3759 // Total capacity: 50 sats.
3761 // Disable other potential paths.
3762 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3764 short_channel_id: 2,
3767 cltv_expiry_delta: 0,
3768 htlc_minimum_msat: 0,
3769 htlc_maximum_msat: 100_000,
3771 fee_proportional_millionths: 0,
3772 excess_data: Vec::new()
3774 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3776 short_channel_id: 7,
3779 cltv_expiry_delta: 0,
3780 htlc_minimum_msat: 0,
3781 htlc_maximum_msat: 100_000,
3783 fee_proportional_millionths: 0,
3784 excess_data: Vec::new()
3789 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3790 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3791 short_channel_id: 12,
3794 cltv_expiry_delta: 0,
3795 htlc_minimum_msat: 0,
3796 htlc_maximum_msat: 100_000,
3798 fee_proportional_millionths: 0,
3799 excess_data: Vec::new()
3801 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3802 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3803 short_channel_id: 13,
3806 cltv_expiry_delta: 0,
3807 htlc_minimum_msat: 0,
3808 htlc_maximum_msat: 100_000,
3810 fee_proportional_millionths: 0,
3811 excess_data: Vec::new()
3814 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3816 short_channel_id: 6,
3819 cltv_expiry_delta: 0,
3820 htlc_minimum_msat: 0,
3821 htlc_maximum_msat: 50_000,
3823 fee_proportional_millionths: 0,
3824 excess_data: Vec::new()
3826 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3828 short_channel_id: 11,
3831 cltv_expiry_delta: 0,
3832 htlc_minimum_msat: 0,
3833 htlc_maximum_msat: 100_000,
3835 fee_proportional_millionths: 0,
3836 excess_data: Vec::new()
3839 // Attempt to route more than available results in a failure.
3840 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3841 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3842 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3843 } else { panic!(); }
3847 // Now, attempt to route 49 sats (just a bit below the capacity).
3848 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3849 assert_eq!(route.paths.len(), 1);
3850 let mut total_amount_paid_msat = 0;
3851 for path in &route.paths {
3852 assert_eq!(path.hops.len(), 4);
3853 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
3854 total_amount_paid_msat += path.final_value_msat();
3856 assert_eq!(total_amount_paid_msat, 49_000);
3860 // Attempt to route an exact amount is also fine
3861 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3862 assert_eq!(route.paths.len(), 1);
3863 let mut total_amount_paid_msat = 0;
3864 for path in &route.paths {
3865 assert_eq!(path.hops.len(), 4);
3866 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
3867 total_amount_paid_msat += path.final_value_msat();
3869 assert_eq!(total_amount_paid_msat, 50_000);
3874 fn ignore_fee_first_hop_test() {
3875 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3876 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3877 let scorer = ln_test_utils::TestScorer::new();
3878 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3879 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3880 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3882 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3883 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3885 short_channel_id: 1,
3888 cltv_expiry_delta: 0,
3889 htlc_minimum_msat: 0,
3890 htlc_maximum_msat: 100_000,
3891 fee_base_msat: 1_000_000,
3892 fee_proportional_millionths: 0,
3893 excess_data: Vec::new()
3895 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3897 short_channel_id: 3,
3900 cltv_expiry_delta: 0,
3901 htlc_minimum_msat: 0,
3902 htlc_maximum_msat: 50_000,
3904 fee_proportional_millionths: 0,
3905 excess_data: Vec::new()
3909 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3910 assert_eq!(route.paths.len(), 1);
3911 let mut total_amount_paid_msat = 0;
3912 for path in &route.paths {
3913 assert_eq!(path.hops.len(), 2);
3914 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3915 total_amount_paid_msat += path.final_value_msat();
3917 assert_eq!(total_amount_paid_msat, 50_000);
3922 fn simple_mpp_route_test() {
3923 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3924 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3925 let scorer = ln_test_utils::TestScorer::new();
3926 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3927 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3928 let config = UserConfig::default();
3929 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3930 .with_features(channelmanager::provided_invoice_features(&config));
3932 // We need a route consisting of 3 paths:
3933 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3934 // To achieve this, the amount being transferred should be around
3935 // the total capacity of these 3 paths.
3937 // First, we set limits on these (previously unlimited) channels.
3938 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3940 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3941 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3942 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3943 short_channel_id: 1,
3946 cltv_expiry_delta: 0,
3947 htlc_minimum_msat: 0,
3948 htlc_maximum_msat: 100_000,
3950 fee_proportional_millionths: 0,
3951 excess_data: Vec::new()
3953 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3955 short_channel_id: 3,
3958 cltv_expiry_delta: 0,
3959 htlc_minimum_msat: 0,
3960 htlc_maximum_msat: 50_000,
3962 fee_proportional_millionths: 0,
3963 excess_data: Vec::new()
3966 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3967 // (total limit 60).
3968 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3969 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3970 short_channel_id: 12,
3973 cltv_expiry_delta: 0,
3974 htlc_minimum_msat: 0,
3975 htlc_maximum_msat: 60_000,
3977 fee_proportional_millionths: 0,
3978 excess_data: Vec::new()
3980 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3982 short_channel_id: 13,
3985 cltv_expiry_delta: 0,
3986 htlc_minimum_msat: 0,
3987 htlc_maximum_msat: 60_000,
3989 fee_proportional_millionths: 0,
3990 excess_data: Vec::new()
3993 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3994 // (total capacity 180 sats).
3995 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3996 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3997 short_channel_id: 2,
4000 cltv_expiry_delta: 0,
4001 htlc_minimum_msat: 0,
4002 htlc_maximum_msat: 200_000,
4004 fee_proportional_millionths: 0,
4005 excess_data: Vec::new()
4007 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4009 short_channel_id: 4,
4012 cltv_expiry_delta: 0,
4013 htlc_minimum_msat: 0,
4014 htlc_maximum_msat: 180_000,
4016 fee_proportional_millionths: 0,
4017 excess_data: Vec::new()
4021 // Attempt to route more than available results in a failure.
4022 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4023 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
4024 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4025 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4026 } else { panic!(); }
4030 // Attempt to route while setting max_path_count to 0 results in a failure.
4031 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4032 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4033 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
4034 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4035 assert_eq!(err, "Can't find a route with no paths allowed.");
4036 } else { panic!(); }
4040 // Attempt to route while setting max_path_count to 3 results in a failure.
4041 // This is the case because the minimal_value_contribution_msat would require each path
4042 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4043 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4044 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4045 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
4046 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4047 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4048 } else { panic!(); }
4052 // Now, attempt to route 250 sats (just a bit below the capacity).
4053 // Our algorithm should provide us with these 3 paths.
4054 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4055 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4056 assert_eq!(route.paths.len(), 3);
4057 let mut total_amount_paid_msat = 0;
4058 for path in &route.paths {
4059 assert_eq!(path.hops.len(), 2);
4060 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4061 total_amount_paid_msat += path.final_value_msat();
4063 assert_eq!(total_amount_paid_msat, 250_000);
4067 // Attempt to route an exact amount is also fine
4068 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4069 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4070 assert_eq!(route.paths.len(), 3);
4071 let mut total_amount_paid_msat = 0;
4072 for path in &route.paths {
4073 assert_eq!(path.hops.len(), 2);
4074 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4075 total_amount_paid_msat += path.final_value_msat();
4077 assert_eq!(total_amount_paid_msat, 290_000);
4082 fn long_mpp_route_test() {
4083 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4084 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4085 let scorer = ln_test_utils::TestScorer::new();
4086 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4087 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4088 let config = UserConfig::default();
4089 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4091 // We need a route consisting of 3 paths:
4092 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4093 // Note that these paths overlap (channels 5, 12, 13).
4094 // We will route 300 sats.
4095 // Each path will have 100 sats capacity, those channels which
4096 // are used twice will have 200 sats capacity.
4098 // Disable other potential paths.
4099 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4101 short_channel_id: 2,
4104 cltv_expiry_delta: 0,
4105 htlc_minimum_msat: 0,
4106 htlc_maximum_msat: 100_000,
4108 fee_proportional_millionths: 0,
4109 excess_data: Vec::new()
4111 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4113 short_channel_id: 7,
4116 cltv_expiry_delta: 0,
4117 htlc_minimum_msat: 0,
4118 htlc_maximum_msat: 100_000,
4120 fee_proportional_millionths: 0,
4121 excess_data: Vec::new()
4124 // Path via {node0, node2} is channels {1, 3, 5}.
4125 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4127 short_channel_id: 1,
4130 cltv_expiry_delta: 0,
4131 htlc_minimum_msat: 0,
4132 htlc_maximum_msat: 100_000,
4134 fee_proportional_millionths: 0,
4135 excess_data: Vec::new()
4137 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4139 short_channel_id: 3,
4142 cltv_expiry_delta: 0,
4143 htlc_minimum_msat: 0,
4144 htlc_maximum_msat: 100_000,
4146 fee_proportional_millionths: 0,
4147 excess_data: Vec::new()
4150 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4151 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4152 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4153 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4154 short_channel_id: 5,
4157 cltv_expiry_delta: 0,
4158 htlc_minimum_msat: 0,
4159 htlc_maximum_msat: 200_000,
4161 fee_proportional_millionths: 0,
4162 excess_data: Vec::new()
4165 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4166 // Add 100 sats to the capacities of {12, 13}, because these channels
4167 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4168 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4170 short_channel_id: 12,
4173 cltv_expiry_delta: 0,
4174 htlc_minimum_msat: 0,
4175 htlc_maximum_msat: 200_000,
4177 fee_proportional_millionths: 0,
4178 excess_data: Vec::new()
4180 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4181 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4182 short_channel_id: 13,
4185 cltv_expiry_delta: 0,
4186 htlc_minimum_msat: 0,
4187 htlc_maximum_msat: 200_000,
4189 fee_proportional_millionths: 0,
4190 excess_data: Vec::new()
4193 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4195 short_channel_id: 6,
4198 cltv_expiry_delta: 0,
4199 htlc_minimum_msat: 0,
4200 htlc_maximum_msat: 100_000,
4202 fee_proportional_millionths: 0,
4203 excess_data: Vec::new()
4205 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4207 short_channel_id: 11,
4210 cltv_expiry_delta: 0,
4211 htlc_minimum_msat: 0,
4212 htlc_maximum_msat: 100_000,
4214 fee_proportional_millionths: 0,
4215 excess_data: Vec::new()
4218 // Path via {node7, node2} is channels {12, 13, 5}.
4219 // We already limited them to 200 sats (they are used twice for 100 sats).
4220 // Nothing to do here.
4223 // Attempt to route more than available results in a failure.
4224 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4225 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4226 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4227 } else { panic!(); }
4231 // Now, attempt to route 300 sats (exact amount we can route).
4232 // Our algorithm should provide us with these 3 paths, 100 sats each.
4233 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4234 assert_eq!(route.paths.len(), 3);
4236 let mut total_amount_paid_msat = 0;
4237 for path in &route.paths {
4238 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4239 total_amount_paid_msat += path.final_value_msat();
4241 assert_eq!(total_amount_paid_msat, 300_000);
4247 fn mpp_cheaper_route_test() {
4248 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4249 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4250 let scorer = ln_test_utils::TestScorer::new();
4251 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4252 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4253 let config = UserConfig::default();
4254 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4256 // This test checks that if we have two cheaper paths and one more expensive path,
4257 // so that liquidity-wise any 2 of 3 combination is sufficient,
4258 // two cheaper paths will be taken.
4259 // These paths have equal available liquidity.
4261 // We need a combination of 3 paths:
4262 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4263 // Note that these paths overlap (channels 5, 12, 13).
4264 // Each path will have 100 sats capacity, those channels which
4265 // are used twice will have 200 sats capacity.
4267 // Disable other potential paths.
4268 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4270 short_channel_id: 2,
4273 cltv_expiry_delta: 0,
4274 htlc_minimum_msat: 0,
4275 htlc_maximum_msat: 100_000,
4277 fee_proportional_millionths: 0,
4278 excess_data: Vec::new()
4280 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4281 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4282 short_channel_id: 7,
4285 cltv_expiry_delta: 0,
4286 htlc_minimum_msat: 0,
4287 htlc_maximum_msat: 100_000,
4289 fee_proportional_millionths: 0,
4290 excess_data: Vec::new()
4293 // Path via {node0, node2} is channels {1, 3, 5}.
4294 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4295 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4296 short_channel_id: 1,
4299 cltv_expiry_delta: 0,
4300 htlc_minimum_msat: 0,
4301 htlc_maximum_msat: 100_000,
4303 fee_proportional_millionths: 0,
4304 excess_data: Vec::new()
4306 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4307 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4308 short_channel_id: 3,
4311 cltv_expiry_delta: 0,
4312 htlc_minimum_msat: 0,
4313 htlc_maximum_msat: 100_000,
4315 fee_proportional_millionths: 0,
4316 excess_data: Vec::new()
4319 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4320 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4321 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4322 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4323 short_channel_id: 5,
4326 cltv_expiry_delta: 0,
4327 htlc_minimum_msat: 0,
4328 htlc_maximum_msat: 200_000,
4330 fee_proportional_millionths: 0,
4331 excess_data: Vec::new()
4334 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4335 // Add 100 sats to the capacities of {12, 13}, because these channels
4336 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4337 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4338 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4339 short_channel_id: 12,
4342 cltv_expiry_delta: 0,
4343 htlc_minimum_msat: 0,
4344 htlc_maximum_msat: 200_000,
4346 fee_proportional_millionths: 0,
4347 excess_data: Vec::new()
4349 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4351 short_channel_id: 13,
4354 cltv_expiry_delta: 0,
4355 htlc_minimum_msat: 0,
4356 htlc_maximum_msat: 200_000,
4358 fee_proportional_millionths: 0,
4359 excess_data: Vec::new()
4362 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4364 short_channel_id: 6,
4367 cltv_expiry_delta: 0,
4368 htlc_minimum_msat: 0,
4369 htlc_maximum_msat: 100_000,
4370 fee_base_msat: 1_000,
4371 fee_proportional_millionths: 0,
4372 excess_data: Vec::new()
4374 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4376 short_channel_id: 11,
4379 cltv_expiry_delta: 0,
4380 htlc_minimum_msat: 0,
4381 htlc_maximum_msat: 100_000,
4383 fee_proportional_millionths: 0,
4384 excess_data: Vec::new()
4387 // Path via {node7, node2} is channels {12, 13, 5}.
4388 // We already limited them to 200 sats (they are used twice for 100 sats).
4389 // Nothing to do here.
4392 // Now, attempt to route 180 sats.
4393 // Our algorithm should provide us with these 2 paths.
4394 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4395 assert_eq!(route.paths.len(), 2);
4397 let mut total_value_transferred_msat = 0;
4398 let mut total_paid_msat = 0;
4399 for path in &route.paths {
4400 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4401 total_value_transferred_msat += path.final_value_msat();
4402 for hop in &path.hops {
4403 total_paid_msat += hop.fee_msat;
4406 // If we paid fee, this would be higher.
4407 assert_eq!(total_value_transferred_msat, 180_000);
4408 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4409 assert_eq!(total_fees_paid, 0);
4414 fn fees_on_mpp_route_test() {
4415 // This test makes sure that MPP algorithm properly takes into account
4416 // fees charged on the channels, by making the fees impactful:
4417 // if the fee is not properly accounted for, the behavior is different.
4418 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4419 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4420 let scorer = ln_test_utils::TestScorer::new();
4421 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4422 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4423 let config = UserConfig::default();
4424 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4426 // We need a route consisting of 2 paths:
4427 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4428 // We will route 200 sats, Each path will have 100 sats capacity.
4430 // This test is not particularly stable: e.g.,
4431 // there's a way to route via {node0, node2, node4}.
4432 // It works while pathfinding is deterministic, but can be broken otherwise.
4433 // It's fine to ignore this concern for now.
4435 // Disable other potential paths.
4436 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4437 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4438 short_channel_id: 2,
4441 cltv_expiry_delta: 0,
4442 htlc_minimum_msat: 0,
4443 htlc_maximum_msat: 100_000,
4445 fee_proportional_millionths: 0,
4446 excess_data: Vec::new()
4449 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4451 short_channel_id: 7,
4454 cltv_expiry_delta: 0,
4455 htlc_minimum_msat: 0,
4456 htlc_maximum_msat: 100_000,
4458 fee_proportional_millionths: 0,
4459 excess_data: Vec::new()
4462 // Path via {node0, node2} is channels {1, 3, 5}.
4463 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4465 short_channel_id: 1,
4468 cltv_expiry_delta: 0,
4469 htlc_minimum_msat: 0,
4470 htlc_maximum_msat: 100_000,
4472 fee_proportional_millionths: 0,
4473 excess_data: Vec::new()
4475 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4477 short_channel_id: 3,
4480 cltv_expiry_delta: 0,
4481 htlc_minimum_msat: 0,
4482 htlc_maximum_msat: 100_000,
4484 fee_proportional_millionths: 0,
4485 excess_data: Vec::new()
4488 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4489 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4491 short_channel_id: 5,
4494 cltv_expiry_delta: 0,
4495 htlc_minimum_msat: 0,
4496 htlc_maximum_msat: 100_000,
4498 fee_proportional_millionths: 0,
4499 excess_data: Vec::new()
4502 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4503 // All channels should be 100 sats capacity. But for the fee experiment,
4504 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4505 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4506 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4507 // so no matter how large are other channels,
4508 // the whole path will be limited by 100 sats with just these 2 conditions:
4509 // - channel 12 capacity is 250 sats
4510 // - fee for channel 6 is 150 sats
4511 // Let's test this by enforcing these 2 conditions and removing other limits.
4512 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4514 short_channel_id: 12,
4517 cltv_expiry_delta: 0,
4518 htlc_minimum_msat: 0,
4519 htlc_maximum_msat: 250_000,
4521 fee_proportional_millionths: 0,
4522 excess_data: Vec::new()
4524 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4526 short_channel_id: 13,
4529 cltv_expiry_delta: 0,
4530 htlc_minimum_msat: 0,
4531 htlc_maximum_msat: MAX_VALUE_MSAT,
4533 fee_proportional_millionths: 0,
4534 excess_data: Vec::new()
4537 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4538 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4539 short_channel_id: 6,
4542 cltv_expiry_delta: 0,
4543 htlc_minimum_msat: 0,
4544 htlc_maximum_msat: MAX_VALUE_MSAT,
4545 fee_base_msat: 150_000,
4546 fee_proportional_millionths: 0,
4547 excess_data: Vec::new()
4549 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4550 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4551 short_channel_id: 11,
4554 cltv_expiry_delta: 0,
4555 htlc_minimum_msat: 0,
4556 htlc_maximum_msat: MAX_VALUE_MSAT,
4558 fee_proportional_millionths: 0,
4559 excess_data: Vec::new()
4563 // Attempt to route more than available results in a failure.
4564 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4565 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4566 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4567 } else { panic!(); }
4571 // Now, attempt to route 200 sats (exact amount we can route).
4572 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4573 assert_eq!(route.paths.len(), 2);
4575 let mut total_amount_paid_msat = 0;
4576 for path in &route.paths {
4577 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4578 total_amount_paid_msat += path.final_value_msat();
4580 assert_eq!(total_amount_paid_msat, 200_000);
4581 assert_eq!(route.get_total_fees(), 150_000);
4586 fn mpp_with_last_hops() {
4587 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4588 // via a single last-hop route hint, we'd fail to route if we first collected routes
4589 // totaling close but not quite enough to fund the full payment.
4591 // This was because we considered last-hop hints to have exactly the sought payment amount
4592 // instead of the amount we were trying to collect, needlessly limiting our path searching
4593 // at the very first hop.
4595 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4596 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4597 // to only have the remaining to-collect amount in available liquidity.
4599 // This bug appeared in production in some specific channel configurations.
4600 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4601 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4602 let scorer = ln_test_utils::TestScorer::new();
4603 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4604 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4605 let config = UserConfig::default();
4606 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_features(channelmanager::provided_invoice_features(&config))
4607 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4608 src_node_id: nodes[2],
4609 short_channel_id: 42,
4610 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4611 cltv_expiry_delta: 42,
4612 htlc_minimum_msat: None,
4613 htlc_maximum_msat: None,
4614 }])]).with_max_channel_saturation_power_of_half(0);
4616 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4617 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4618 // would first use the no-fee route and then fail to find a path along the second route as
4619 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4620 // under 5% of our payment amount.
4621 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4623 short_channel_id: 1,
4626 cltv_expiry_delta: (5 << 4) | 5,
4627 htlc_minimum_msat: 0,
4628 htlc_maximum_msat: 99_000,
4629 fee_base_msat: u32::max_value(),
4630 fee_proportional_millionths: u32::max_value(),
4631 excess_data: Vec::new()
4633 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4635 short_channel_id: 2,
4638 cltv_expiry_delta: (5 << 4) | 3,
4639 htlc_minimum_msat: 0,
4640 htlc_maximum_msat: 99_000,
4641 fee_base_msat: u32::max_value(),
4642 fee_proportional_millionths: u32::max_value(),
4643 excess_data: Vec::new()
4645 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4646 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4647 short_channel_id: 4,
4650 cltv_expiry_delta: (4 << 4) | 1,
4651 htlc_minimum_msat: 0,
4652 htlc_maximum_msat: MAX_VALUE_MSAT,
4654 fee_proportional_millionths: 0,
4655 excess_data: Vec::new()
4657 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4659 short_channel_id: 13,
4661 flags: 0|2, // Channel disabled
4662 cltv_expiry_delta: (13 << 4) | 1,
4663 htlc_minimum_msat: 0,
4664 htlc_maximum_msat: MAX_VALUE_MSAT,
4666 fee_proportional_millionths: 2000000,
4667 excess_data: Vec::new()
4670 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4672 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();
4673 assert_eq!(route.paths.len(), 2);
4674 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
4675 // Paths are manually ordered ordered by SCID, so:
4676 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4677 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4678 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
4679 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4680 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
4681 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
4682 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
4683 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
4684 assert_eq!(route.get_total_fees(), 1);
4685 assert_eq!(route.get_total_amount(), 100_000);
4689 fn drop_lowest_channel_mpp_route_test() {
4690 // This test checks that low-capacity channel is dropped when after
4691 // path finding we realize that we found more capacity than we need.
4692 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4693 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4694 let scorer = ln_test_utils::TestScorer::new();
4695 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4696 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4697 let config = UserConfig::default();
4698 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config))
4699 .with_max_channel_saturation_power_of_half(0);
4701 // We need a route consisting of 3 paths:
4702 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4704 // The first and the second paths should be sufficient, but the third should be
4705 // cheaper, so that we select it but drop later.
4707 // First, we set limits on these (previously unlimited) channels.
4708 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4710 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4711 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4713 short_channel_id: 1,
4716 cltv_expiry_delta: 0,
4717 htlc_minimum_msat: 0,
4718 htlc_maximum_msat: 100_000,
4720 fee_proportional_millionths: 0,
4721 excess_data: Vec::new()
4723 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4724 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4725 short_channel_id: 3,
4728 cltv_expiry_delta: 0,
4729 htlc_minimum_msat: 0,
4730 htlc_maximum_msat: 50_000,
4732 fee_proportional_millionths: 0,
4733 excess_data: Vec::new()
4736 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4737 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4739 short_channel_id: 12,
4742 cltv_expiry_delta: 0,
4743 htlc_minimum_msat: 0,
4744 htlc_maximum_msat: 60_000,
4746 fee_proportional_millionths: 0,
4747 excess_data: Vec::new()
4749 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4751 short_channel_id: 13,
4754 cltv_expiry_delta: 0,
4755 htlc_minimum_msat: 0,
4756 htlc_maximum_msat: 60_000,
4758 fee_proportional_millionths: 0,
4759 excess_data: Vec::new()
4762 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4763 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4765 short_channel_id: 2,
4768 cltv_expiry_delta: 0,
4769 htlc_minimum_msat: 0,
4770 htlc_maximum_msat: 20_000,
4772 fee_proportional_millionths: 0,
4773 excess_data: Vec::new()
4775 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4777 short_channel_id: 4,
4780 cltv_expiry_delta: 0,
4781 htlc_minimum_msat: 0,
4782 htlc_maximum_msat: 20_000,
4784 fee_proportional_millionths: 0,
4785 excess_data: Vec::new()
4789 // Attempt to route more than available results in a failure.
4790 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4791 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4792 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4793 } else { panic!(); }
4797 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4798 // Our algorithm should provide us with these 3 paths.
4799 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4800 assert_eq!(route.paths.len(), 3);
4801 let mut total_amount_paid_msat = 0;
4802 for path in &route.paths {
4803 assert_eq!(path.hops.len(), 2);
4804 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4805 total_amount_paid_msat += path.final_value_msat();
4807 assert_eq!(total_amount_paid_msat, 125_000);
4811 // Attempt to route without the last small cheap channel
4812 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4813 assert_eq!(route.paths.len(), 2);
4814 let mut total_amount_paid_msat = 0;
4815 for path in &route.paths {
4816 assert_eq!(path.hops.len(), 2);
4817 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4818 total_amount_paid_msat += path.final_value_msat();
4820 assert_eq!(total_amount_paid_msat, 90_000);
4825 fn min_criteria_consistency() {
4826 // Test that we don't use an inconsistent metric between updating and walking nodes during
4827 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4828 // was updated with a different criterion from the heap sorting, resulting in loops in
4829 // calculated paths. We test for that specific case here.
4831 // We construct a network that looks like this:
4833 // node2 -1(3)2- node3
4837 // node1 -1(5)2- node4 -1(1)2- node6
4843 // We create a loop on the side of our real path - our destination is node 6, with a
4844 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4845 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4846 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4847 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4848 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4849 // "previous hop" being set to node 3, creating a loop in the path.
4850 let secp_ctx = Secp256k1::new();
4851 let logger = Arc::new(ln_test_utils::TestLogger::new());
4852 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
4853 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4854 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4855 let scorer = ln_test_utils::TestScorer::new();
4856 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4857 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4858 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
4860 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4861 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4862 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4863 short_channel_id: 6,
4866 cltv_expiry_delta: (6 << 4) | 0,
4867 htlc_minimum_msat: 0,
4868 htlc_maximum_msat: MAX_VALUE_MSAT,
4870 fee_proportional_millionths: 0,
4871 excess_data: Vec::new()
4873 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4875 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4876 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4878 short_channel_id: 5,
4881 cltv_expiry_delta: (5 << 4) | 0,
4882 htlc_minimum_msat: 0,
4883 htlc_maximum_msat: MAX_VALUE_MSAT,
4885 fee_proportional_millionths: 0,
4886 excess_data: Vec::new()
4888 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4890 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4891 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4893 short_channel_id: 4,
4896 cltv_expiry_delta: (4 << 4) | 0,
4897 htlc_minimum_msat: 0,
4898 htlc_maximum_msat: MAX_VALUE_MSAT,
4900 fee_proportional_millionths: 0,
4901 excess_data: Vec::new()
4903 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4905 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4906 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4907 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4908 short_channel_id: 3,
4911 cltv_expiry_delta: (3 << 4) | 0,
4912 htlc_minimum_msat: 0,
4913 htlc_maximum_msat: MAX_VALUE_MSAT,
4915 fee_proportional_millionths: 0,
4916 excess_data: Vec::new()
4918 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4920 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4921 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4923 short_channel_id: 2,
4926 cltv_expiry_delta: (2 << 4) | 0,
4927 htlc_minimum_msat: 0,
4928 htlc_maximum_msat: MAX_VALUE_MSAT,
4930 fee_proportional_millionths: 0,
4931 excess_data: Vec::new()
4934 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4935 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4937 short_channel_id: 1,
4940 cltv_expiry_delta: (1 << 4) | 0,
4941 htlc_minimum_msat: 100,
4942 htlc_maximum_msat: MAX_VALUE_MSAT,
4944 fee_proportional_millionths: 0,
4945 excess_data: Vec::new()
4947 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4950 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4951 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4952 assert_eq!(route.paths.len(), 1);
4953 assert_eq!(route.paths[0].hops.len(), 3);
4955 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4956 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
4957 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4958 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
4959 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
4960 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
4962 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
4963 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
4964 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4965 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
4966 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
4967 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
4969 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
4970 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
4971 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
4972 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
4973 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4974 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
4980 fn exact_fee_liquidity_limit() {
4981 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4982 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4983 // we calculated fees on a higher value, resulting in us ignoring such paths.
4984 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4985 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4986 let scorer = ln_test_utils::TestScorer::new();
4987 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4988 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4989 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4991 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4993 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4995 short_channel_id: 2,
4998 cltv_expiry_delta: 0,
4999 htlc_minimum_msat: 0,
5000 htlc_maximum_msat: 85_000,
5002 fee_proportional_millionths: 0,
5003 excess_data: Vec::new()
5006 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5007 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5008 short_channel_id: 12,
5011 cltv_expiry_delta: (4 << 4) | 1,
5012 htlc_minimum_msat: 0,
5013 htlc_maximum_msat: 270_000,
5015 fee_proportional_millionths: 1000000,
5016 excess_data: Vec::new()
5020 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5021 // 200% fee charged channel 13 in the 1-to-2 direction.
5022 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5023 assert_eq!(route.paths.len(), 1);
5024 assert_eq!(route.paths[0].hops.len(), 2);
5026 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5027 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5028 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5029 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5030 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5031 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5033 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5034 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5035 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5036 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5037 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5038 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5043 fn htlc_max_reduction_below_min() {
5044 // Test that if, while walking the graph, we reduce the value being sent to meet an
5045 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5046 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5047 // resulting in us thinking there is no possible path, even if other paths exist.
5048 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5049 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5050 let scorer = ln_test_utils::TestScorer::new();
5051 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5052 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5053 let config = UserConfig::default();
5054 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
5056 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5057 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5058 // then try to send 90_000.
5059 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5061 short_channel_id: 2,
5064 cltv_expiry_delta: 0,
5065 htlc_minimum_msat: 0,
5066 htlc_maximum_msat: 80_000,
5068 fee_proportional_millionths: 0,
5069 excess_data: Vec::new()
5071 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5073 short_channel_id: 4,
5076 cltv_expiry_delta: (4 << 4) | 1,
5077 htlc_minimum_msat: 90_000,
5078 htlc_maximum_msat: MAX_VALUE_MSAT,
5080 fee_proportional_millionths: 0,
5081 excess_data: Vec::new()
5085 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5086 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5087 // expensive) channels 12-13 path.
5088 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5089 assert_eq!(route.paths.len(), 1);
5090 assert_eq!(route.paths[0].hops.len(), 2);
5092 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5093 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5094 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5095 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5096 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5097 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5099 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5100 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5101 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5102 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5103 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5104 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5109 fn multiple_direct_first_hops() {
5110 // Previously we'd only ever considered one first hop path per counterparty.
5111 // However, as we don't restrict users to one channel per peer, we really need to support
5112 // looking at all first hop paths.
5113 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5114 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5115 // route over multiple channels with the same first hop.
5116 let secp_ctx = Secp256k1::new();
5117 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5118 let logger = Arc::new(ln_test_utils::TestLogger::new());
5119 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5120 let scorer = ln_test_utils::TestScorer::new();
5121 let config = UserConfig::default();
5122 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_features(channelmanager::provided_invoice_features(&config));
5123 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5124 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5127 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5128 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5129 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5130 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5131 assert_eq!(route.paths.len(), 1);
5132 assert_eq!(route.paths[0].hops.len(), 1);
5134 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5135 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5136 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5139 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5140 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5141 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5142 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5143 assert_eq!(route.paths.len(), 2);
5144 assert_eq!(route.paths[0].hops.len(), 1);
5145 assert_eq!(route.paths[1].hops.len(), 1);
5147 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5148 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5150 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5151 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5153 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5154 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5158 // If we have a bunch of outbound channels to the same node, where most are not
5159 // sufficient to pay the full payment, but one is, we should default to just using the
5160 // one single channel that has sufficient balance, avoiding MPP.
5162 // If we have several options above the 3xpayment value threshold, we should pick the
5163 // smallest of them, avoiding further fragmenting our available outbound balance to
5165 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5166 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5167 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5168 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5169 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5170 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5171 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5172 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5173 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5174 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5175 assert_eq!(route.paths.len(), 1);
5176 assert_eq!(route.paths[0].hops.len(), 1);
5178 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5179 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5180 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5185 fn prefers_shorter_route_with_higher_fees() {
5186 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5187 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5188 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5190 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5191 let scorer = ln_test_utils::TestScorer::new();
5192 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5193 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5194 let route = get_route(
5195 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5196 Arc::clone(&logger), &scorer, &random_seed_bytes
5198 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5200 assert_eq!(route.get_total_fees(), 100);
5201 assert_eq!(route.get_total_amount(), 100);
5202 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5204 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5205 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5206 let scorer = FixedPenaltyScorer::with_penalty(100);
5207 let route = get_route(
5208 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5209 Arc::clone(&logger), &scorer, &random_seed_bytes
5211 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5213 assert_eq!(route.get_total_fees(), 300);
5214 assert_eq!(route.get_total_amount(), 100);
5215 assert_eq!(path, vec![2, 4, 7, 10]);
5218 struct BadChannelScorer {
5219 short_channel_id: u64,
5223 impl Writeable for BadChannelScorer {
5224 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5226 impl Score for BadChannelScorer {
5227 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5228 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5231 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5232 fn payment_path_successful(&mut self, _path: &Path) {}
5233 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5234 fn probe_successful(&mut self, _path: &Path) {}
5237 struct BadNodeScorer {
5242 impl Writeable for BadNodeScorer {
5243 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5246 impl Score for BadNodeScorer {
5247 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5248 if *target == self.node_id { u64::max_value() } else { 0 }
5251 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5252 fn payment_path_successful(&mut self, _path: &Path) {}
5253 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5254 fn probe_successful(&mut self, _path: &Path) {}
5258 fn avoids_routing_through_bad_channels_and_nodes() {
5259 let (secp_ctx, network, _, _, logger) = build_graph();
5260 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5261 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5262 let network_graph = network.read_only();
5264 // A path to nodes[6] exists when no penalties are applied to any channel.
5265 let scorer = ln_test_utils::TestScorer::new();
5266 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5267 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5268 let route = get_route(
5269 &our_id, &payment_params, &network_graph, None, 100, 42,
5270 Arc::clone(&logger), &scorer, &random_seed_bytes
5272 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5274 assert_eq!(route.get_total_fees(), 100);
5275 assert_eq!(route.get_total_amount(), 100);
5276 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5278 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5279 let scorer = BadChannelScorer { short_channel_id: 6 };
5280 let route = get_route(
5281 &our_id, &payment_params, &network_graph, None, 100, 42,
5282 Arc::clone(&logger), &scorer, &random_seed_bytes
5284 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5286 assert_eq!(route.get_total_fees(), 300);
5287 assert_eq!(route.get_total_amount(), 100);
5288 assert_eq!(path, vec![2, 4, 7, 10]);
5290 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5291 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5293 &our_id, &payment_params, &network_graph, None, 100, 42,
5294 Arc::clone(&logger), &scorer, &random_seed_bytes
5296 Err(LightningError { err, .. } ) => {
5297 assert_eq!(err, "Failed to find a path to the given destination");
5299 Ok(_) => panic!("Expected error"),
5304 fn total_fees_single_path() {
5306 paths: vec![Path { hops: vec![
5308 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5309 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5310 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5313 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5314 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5315 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5318 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5319 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5320 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5322 ], blinded_tail: None }],
5323 payment_params: None,
5326 assert_eq!(route.get_total_fees(), 250);
5327 assert_eq!(route.get_total_amount(), 225);
5331 fn total_fees_multi_path() {
5333 paths: vec![Path { hops: vec![
5335 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5336 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5337 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5340 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5341 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5342 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5344 ], blinded_tail: None }, Path { hops: vec![
5346 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5347 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5348 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5351 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5352 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5353 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5355 ], blinded_tail: None }],
5356 payment_params: None,
5359 assert_eq!(route.get_total_fees(), 200);
5360 assert_eq!(route.get_total_amount(), 300);
5364 fn total_empty_route_no_panic() {
5365 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5366 // would both panic if the route was completely empty. We test to ensure they return 0
5367 // here, even though its somewhat nonsensical as a route.
5368 let route = Route { paths: Vec::new(), payment_params: None };
5370 assert_eq!(route.get_total_fees(), 0);
5371 assert_eq!(route.get_total_amount(), 0);
5375 fn limits_total_cltv_delta() {
5376 let (secp_ctx, network, _, _, logger) = build_graph();
5377 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5378 let network_graph = network.read_only();
5380 let scorer = ln_test_utils::TestScorer::new();
5382 // Make sure that generally there is at least one route available
5383 let feasible_max_total_cltv_delta = 1008;
5384 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5385 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5386 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5387 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5388 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5389 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5390 assert_ne!(path.len(), 0);
5392 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5393 let fail_max_total_cltv_delta = 23;
5394 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5395 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5396 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5398 Err(LightningError { err, .. } ) => {
5399 assert_eq!(err, "Failed to find a path to the given destination");
5401 Ok(_) => panic!("Expected error"),
5406 fn avoids_recently_failed_paths() {
5407 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5408 // randomly inserting channels into it until we can't find a route anymore.
5409 let (secp_ctx, network, _, _, logger) = build_graph();
5410 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5411 let network_graph = network.read_only();
5413 let scorer = ln_test_utils::TestScorer::new();
5414 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5415 .with_max_path_count(1);
5416 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5417 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5419 // We should be able to find a route initially, and then after we fail a few random
5420 // channels eventually we won't be able to any longer.
5421 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5423 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5424 for chan in route.paths[0].hops.iter() {
5425 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5427 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5428 % route.paths[0].hops.len();
5429 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5435 fn limits_path_length() {
5436 let (secp_ctx, network, _, _, logger) = build_line_graph();
5437 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5438 let network_graph = network.read_only();
5440 let scorer = ln_test_utils::TestScorer::new();
5441 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5442 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5444 // First check we can actually create a long route on this graph.
5445 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5446 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5447 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5448 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5449 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5451 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5452 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5453 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5454 Arc::clone(&logger), &scorer, &random_seed_bytes)
5456 Err(LightningError { err, .. } ) => {
5457 assert_eq!(err, "Failed to find a path to the given destination");
5459 Ok(_) => panic!("Expected error"),
5464 fn adds_and_limits_cltv_offset() {
5465 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5466 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5468 let scorer = ln_test_utils::TestScorer::new();
5470 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5471 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5472 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5473 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5474 assert_eq!(route.paths.len(), 1);
5476 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5478 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5479 let mut route_default = route.clone();
5480 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5481 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5482 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5483 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5484 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5486 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5487 let mut route_limited = route.clone();
5488 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5489 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5490 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5491 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5492 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5496 fn adds_plausible_cltv_offset() {
5497 let (secp_ctx, network, _, _, logger) = build_graph();
5498 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5499 let network_graph = network.read_only();
5500 let network_nodes = network_graph.nodes();
5501 let network_channels = network_graph.channels();
5502 let scorer = ln_test_utils::TestScorer::new();
5503 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5504 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5505 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5507 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5508 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5509 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5511 let mut path_plausibility = vec![];
5513 for p in route.paths {
5514 // 1. Select random observation point
5515 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5516 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5518 prng.process_in_place(&mut random_bytes);
5519 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5520 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5522 // 2. Calculate what CLTV expiry delta we would observe there
5523 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5525 // 3. Starting from the observation point, find candidate paths
5526 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5527 candidates.push_back((observation_point, vec![]));
5529 let mut found_plausible_candidate = false;
5531 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5532 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5533 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5534 found_plausible_candidate = true;
5535 break 'candidate_loop;
5539 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5540 for channel_id in &cur_node.channels {
5541 if let Some(channel_info) = network_channels.get(&channel_id) {
5542 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5543 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5544 if cur_path_cltv_deltas.iter().sum::<u32>()
5545 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5546 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5547 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5548 candidates.push_back((*next_id, new_path_cltv_deltas));
5556 path_plausibility.push(found_plausible_candidate);
5558 assert!(path_plausibility.iter().all(|x| *x));
5562 fn builds_correct_path_from_hops() {
5563 let (secp_ctx, network, _, _, logger) = build_graph();
5564 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5565 let network_graph = network.read_only();
5567 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5568 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5570 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5571 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5572 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5573 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5574 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5575 assert_eq!(hops.len(), route.paths[0].hops.len());
5576 for (idx, hop_pubkey) in hops.iter().enumerate() {
5577 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5582 fn avoids_saturating_channels() {
5583 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5584 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5586 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5588 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5589 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5590 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5592 short_channel_id: 4,
5595 cltv_expiry_delta: (4 << 4) | 1,
5596 htlc_minimum_msat: 0,
5597 htlc_maximum_msat: 250_000_000,
5599 fee_proportional_millionths: 0,
5600 excess_data: Vec::new()
5602 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5603 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5604 short_channel_id: 13,
5607 cltv_expiry_delta: (13 << 4) | 1,
5608 htlc_minimum_msat: 0,
5609 htlc_maximum_msat: 250_000_000,
5611 fee_proportional_millionths: 0,
5612 excess_data: Vec::new()
5615 let config = UserConfig::default();
5616 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
5617 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5618 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5619 // 100,000 sats is less than the available liquidity on each channel, set above.
5620 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();
5621 assert_eq!(route.paths.len(), 2);
5622 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
5623 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
5626 #[cfg(not(feature = "no-std"))]
5627 pub(super) fn random_init_seed() -> u64 {
5628 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5629 use core::hash::{BuildHasher, Hasher};
5630 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5631 println!("Using seed of {}", seed);
5634 #[cfg(not(feature = "no-std"))]
5635 use crate::util::ser::ReadableArgs;
5638 #[cfg(not(feature = "no-std"))]
5639 fn generate_routes() {
5640 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5642 let mut d = match super::bench_utils::get_route_file() {
5649 let logger = ln_test_utils::TestLogger::new();
5650 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5651 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5652 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5654 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5655 let mut seed = random_init_seed() as usize;
5656 let nodes = graph.read_only().nodes().clone();
5657 'load_endpoints: for _ in 0..10 {
5659 seed = seed.overflowing_mul(0xdeadbeef).0;
5660 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5661 seed = seed.overflowing_mul(0xdeadbeef).0;
5662 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5663 let payment_params = PaymentParameters::from_node_id(dst, 42);
5664 let amt = seed as u64 % 200_000_000;
5665 let params = ProbabilisticScoringParameters::default();
5666 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5667 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5668 continue 'load_endpoints;
5675 #[cfg(not(feature = "no-std"))]
5676 fn generate_routes_mpp() {
5677 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5679 let mut d = match super::bench_utils::get_route_file() {
5686 let logger = ln_test_utils::TestLogger::new();
5687 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5688 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5689 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5690 let config = UserConfig::default();
5692 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5693 let mut seed = random_init_seed() as usize;
5694 let nodes = graph.read_only().nodes().clone();
5695 'load_endpoints: for _ in 0..10 {
5697 seed = seed.overflowing_mul(0xdeadbeef).0;
5698 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5699 seed = seed.overflowing_mul(0xdeadbeef).0;
5700 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5701 let payment_params = PaymentParameters::from_node_id(dst, 42).with_features(channelmanager::provided_invoice_features(&config));
5702 let amt = seed as u64 % 200_000_000;
5703 let params = ProbabilisticScoringParameters::default();
5704 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5705 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5706 continue 'load_endpoints;
5713 fn honors_manual_penalties() {
5714 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5715 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5717 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5718 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5720 let scorer_params = ProbabilisticScoringParameters::default();
5721 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5723 // First check set manual penalties are returned by the scorer.
5724 let usage = ChannelUsage {
5726 inflight_htlc_msat: 0,
5727 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5729 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5730 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5731 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5733 // Then check we can get a normal route
5734 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
5735 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5736 assert!(route.is_ok());
5738 // Then check that we can't get a route if we ban an intermediate node.
5739 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5740 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5741 assert!(route.is_err());
5743 // Finally make sure we can route again, when we remove the ban.
5744 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5745 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5746 assert!(route.is_ok());
5750 #[cfg(all(test, not(feature = "no-std")))]
5751 pub(crate) mod bench_utils {
5753 /// Tries to open a network graph file, or panics with a URL to fetch it.
5754 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5755 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
5756 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
5757 .or_else(|_| { // Fall back to guessing based on the binary location
5758 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5759 let mut path = std::env::current_exe().unwrap();
5760 path.pop(); // lightning-...
5762 path.pop(); // debug
5763 path.pop(); // target
5764 path.push("lightning");
5765 path.push("net_graph-2023-01-18.bin");
5766 eprintln!("{}", path.to_str().unwrap());
5769 .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");
5770 #[cfg(require_route_graph_test)]
5771 return Ok(res.unwrap());
5772 #[cfg(not(require_route_graph_test))]
5777 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5780 use bitcoin::hashes::Hash;
5781 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5782 use crate::chain::transaction::OutPoint;
5783 use crate::chain::keysinterface::{EntropySource, KeysManager};
5784 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5785 use crate::ln::features::InvoiceFeatures;
5786 use crate::routing::gossip::NetworkGraph;
5787 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5788 use crate::util::config::UserConfig;
5789 use crate::util::logger::{Logger, Record};
5790 use crate::util::ser::ReadableArgs;
5794 struct DummyLogger {}
5795 impl Logger for DummyLogger {
5796 fn log(&self, _record: &Record) {}
5799 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5800 let mut d = bench_utils::get_route_file().unwrap();
5801 NetworkGraph::read(&mut d, logger).unwrap()
5804 fn payer_pubkey() -> PublicKey {
5805 let secp_ctx = Secp256k1::new();
5806 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5810 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5812 channel_id: [0; 32],
5813 counterparty: ChannelCounterparty {
5814 features: channelmanager::provided_init_features(&UserConfig::default()),
5816 unspendable_punishment_reserve: 0,
5817 forwarding_info: None,
5818 outbound_htlc_minimum_msat: None,
5819 outbound_htlc_maximum_msat: None,
5821 funding_txo: Some(OutPoint {
5822 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5825 short_channel_id: Some(1),
5826 inbound_scid_alias: None,
5827 outbound_scid_alias: None,
5828 channel_value_satoshis: 10_000_000,
5830 balance_msat: 10_000_000,
5831 outbound_capacity_msat: 10_000_000,
5832 next_outbound_htlc_limit_msat: 10_000_000,
5833 inbound_capacity_msat: 0,
5834 unspendable_punishment_reserve: None,
5835 confirmations_required: None,
5836 confirmations: None,
5837 force_close_spend_delay: None,
5839 is_channel_ready: true,
5842 inbound_htlc_minimum_msat: None,
5843 inbound_htlc_maximum_msat: None,
5845 feerate_sat_per_1000_weight: None,
5850 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5851 let logger = DummyLogger {};
5852 let network_graph = read_network_graph(&logger);
5853 let scorer = FixedPenaltyScorer::with_penalty(0);
5854 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5858 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5859 let logger = DummyLogger {};
5860 let network_graph = read_network_graph(&logger);
5861 let scorer = FixedPenaltyScorer::with_penalty(0);
5862 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5866 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5867 let logger = DummyLogger {};
5868 let network_graph = read_network_graph(&logger);
5869 let params = ProbabilisticScoringParameters::default();
5870 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5871 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5875 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5876 let logger = DummyLogger {};
5877 let network_graph = read_network_graph(&logger);
5878 let params = ProbabilisticScoringParameters::default();
5879 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
5880 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
5883 fn generate_routes<S: Score>(
5884 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
5885 features: InvoiceFeatures
5887 let nodes = graph.read_only().nodes().clone();
5888 let payer = payer_pubkey();
5889 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
5890 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5892 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5893 let mut routes = Vec::new();
5894 let mut route_endpoints = Vec::new();
5895 let mut seed: usize = 0xdeadbeef;
5896 'load_endpoints: for _ in 0..150 {
5899 let src = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5901 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5902 let params = PaymentParameters::from_node_id(dst, 42).with_features(features.clone());
5903 let first_hop = first_hop(src);
5904 let amt = seed as u64 % 1_000_000;
5905 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
5907 route_endpoints.push((first_hop, params, amt));
5908 continue 'load_endpoints;
5913 // ...and seed the scorer with success and failure data...
5914 for route in routes {
5915 let amount = route.get_total_amount();
5916 if amount < 250_000 {
5917 for path in route.paths {
5918 scorer.payment_path_successful(&path);
5920 } else if amount > 750_000 {
5921 for path in route.paths {
5922 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
5923 scorer.payment_path_failed(&path, short_channel_id);
5928 // Because we've changed channel scores, its possible we'll take different routes to the
5929 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
5930 // requires a too-high CLTV delta.
5931 route_endpoints.retain(|(first_hop, params, amt)| {
5932 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
5934 route_endpoints.truncate(100);
5935 assert_eq!(route_endpoints.len(), 100);
5937 // ...then benchmark finding paths between the nodes we learned.
5940 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5941 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());