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 };
176 let mut cumulative_msat = 0;
177 if let Some(tail) = &path.blinded_tail {
178 cumulative_msat += tail.final_value_msat;
181 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
182 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
183 // the router excludes the payer node. In the following lines, the payer's information is
184 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
185 // in our sliding window of two.
186 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
187 .map(|hop| hop.pubkey)
188 .chain(core::iter::once(payer_node_id));
190 // Taking the reversed vector from above, we zip it with just the reversed hops list to
191 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
192 // the total amount sent.
193 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
194 cumulative_msat += next_hop.fee_msat;
196 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
197 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
198 .or_insert(cumulative_msat);
202 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
204 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
205 self.0.get(&(channel_scid, source < target)).map(|v| *v)
209 impl Writeable for InFlightHtlcs {
210 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
213 impl Readable for InFlightHtlcs {
214 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
215 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
216 Ok(Self(infight_map))
220 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
221 /// that leads to it.
222 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
223 pub struct RouteHop {
224 /// The node_id of the node at this hop.
225 pub pubkey: PublicKey,
226 /// The node_announcement features of the node at this hop. For the last hop, these may be
227 /// amended to match the features present in the invoice this node generated.
228 pub node_features: NodeFeatures,
229 /// The channel that should be used from the previous hop to reach this node.
230 pub short_channel_id: u64,
231 /// The channel_announcement features of the channel that should be used from the previous hop
232 /// to reach this node.
233 pub channel_features: ChannelFeatures,
234 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
235 /// If this is the last hop in [`Path::hops`]:
236 /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
237 /// * otherwise, this is the full value of this [`Path`]'s part of the payment
239 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
241 /// The CLTV delta added for this hop.
242 /// If this is the last hop in [`Path::hops`]:
243 /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
244 /// * otherwise, this is the CLTV delta expected at the destination
246 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
247 pub cltv_expiry_delta: u32,
250 impl_writeable_tlv_based!(RouteHop, {
251 (0, pubkey, required),
252 (2, node_features, required),
253 (4, short_channel_id, required),
254 (6, channel_features, required),
255 (8, fee_msat, required),
256 (10, cltv_expiry_delta, required),
259 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
260 /// their BOLT12 [`Invoice`].
262 /// [`Invoice`]: crate::offers::invoice::Invoice
263 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
264 pub struct BlindedTail {
265 /// The hops of the [`BlindedPath`] provided by the recipient.
267 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
268 pub hops: Vec<BlindedHop>,
269 /// The blinding point of the [`BlindedPath`] provided by the recipient.
271 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
272 pub blinding_point: PublicKey,
273 /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
274 /// inferring the destination. May be 0.
275 pub excess_final_cltv_expiry_delta: u32,
276 /// The total amount paid on this [`Path`], excluding the fees.
277 pub final_value_msat: u64,
280 impl_writeable_tlv_based!(BlindedTail, {
282 (2, blinding_point, required),
283 (4, excess_final_cltv_expiry_delta, required),
284 (6, final_value_msat, required),
287 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
288 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
289 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
291 /// The list of unblinded hops in this [`Path`]. Must be at least length one.
292 pub hops: Vec<RouteHop>,
293 /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
294 pub blinded_tail: Option<BlindedTail>,
298 /// Gets the fees for a given path, excluding any excess paid to the recipient.
299 pub fn fee_msat(&self) -> u64 {
300 match &self.blinded_tail {
301 Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
303 // Do not count last hop of each path since that's the full value of the payment
304 self.hops.split_last().map_or(0,
305 |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
310 /// Gets the total amount paid on this [`Path`], excluding the fees.
311 pub fn final_value_msat(&self) -> u64 {
312 match &self.blinded_tail {
313 Some(blinded_tail) => blinded_tail.final_value_msat,
314 None => self.hops.last().map_or(0, |hop| hop.fee_msat)
318 /// Gets the final hop's CLTV expiry delta.
319 pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
320 match &self.blinded_tail {
322 None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
327 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
328 /// it can take multiple paths. Each path is composed of one or more hops through the network.
329 #[derive(Clone, Hash, PartialEq, Eq)]
331 /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
332 /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
334 pub paths: Vec<Path>,
335 /// The `payment_params` parameter passed to [`find_route`].
336 /// This is used by `ChannelManager` to track information which may be required for retries,
337 /// provided back to you via [`Event::PaymentPathFailed`].
339 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
340 pub payment_params: Option<PaymentParameters>,
344 /// Returns the total amount of fees paid on this [`Route`].
346 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
347 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
348 pub fn get_total_fees(&self) -> u64 {
349 self.paths.iter().map(|path| path.fee_msat()).sum()
352 /// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
353 /// requested if we had to reach htlc_minimum_msat.
354 pub fn get_total_amount(&self) -> u64 {
355 self.paths.iter().map(|path| path.final_value_msat()).sum()
359 const SERIALIZATION_VERSION: u8 = 1;
360 const MIN_SERIALIZATION_VERSION: u8 = 1;
362 impl Writeable for Route {
363 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
364 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
365 (self.paths.len() as u64).write(writer)?;
366 let mut blinded_tails = Vec::new();
367 for path in self.paths.iter() {
368 (path.hops.len() as u8).write(writer)?;
369 for (idx, hop) in path.hops.iter().enumerate() {
371 if let Some(blinded_tail) = &path.blinded_tail {
372 if blinded_tails.is_empty() {
373 blinded_tails = Vec::with_capacity(path.hops.len());
375 blinded_tails.push(None);
378 blinded_tails.push(Some(blinded_tail));
379 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
382 write_tlv_fields!(writer, {
383 (1, self.payment_params, option),
384 (2, blinded_tails, optional_vec),
390 impl Readable for Route {
391 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
392 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
393 let path_count: u64 = Readable::read(reader)?;
394 if path_count == 0 { return Err(DecodeError::InvalidValue); }
395 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
396 let mut min_final_cltv_expiry_delta = u32::max_value();
397 for _ in 0..path_count {
398 let hop_count: u8 = Readable::read(reader)?;
399 let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
400 for _ in 0..hop_count {
401 hops.push(Readable::read(reader)?);
403 if hops.is_empty() { return Err(DecodeError::InvalidValue); }
404 min_final_cltv_expiry_delta =
405 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
406 paths.push(Path { hops, blinded_tail: None });
408 _init_and_read_tlv_fields!(reader, {
409 (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
410 (2, blinded_tails, optional_vec),
412 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
413 if blinded_tails.len() != 0 {
414 if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
415 for (mut path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
416 path.blinded_tail = blinded_tail_opt;
419 Ok(Route { paths, payment_params })
423 /// Parameters needed to find a [`Route`].
425 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
426 /// [`Event::PaymentPathFailed`].
428 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
429 #[derive(Clone, Debug, PartialEq, Eq)]
430 pub struct RouteParameters {
431 /// The parameters of the failed payment path.
432 pub payment_params: PaymentParameters,
434 /// The amount in msats sent on the failed payment path.
435 pub final_value_msat: u64,
438 impl Writeable for RouteParameters {
439 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
440 write_tlv_fields!(writer, {
441 (0, self.payment_params, required),
442 (2, self.final_value_msat, required),
443 // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
444 // `RouteParameters` directly. For compatibility, we write it here.
445 (4, self.payment_params.final_cltv_expiry_delta, required),
451 impl Readable for RouteParameters {
452 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
453 _init_and_read_tlv_fields!(reader, {
454 (0, payment_params, (required: ReadableArgs, 0)),
455 (2, final_value_msat, required),
456 (4, final_cltv_expiry_delta, required),
458 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
459 if payment_params.final_cltv_expiry_delta == 0 {
460 payment_params.final_cltv_expiry_delta = final_cltv_expiry_delta.0.unwrap();
464 final_value_msat: final_value_msat.0.unwrap(),
469 /// Maximum total CTLV difference we allow for a full payment path.
470 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
472 /// Maximum number of paths we allow an (MPP) payment to have.
473 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
474 // limits, but for now more than 10 paths likely carries too much one-path failure.
475 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
477 // The median hop CLTV expiry delta currently seen in the network.
478 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
480 // During routing, we only consider paths shorter than our maximum length estimate.
481 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
482 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
483 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
485 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
486 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
487 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
488 // (payment_secret and total_msat) = 93 bytes for the final hop.
489 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
490 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
491 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
493 /// The recipient of a payment.
494 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
495 pub struct PaymentParameters {
496 /// The node id of the payee.
497 pub payee_pubkey: PublicKey,
499 /// Features supported by the payee.
501 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
502 /// does not contain any features.
504 /// [`for_keysend`]: Self::for_keysend
505 pub features: Option<InvoiceFeatures>,
507 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
508 pub route_hints: Hints,
510 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
511 pub expiry_time: Option<u64>,
513 /// The maximum total CLTV delta we accept for the route.
514 /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
515 pub max_total_cltv_expiry_delta: u32,
517 /// The maximum number of paths that may be used by (MPP) payments.
518 /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
519 pub max_path_count: u8,
521 /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
522 /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
523 /// a lower value prefers to send larger MPP parts, potentially saturating channels and
524 /// increasing failure probability for those paths.
526 /// Note that this restriction will be relaxed during pathfinding after paths which meet this
527 /// restriction have been found. While paths which meet this criteria will be searched for, it
528 /// is ultimately up to the scorer to select them over other paths.
530 /// A value of 0 will allow payments up to and including a channel's total announced usable
531 /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
534 pub max_channel_saturation_power_of_half: u8,
536 /// A list of SCIDs which this payment was previously attempted over and which caused the
537 /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
539 pub previously_failed_channels: Vec<u64>,
541 /// The minimum CLTV delta at the end of the route. This value must not be zero.
542 pub final_cltv_expiry_delta: u32,
545 impl Writeable for PaymentParameters {
546 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
547 let mut clear_hints = &vec![];
548 let mut blinded_hints = &vec![];
549 match &self.route_hints {
550 Hints::Clear(hints) => clear_hints = hints,
551 Hints::Blinded(hints) => blinded_hints = hints,
553 write_tlv_fields!(writer, {
554 (0, self.payee_pubkey, required),
555 (1, self.max_total_cltv_expiry_delta, required),
556 (2, self.features, option),
557 (3, self.max_path_count, required),
558 (4, *clear_hints, vec_type),
559 (5, self.max_channel_saturation_power_of_half, required),
560 (6, self.expiry_time, option),
561 (7, self.previously_failed_channels, vec_type),
562 (8, *blinded_hints, optional_vec),
563 (9, self.final_cltv_expiry_delta, required),
569 impl ReadableArgs<u32> for PaymentParameters {
570 fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
571 _init_and_read_tlv_fields!(reader, {
572 (0, payee_pubkey, required),
573 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
574 (2, features, option),
575 (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
576 (4, route_hints, vec_type),
577 (5, max_channel_saturation_power_of_half, (default_value, 2)),
578 (6, expiry_time, option),
579 (7, previously_failed_channels, vec_type),
580 (8, blinded_route_hints, optional_vec),
581 (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
583 let clear_route_hints = route_hints.unwrap_or(vec![]);
584 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
585 let route_hints = if blinded_route_hints.len() != 0 {
586 if clear_route_hints.len() != 0 { return Err(DecodeError::InvalidValue) }
587 Hints::Blinded(blinded_route_hints)
589 Hints::Clear(clear_route_hints)
592 payee_pubkey: _init_tlv_based_struct_field!(payee_pubkey, required),
593 max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
595 max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
597 max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
599 previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
600 final_cltv_expiry_delta: _init_tlv_based_struct_field!(final_cltv_expiry_delta, (default_value, unused)),
606 impl PaymentParameters {
607 /// Creates a payee with the node id of the given `pubkey`.
609 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
611 pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
615 route_hints: Hints::Clear(vec![]),
617 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
618 max_path_count: DEFAULT_MAX_PATH_COUNT,
619 max_channel_saturation_power_of_half: 2,
620 previously_failed_channels: Vec::new(),
621 final_cltv_expiry_delta,
625 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
627 /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
629 pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
630 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta).with_features(InvoiceFeatures::for_keysend())
633 /// Includes the payee's features.
635 /// This is not exported to bindings users since bindings don't support move semantics
636 pub fn with_features(self, features: InvoiceFeatures) -> Self {
637 Self { features: Some(features), ..self }
640 /// Includes hints for routing to the payee.
642 /// This is not exported to bindings users since bindings don't support move semantics
643 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
644 Self { route_hints: Hints::Clear(route_hints), ..self }
647 /// Includes a payment expiration in seconds relative to the UNIX epoch.
649 /// This is not exported to bindings users since bindings don't support move semantics
650 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
651 Self { expiry_time: Some(expiry_time), ..self }
654 /// Includes a limit for the total CLTV expiry delta which is considered during routing
656 /// This is not exported to bindings users since bindings don't support move semantics
657 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
658 Self { max_total_cltv_expiry_delta, ..self }
661 /// Includes a limit for the maximum number of payment paths that may be used.
663 /// This is not exported to bindings users since bindings don't support move semantics
664 pub fn with_max_path_count(self, max_path_count: u8) -> Self {
665 Self { max_path_count, ..self }
668 /// Includes a limit for the maximum number of payment paths that may be used.
670 /// This is not exported to bindings users since bindings don't support move semantics
671 pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
672 Self { max_channel_saturation_power_of_half, ..self }
676 /// Routing hints for the tail of the route.
677 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
679 /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
680 /// will be included in the final [`Route`].
681 Blinded(Vec<(BlindedPayInfo, BlindedPath)>),
682 /// The recipient included these route hints in their BOLT11 invoice.
683 Clear(Vec<RouteHint>),
686 /// A list of hops along a payment path terminating with a channel to the recipient.
687 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
688 pub struct RouteHint(pub Vec<RouteHintHop>);
690 impl Writeable for RouteHint {
691 fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
692 (self.0.len() as u64).write(writer)?;
693 for hop in self.0.iter() {
700 impl Readable for RouteHint {
701 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
702 let hop_count: u64 = Readable::read(reader)?;
703 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
704 for _ in 0..hop_count {
705 hops.push(Readable::read(reader)?);
711 /// A channel descriptor for a hop along a payment path.
712 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
713 pub struct RouteHintHop {
714 /// The node_id of the non-target end of the route
715 pub src_node_id: PublicKey,
716 /// The short_channel_id of this channel
717 pub short_channel_id: u64,
718 /// The fees which must be paid to use this channel
719 pub fees: RoutingFees,
720 /// The difference in CLTV values between this node and the next node.
721 pub cltv_expiry_delta: u16,
722 /// The minimum value, in msat, which must be relayed to the next hop.
723 pub htlc_minimum_msat: Option<u64>,
724 /// The maximum value in msat available for routing with a single HTLC.
725 pub htlc_maximum_msat: Option<u64>,
728 impl_writeable_tlv_based!(RouteHintHop, {
729 (0, src_node_id, required),
730 (1, htlc_minimum_msat, option),
731 (2, short_channel_id, required),
732 (3, htlc_maximum_msat, option),
734 (6, cltv_expiry_delta, required),
737 #[derive(Eq, PartialEq)]
738 struct RouteGraphNode {
740 lowest_fee_to_node: u64,
741 total_cltv_delta: u32,
742 // The maximum value a yet-to-be-constructed payment path might flow through this node.
743 // This value is upper-bounded by us by:
744 // - how much is needed for a path being constructed
745 // - how much value can channels following this node (up to the destination) can contribute,
746 // considering their capacity and fees
747 value_contribution_msat: u64,
748 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
749 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
750 path_htlc_minimum_msat: u64,
751 /// All penalties incurred from this hop on the way to the destination, as calculated using
753 path_penalty_msat: u64,
754 /// The number of hops walked up to this node.
755 path_length_to_node: u8,
758 impl cmp::Ord for RouteGraphNode {
759 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
760 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
761 .saturating_add(other.path_penalty_msat);
762 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
763 .saturating_add(self.path_penalty_msat);
764 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
768 impl cmp::PartialOrd for RouteGraphNode {
769 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
770 Some(self.cmp(other))
774 /// A wrapper around the various hop representations.
776 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
777 #[derive(Clone, Debug)]
778 enum CandidateRouteHop<'a> {
779 /// A hop from the payer, where the outbound liquidity is known.
781 details: &'a ChannelDetails,
783 /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
785 info: DirectedChannelInfo<'a>,
786 short_channel_id: u64,
788 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
790 hint: &'a RouteHintHop,
794 impl<'a> CandidateRouteHop<'a> {
795 fn short_channel_id(&self) -> u64 {
797 CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
798 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
799 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
803 // NOTE: This may alloc memory so avoid calling it in a hot code path.
804 fn features(&self) -> ChannelFeatures {
806 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
807 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
808 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
812 fn cltv_expiry_delta(&self) -> u32 {
814 CandidateRouteHop::FirstHop { .. } => 0,
815 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
816 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
820 fn htlc_minimum_msat(&self) -> u64 {
822 CandidateRouteHop::FirstHop { .. } => 0,
823 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
824 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
828 fn fees(&self) -> RoutingFees {
830 CandidateRouteHop::FirstHop { .. } => RoutingFees {
831 base_msat: 0, proportional_millionths: 0,
833 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
834 CandidateRouteHop::PrivateHop { hint } => hint.fees,
838 fn effective_capacity(&self) -> EffectiveCapacity {
840 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
841 liquidity_msat: details.next_outbound_htlc_limit_msat,
843 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
844 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
850 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
851 let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
853 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
854 EffectiveCapacity::Infinite => u64::max_value(),
855 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
856 EffectiveCapacity::MaximumHTLC { amount_msat } =>
857 amount_msat.checked_shr(saturation_shift).unwrap_or(0),
858 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
859 cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
863 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
864 -> bool where I1::Item: PartialEq<I2::Item> {
866 let a = iter_a.next();
867 let b = iter_b.next();
868 if a.is_none() && b.is_none() { return true; }
869 if a.is_none() || b.is_none() { return false; }
870 if a.unwrap().ne(&b.unwrap()) { return false; }
874 /// It's useful to keep track of the hops associated with the fees required to use them,
875 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
876 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
877 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
879 struct PathBuildingHop<'a> {
880 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
881 // is a larger refactor and will require careful performance analysis.
883 candidate: CandidateRouteHop<'a>,
886 /// All the fees paid *after* this channel on the way to the destination
887 next_hops_fee_msat: u64,
888 /// Fee paid for the use of the current channel (see candidate.fees()).
889 /// The value will be actually deducted from the counterparty balance on the previous link.
890 hop_use_fee_msat: u64,
891 /// Used to compare channels when choosing the for routing.
892 /// Includes paying for the use of a hop and the following hops, as well as
893 /// an estimated cost of reaching this hop.
894 /// Might get stale when fees are recomputed. Primarily for internal use.
896 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
897 /// walk and may be invalid thereafter.
898 path_htlc_minimum_msat: u64,
899 /// All penalties incurred from this channel on the way to the destination, as calculated using
901 path_penalty_msat: u64,
902 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
903 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
904 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
905 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
906 /// avoid processing them again.
908 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
909 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
910 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
911 // value_contribution_msat, which requires tracking it here. See comments below where it is
912 // used for more info.
913 value_contribution_msat: u64,
916 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
917 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
918 let mut debug_struct = f.debug_struct("PathBuildingHop");
920 .field("node_id", &self.node_id)
921 .field("short_channel_id", &self.candidate.short_channel_id())
922 .field("total_fee_msat", &self.total_fee_msat)
923 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
924 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
925 .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)))
926 .field("path_penalty_msat", &self.path_penalty_msat)
927 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
928 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
929 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
930 let debug_struct = debug_struct
931 .field("value_contribution_msat", &self.value_contribution_msat);
932 debug_struct.finish()
936 // Instantiated with a list of hops with correct data in them collected during path finding,
937 // an instance of this struct should be further modified only via given methods.
939 struct PaymentPath<'a> {
940 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
943 impl<'a> PaymentPath<'a> {
944 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
945 fn get_value_msat(&self) -> u64 {
946 self.hops.last().unwrap().0.fee_msat
949 fn get_path_penalty_msat(&self) -> u64 {
950 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
953 fn get_total_fee_paid_msat(&self) -> u64 {
954 if self.hops.len() < 1 {
958 // Can't use next_hops_fee_msat because it gets outdated.
959 for (i, (hop, _)) in self.hops.iter().enumerate() {
960 if i != self.hops.len() - 1 {
961 result += hop.fee_msat;
967 fn get_cost_msat(&self) -> u64 {
968 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
971 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
972 // to change fees may result in an inconsistency.
974 // Sometimes we call this function right after constructing a path which is inconsistent in
975 // that it the value being transferred has decreased while we were doing path finding, leading
976 // to the fees being paid not lining up with the actual limits.
978 // Note that this function is not aware of the available_liquidity limit, and thus does not
979 // support increasing the value being transferred beyond what was selected during the initial
981 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
982 let mut total_fee_paid_msat = 0 as u64;
983 for i in (0..self.hops.len()).rev() {
984 let last_hop = i == self.hops.len() - 1;
986 // For non-last-hop, this value will represent the fees paid on the current hop. It
987 // will consist of the fees for the use of the next hop, and extra fees to match
988 // htlc_minimum_msat of the current channel. Last hop is handled separately.
989 let mut cur_hop_fees_msat = 0;
991 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
994 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
995 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
996 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
997 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
998 // set it too high just to maliciously take more fees by exploiting this
999 // match htlc_minimum_msat logic.
1000 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1001 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1002 // Note that there is a risk that *previous hops* (those closer to us, as we go
1003 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1005 // This might make us end up with a broken route, although this should be super-rare
1006 // in practice, both because of how healthy channels look like, and how we pick
1007 // channels in add_entry.
1008 // Also, this can't be exploited more heavily than *announce a free path and fail
1010 cur_hop_transferred_amount_msat += extra_fees_msat;
1011 total_fee_paid_msat += extra_fees_msat;
1012 cur_hop_fees_msat += extra_fees_msat;
1016 // Final hop is a special case: it usually has just value_msat (by design), but also
1017 // it still could overpay for the htlc_minimum_msat.
1018 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1020 // Propagate updated fees for the use of the channels to one hop back, where they
1021 // will be actually paid (fee_msat). The last hop is handled above separately.
1022 cur_hop.fee_msat = cur_hop_fees_msat;
1025 // Fee for the use of the current hop which will be deducted on the previous hop.
1026 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1027 // this channel is free for us.
1029 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1030 cur_hop.hop_use_fee_msat = new_fee;
1031 total_fee_paid_msat += new_fee;
1033 // It should not be possible because this function is called only to reduce the
1034 // value. In that case, compute_fee was already called with the same fees for
1035 // larger amount and there was no overflow.
1044 /// Calculate the fees required to route the given amount over a channel with the given fees.
1045 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1046 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1047 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1051 /// Calculate the fees required to route the given amount over a channel with the given fees,
1052 /// saturating to [`u64::max_value`].
1053 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1054 amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1055 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1056 .saturating_add(channel_fees.base_msat as u64)
1059 /// The default `features` we assume for a node in a route, when no `features` are known about that
1062 /// Default features are:
1063 /// * variable_length_onion_optional
1064 fn default_node_features() -> NodeFeatures {
1065 let mut features = NodeFeatures::empty();
1066 features.set_variable_length_onion_optional();
1070 /// Finds a route from us (payer) to the given target node (payee).
1072 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
1073 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1075 /// Private routing paths between a public node and the target may be included in `params.payee`.
1077 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1078 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1079 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1081 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1082 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1083 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1087 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
1088 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
1093 /// Panics if first_hops contains channels without short_channel_ids;
1094 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1096 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1097 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1098 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1099 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1100 our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1101 network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1102 scorer: &S, random_seed_bytes: &[u8; 32]
1103 ) -> Result<Route, LightningError>
1104 where L::Target: Logger, GL::Target: Logger {
1105 let graph_lock = network_graph.read_only();
1106 let final_cltv_expiry_delta = route_params.payment_params.final_cltv_expiry_delta;
1107 let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1108 route_params.final_value_msat, final_cltv_expiry_delta, logger, scorer,
1109 random_seed_bytes)?;
1110 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1114 pub(crate) fn get_route<L: Deref, S: Score>(
1115 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1116 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
1117 logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
1118 ) -> Result<Route, LightningError>
1119 where L::Target: Logger {
1120 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
1121 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1123 if payee_node_id == our_node_id {
1124 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1127 if final_value_msat > MAX_VALUE_MSAT {
1128 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1131 if final_value_msat == 0 {
1132 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1135 match &payment_params.route_hints {
1136 Hints::Clear(hints) => {
1137 for route in hints.iter() {
1138 for hop in &route.0 {
1139 if hop.src_node_id == payment_params.payee_pubkey {
1140 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1145 _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1148 if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1149 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});
1152 // TODO: Remove the explicit final_cltv_expiry_delta parameter
1153 debug_assert_eq!(final_cltv_expiry_delta, payment_params.final_cltv_expiry_delta);
1155 // The general routing idea is the following:
1156 // 1. Fill first/last hops communicated by the caller.
1157 // 2. Attempt to construct a path from payer to payee for transferring
1158 // any ~sufficient (described later) value.
1159 // If succeed, remember which channels were used and how much liquidity they have available,
1160 // so that future paths don't rely on the same liquidity.
1161 // 3. Proceed to the next step if:
1162 // - we hit the recommended target value;
1163 // - OR if we could not construct a new path. Any next attempt will fail too.
1164 // Otherwise, repeat step 2.
1165 // 4. See if we managed to collect paths which aggregately are able to transfer target value
1166 // (not recommended value).
1167 // 5. If yes, proceed. If not, fail routing.
1168 // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1169 // transferred up to the transfer target value.
1170 // 7. Reduce the value of the last path until we are sending only the target value.
1171 // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1172 // them so that we're not sending two HTLCs along the same path.
1174 // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1175 // distance from the payee
1177 // We are not a faithful Dijkstra's implementation because we can change values which impact
1178 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1179 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1180 // the value we are currently attempting to send over a path, we simply reduce the value being
1181 // sent along the path for any hops after that channel. This may imply that later fees (which
1182 // we've already tabulated) are lower because a smaller value is passing through the channels
1183 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1184 // channels which were selected earlier (and which may still be used for other paths without a
1185 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1188 // One potentially problematic case for this algorithm would be if there are many
1189 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1190 // graph walking), we may never find a path which is not liquidity-limited and has lower
1191 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1192 // Because we only consider paths with at least 5% of the total value being sent, the damage
1193 // from such a case should be limited, however this could be further reduced in the future by
1194 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1195 // limits for the purposes of fee calculation.
1197 // Alternatively, we could store more detailed path information in the heap (targets, below)
1198 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1199 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1200 // and practically (as we would need to store dynamically-allocated path information in heap
1201 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1202 // results of such an algorithm would likely be biased towards lower-value paths.
1204 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1205 // outside of our current search value, running a path search more times to gather candidate
1206 // paths at different values. While this may be acceptable, further path searches may increase
1207 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1208 // graph for candidate paths, calculating the maximum value which can realistically be sent at
1209 // the same time, remaining generic across different payment values.
1211 let network_channels = network_graph.channels();
1212 let network_nodes = network_graph.nodes();
1214 if payment_params.max_path_count == 0 {
1215 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1218 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1219 // it. If the payee supports it they're supposed to include it in the invoice, so that should
1221 let allow_mpp = if payment_params.max_path_count == 1 {
1223 } else if let Some(features) = &payment_params.features {
1224 features.supports_basic_mpp()
1225 } else if let Some(node) = network_nodes.get(&payee_node_id) {
1226 if let Some(node_info) = node.announcement_info.as_ref() {
1227 node_info.features.supports_basic_mpp()
1231 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1232 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
1233 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1236 // Prepare the data we'll use for payee-to-payer search by
1237 // inserting first hops suggested by the caller as targets.
1238 // Our search will then attempt to reach them while traversing from the payee node.
1239 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1240 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1241 if let Some(hops) = first_hops {
1243 if chan.get_outbound_payment_scid().is_none() {
1244 panic!("first_hops should be filled in with usable channels, not pending ones");
1246 if chan.counterparty.node_id == *our_node_pubkey {
1247 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1250 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1251 .or_insert(Vec::new())
1254 if first_hop_targets.is_empty() {
1255 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1259 // The main heap containing all candidate next-hops sorted by their score (max(fee,
1260 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1261 // adding duplicate entries when we find a better path to a given node.
1262 let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1264 // Map from node_id to information about the best current path to that node, including feerate
1266 let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1268 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1269 // indicating that we may wish to try again with a higher value, potentially paying to meet an
1270 // htlc_minimum with extra fees while still finding a cheaper path.
1271 let mut hit_minimum_limit;
1273 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1274 // We start with a path_value of the exact amount we want, and if that generates a route we may
1275 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1276 // amount we want in total across paths, selecting the best subset at the end.
1277 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1278 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1279 let mut path_value_msat = final_value_msat;
1281 // Routing Fragmentation Mitigation heuristic:
1283 // Routing fragmentation across many payment paths increases the overall routing
1284 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1285 // Taking too many smaller paths also increases the chance of payment failure.
1286 // Thus to avoid this effect, we require from our collected links to provide
1287 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1288 // This requirement is currently set to be 1/max_path_count of the payment
1289 // value to ensure we only ever return routes that do not violate this limit.
1290 let minimal_value_contribution_msat: u64 = if allow_mpp {
1291 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1296 // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1297 // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1298 // drop the requirement by setting this to 0.
1299 let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1301 // Keep track of how much liquidity has been used in selected channels. Used to determine
1302 // if the channel can be used by additional MPP paths or to inform path finding decisions. It is
1303 // aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
1304 // liquidity used in one direction will not offset any used in the opposite direction.
1305 let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
1306 HashMap::with_capacity(network_nodes.len());
1308 // Keeping track of how much value we already collected across other paths. Helps to decide
1309 // when we want to stop looking for new paths.
1310 let mut already_collected_value_msat = 0;
1312 for (_, channels) in first_hop_targets.iter_mut() {
1313 // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1314 // most like to use.
1316 // First, if channels are below `recommended_value_msat`, sort them in descending order,
1317 // preferring larger channels to avoid splitting the payment into more MPP parts than is
1320 // Second, because simply always sorting in descending order would always use our largest
1321 // available outbound capacity, needlessly fragmenting our available channel capacities,
1322 // sort channels above `recommended_value_msat` in ascending order, preferring channels
1323 // which have enough, but not too much, capacity for the payment.
1324 channels.sort_unstable_by(|chan_a, chan_b| {
1325 if chan_b.next_outbound_htlc_limit_msat < recommended_value_msat || chan_a.next_outbound_htlc_limit_msat < recommended_value_msat {
1326 // Sort in descending order
1327 chan_b.next_outbound_htlc_limit_msat.cmp(&chan_a.next_outbound_htlc_limit_msat)
1329 // Sort in ascending order
1330 chan_a.next_outbound_htlc_limit_msat.cmp(&chan_b.next_outbound_htlc_limit_msat)
1335 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
1337 macro_rules! add_entry {
1338 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1339 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1340 // since that value has to be transferred over this channel.
1341 // Returns whether this channel caused an update to `targets`.
1342 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1343 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1344 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1345 // We "return" whether we updated the path at the end, via this:
1346 let mut did_add_update_path_to_src_node = false;
1347 // Channels to self should not be used. This is more of belt-and-suspenders, because in
1348 // practice these cases should be caught earlier:
1349 // - for regular channels at channel announcement (TODO)
1350 // - for first and last hops early in get_route
1351 if $src_node_id != $dest_node_id {
1352 let short_channel_id = $candidate.short_channel_id();
1353 let effective_capacity = $candidate.effective_capacity();
1354 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1356 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1357 // It may be misleading because we might later choose to reduce the value transferred
1358 // over these channels, and the channel which was insufficient might become sufficient.
1359 // Worst case: we drop a good channel here because it can't cover the high following
1360 // fees caused by one expensive channel, but then this channel could have been used
1361 // if the amount being transferred over this path is lower.
1362 // We do this for now, but this is a subject for removal.
1363 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1364 let used_liquidity_msat = used_channel_liquidities
1365 .get(&(short_channel_id, $src_node_id < $dest_node_id))
1366 .map_or(0, |used_liquidity_msat| {
1367 available_value_contribution_msat = available_value_contribution_msat
1368 .saturating_sub(*used_liquidity_msat);
1369 *used_liquidity_msat
1372 // Verify the liquidity offered by this channel complies to the minimal contribution.
1373 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1374 // Do not consider candidate hops that would exceed the maximum path length.
1375 let path_length_to_node = $next_hops_path_length + 1;
1376 let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1378 // Do not consider candidates that exceed the maximum total cltv expiry limit.
1379 // In order to already account for some of the privacy enhancing random CLTV
1380 // expiry delta offset we add on top later, we subtract a rough estimate
1381 // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1382 let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1383 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1384 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1385 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1386 .saturating_add($candidate.cltv_expiry_delta());
1387 let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1389 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1390 // Includes paying fees for the use of the following channels.
1391 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1392 Some(result) => result,
1393 // Can't overflow due to how the values were computed right above.
1394 None => unreachable!(),
1396 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1397 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1398 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1400 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1401 let may_overpay_to_meet_path_minimum_msat =
1402 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1403 recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1404 (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1405 recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1407 let payment_failed_on_this_channel =
1408 payment_params.previously_failed_channels.contains(&short_channel_id);
1410 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1411 // bother considering this channel. If retrying with recommended_value_msat may
1412 // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1413 // around again with a higher amount.
1414 if !contributes_sufficient_value || exceeds_max_path_length ||
1415 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1416 // Path isn't useful, ignore it and move on.
1417 } else if may_overpay_to_meet_path_minimum_msat {
1418 hit_minimum_limit = true;
1419 } else if over_path_minimum_msat {
1420 // Note that low contribution here (limited by available_liquidity_msat)
1421 // might violate htlc_minimum_msat on the hops which are next along the
1422 // payment path (upstream to the payee). To avoid that, we recompute
1423 // path fees knowing the final path contribution after constructing it.
1424 let path_htlc_minimum_msat = cmp::max(
1425 compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1426 .saturating_add($next_hops_path_htlc_minimum_msat),
1427 $candidate.htlc_minimum_msat());
1428 let hm_entry = dist.entry($src_node_id);
1429 let old_entry = hm_entry.or_insert_with(|| {
1430 // If there was previously no known way to access the source node
1431 // (recall it goes payee-to-payer) of short_channel_id, first add a
1432 // semi-dummy record just to compute the fees to reach the source node.
1433 // This will affect our decision on selecting short_channel_id
1434 // as a way to reach the $dest_node_id.
1436 node_id: $dest_node_id.clone(),
1437 candidate: $candidate.clone(),
1439 next_hops_fee_msat: u64::max_value(),
1440 hop_use_fee_msat: u64::max_value(),
1441 total_fee_msat: u64::max_value(),
1442 path_htlc_minimum_msat,
1443 path_penalty_msat: u64::max_value(),
1444 was_processed: false,
1445 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1446 value_contribution_msat,
1450 #[allow(unused_mut)] // We only use the mut in cfg(test)
1451 let mut should_process = !old_entry.was_processed;
1452 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1454 // In test/fuzzing builds, we do extra checks to make sure the skipping
1455 // of already-seen nodes only happens in cases we expect (see below).
1456 if !should_process { should_process = true; }
1460 let mut hop_use_fee_msat = 0;
1461 let mut total_fee_msat: u64 = $next_hops_fee_msat;
1463 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1464 // will have the same effective-fee
1465 if $src_node_id != our_node_id {
1466 // Note that `u64::max_value` means we'll always fail the
1467 // `old_entry.total_fee_msat > total_fee_msat` check below
1468 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1469 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1472 let channel_usage = ChannelUsage {
1473 amount_msat: amount_to_transfer_over_msat,
1474 inflight_htlc_msat: used_liquidity_msat,
1477 let channel_penalty_msat = scorer.channel_penalty_msat(
1478 short_channel_id, &$src_node_id, &$dest_node_id, channel_usage
1480 let path_penalty_msat = $next_hops_path_penalty_msat
1481 .saturating_add(channel_penalty_msat);
1482 let new_graph_node = RouteGraphNode {
1483 node_id: $src_node_id,
1484 lowest_fee_to_node: total_fee_msat,
1485 total_cltv_delta: hop_total_cltv_delta,
1486 value_contribution_msat,
1487 path_htlc_minimum_msat,
1489 path_length_to_node,
1492 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1493 // if this way is cheaper than the already known
1494 // (considering the cost to "reach" this channel from the route destination,
1495 // the cost of using this channel,
1496 // and the cost of routing to the source node of this channel).
1497 // Also, consider that htlc_minimum_msat_difference, because we might end up
1498 // paying it. Consider the following exploit:
1499 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1500 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1501 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1502 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1504 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1505 // but it may require additional tracking - we don't want to double-count
1506 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1507 // can't use something that may decrease on future hops.
1508 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1509 .saturating_add(old_entry.path_penalty_msat);
1510 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1511 .saturating_add(path_penalty_msat);
1513 if !old_entry.was_processed && new_cost < old_cost {
1514 targets.push(new_graph_node);
1515 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1516 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1517 old_entry.total_fee_msat = total_fee_msat;
1518 old_entry.node_id = $dest_node_id.clone();
1519 old_entry.candidate = $candidate.clone();
1520 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1521 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1522 old_entry.path_penalty_msat = path_penalty_msat;
1523 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1525 old_entry.value_contribution_msat = value_contribution_msat;
1527 did_add_update_path_to_src_node = true;
1528 } else if old_entry.was_processed && new_cost < old_cost {
1529 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1531 // If we're skipping processing a node which was previously
1532 // processed even though we found another path to it with a
1533 // cheaper fee, check that it was because the second path we
1534 // found (which we are processing now) has a lower value
1535 // contribution due to an HTLC minimum limit.
1537 // e.g. take a graph with two paths from node 1 to node 2, one
1538 // through channel A, and one through channel B. Channel A and
1539 // B are both in the to-process heap, with their scores set by
1540 // a higher htlc_minimum than fee.
1541 // Channel A is processed first, and the channels onwards from
1542 // node 1 are added to the to-process heap. Thereafter, we pop
1543 // Channel B off of the heap, note that it has a much more
1544 // restrictive htlc_maximum_msat, and recalculate the fees for
1545 // all of node 1's channels using the new, reduced, amount.
1547 // This would be bogus - we'd be selecting a higher-fee path
1548 // with a lower htlc_maximum_msat instead of the one we'd
1549 // already decided to use.
1550 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1552 value_contribution_msat + path_penalty_msat <
1553 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1561 did_add_update_path_to_src_node
1565 let default_node_features = default_node_features();
1567 // Find ways (channels with destination) to reach a given node and store them
1568 // in the corresponding data structures (routing graph etc).
1569 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1570 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1571 // This data can later be helpful to optimize routing (pay lower fees).
1572 macro_rules! add_entries_to_cheapest_to_target_node {
1573 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1574 $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1575 $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1576 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1577 let was_processed = elem.was_processed;
1578 elem.was_processed = true;
1581 // Entries are added to dist in add_entry!() when there is a channel from a node.
1582 // Because there are no channels from payee, it will not have a dist entry at this point.
1583 // If we're processing any other node, it is always be the result of a channel from it.
1584 assert_eq!($node_id, payee_node_id);
1589 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1590 for details in first_channels {
1591 let candidate = CandidateRouteHop::FirstHop { details };
1592 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1593 $next_hops_value_contribution,
1594 $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1595 $next_hops_cltv_delta, $next_hops_path_length);
1599 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1602 &default_node_features
1605 if !features.requires_unknown_bits() {
1606 for chan_id in $node.channels.iter() {
1607 let chan = network_channels.get(chan_id).unwrap();
1608 if !chan.features.requires_unknown_bits() {
1609 if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1610 if first_hops.is_none() || *source != our_node_id {
1611 if directed_channel.direction().enabled {
1612 let candidate = CandidateRouteHop::PublicHop {
1613 info: directed_channel,
1614 short_channel_id: *chan_id,
1616 add_entry!(candidate, *source, $node_id,
1617 $fee_to_target_msat,
1618 $next_hops_value_contribution,
1619 $next_hops_path_htlc_minimum_msat,
1620 $next_hops_path_penalty_msat,
1621 $next_hops_cltv_delta, $next_hops_path_length);
1632 let mut payment_paths = Vec::<PaymentPath>::new();
1634 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1635 'paths_collection: loop {
1636 // For every new path, start from scratch, except for used_channel_liquidities, which
1637 // helps to avoid reusing previously selected paths in future iterations.
1640 hit_minimum_limit = false;
1642 // If first hop is a private channel and the only way to reach the payee, this is the only
1643 // place where it could be added.
1644 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1645 for details in first_channels {
1646 let candidate = CandidateRouteHop::FirstHop { details };
1647 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat,
1649 log_trace!(logger, "{} direct route to payee via SCID {}",
1650 if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1654 // Add the payee as a target, so that the payee-to-payer
1655 // search algorithm knows what to start with.
1656 match network_nodes.get(&payee_node_id) {
1657 // The payee is not in our network graph, so nothing to add here.
1658 // There is still a chance of reaching them via last_hops though,
1659 // so don't yet fail the payment here.
1660 // If not, targets.pop() will not even let us enter the loop in step 2.
1663 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0, 0);
1668 // If a caller provided us with last hops, add them to routing targets. Since this happens
1669 // earlier than general path finding, they will be somewhat prioritized, although currently
1670 // it matters only if the fees are exactly the same.
1671 let route_hints = match &payment_params.route_hints {
1672 Hints::Clear(hints) => hints,
1673 _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1675 for route in route_hints.iter().filter(|route| !route.0.is_empty()) {
1676 let first_hop_in_route = &(route.0)[0];
1677 let have_hop_src_in_graph =
1678 // Only add the hops in this route to our candidate set if either
1679 // we have a direct channel to the first hop or the first hop is
1680 // in the regular network graph.
1681 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1682 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1683 if have_hop_src_in_graph {
1684 // We start building the path from reverse, i.e., from payee
1685 // to the first RouteHintHop in the path.
1686 let hop_iter = route.0.iter().rev();
1687 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1688 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1689 let mut hop_used = true;
1690 let mut aggregate_next_hops_fee_msat: u64 = 0;
1691 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1692 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1693 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1694 let mut aggregate_next_hops_path_length: u8 = 0;
1696 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1697 let source = NodeId::from_pubkey(&hop.src_node_id);
1698 let target = NodeId::from_pubkey(&prev_hop_id);
1699 let candidate = network_channels
1700 .get(&hop.short_channel_id)
1701 .and_then(|channel| channel.as_directed_to(&target))
1702 .map(|(info, _)| CandidateRouteHop::PublicHop {
1704 short_channel_id: hop.short_channel_id,
1706 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1708 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat,
1709 path_value_msat, aggregate_next_hops_path_htlc_minimum_msat,
1710 aggregate_next_hops_path_penalty_msat,
1711 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length) {
1712 // If this hop was not used then there is no use checking the preceding
1713 // hops in the RouteHint. We can break by just searching for a direct
1714 // channel between last checked hop and first_hop_targets.
1718 let used_liquidity_msat = used_channel_liquidities
1719 .get(&(hop.short_channel_id, source < target)).copied().unwrap_or(0);
1720 let channel_usage = ChannelUsage {
1721 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1722 inflight_htlc_msat: used_liquidity_msat,
1723 effective_capacity: candidate.effective_capacity(),
1725 let channel_penalty_msat = scorer.channel_penalty_msat(
1726 hop.short_channel_id, &source, &target, channel_usage
1728 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1729 .saturating_add(channel_penalty_msat);
1731 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1732 .saturating_add(hop.cltv_expiry_delta as u32);
1734 aggregate_next_hops_path_length = aggregate_next_hops_path_length
1737 // Searching for a direct channel between last checked hop and first_hop_targets
1738 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1739 for details in first_channels {
1740 let candidate = CandidateRouteHop::FirstHop { details };
1741 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
1742 aggregate_next_hops_fee_msat, path_value_msat,
1743 aggregate_next_hops_path_htlc_minimum_msat,
1744 aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta,
1745 aggregate_next_hops_path_length);
1753 // In the next values of the iterator, the aggregate fees already reflects
1754 // the sum of value sent from payer (final_value_msat) and routing fees
1755 // for the last node in the RouteHint. We need to just add the fees to
1756 // route through the current node so that the preceding node (next iteration)
1758 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1759 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1760 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1762 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1763 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1764 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1765 .checked_add(hop_htlc_minimum_msat_inc);
1766 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1768 if idx == route.0.len() - 1 {
1769 // The last hop in this iterator is the first hop in
1770 // overall RouteHint.
1771 // If this hop connects to a node with which we have a direct channel,
1772 // ignore the network graph and, if the last hop was added, add our
1773 // direct channel to the candidate set.
1775 // Note that we *must* check if the last hop was added as `add_entry`
1776 // always assumes that the third argument is a node to which we have a
1778 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1779 for details in first_channels {
1780 let candidate = CandidateRouteHop::FirstHop { details };
1781 add_entry!(candidate, our_node_id,
1782 NodeId::from_pubkey(&hop.src_node_id),
1783 aggregate_next_hops_fee_msat, path_value_msat,
1784 aggregate_next_hops_path_htlc_minimum_msat,
1785 aggregate_next_hops_path_penalty_msat,
1786 aggregate_next_hops_cltv_delta,
1787 aggregate_next_hops_path_length);
1795 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1797 // At this point, targets are filled with the data from first and
1798 // last hops communicated by the caller, and the payment receiver.
1799 let mut found_new_path = false;
1802 // If this loop terminates due the exhaustion of targets, two situations are possible:
1803 // - not enough outgoing liquidity:
1804 // 0 < already_collected_value_msat < final_value_msat
1805 // - enough outgoing liquidity:
1806 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1807 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1808 // paths_collection will be stopped because found_new_path==false.
1809 // This is not necessarily a routing failure.
1810 '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() {
1812 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1813 // traversing the graph and arrange the path out of what we found.
1814 if node_id == our_node_id {
1815 let mut new_entry = dist.remove(&our_node_id).unwrap();
1816 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
1819 let mut features_set = false;
1820 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1821 for details in first_channels {
1822 if details.get_outbound_payment_scid().unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1823 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1824 features_set = true;
1830 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1831 if let Some(node_info) = node.announcement_info.as_ref() {
1832 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1834 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
1837 // We can fill in features for everything except hops which were
1838 // provided via the invoice we're paying. We could guess based on the
1839 // recipient's features but for now we simply avoid guessing at all.
1843 // Means we succesfully traversed from the payer to the payee, now
1844 // save this path for the payment route. Also, update the liquidity
1845 // remaining on the used hops, so that we take them into account
1846 // while looking for more paths.
1847 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1851 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1852 Some(payment_hop) => payment_hop,
1853 // We can't arrive at None because, if we ever add an entry to targets,
1854 // we also fill in the entry in dist (see add_entry!).
1855 None => unreachable!(),
1857 // We "propagate" the fees one hop backward (topologically) here,
1858 // so that fees paid for a HTLC forwarding on the current channel are
1859 // associated with the previous channel (where they will be subtracted).
1860 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1861 ordered_hops.push((new_entry.clone(), default_node_features.clone()));
1863 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1864 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1866 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1867 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1869 let mut payment_path = PaymentPath {hops: ordered_hops};
1871 // We could have possibly constructed a slightly inconsistent path: since we reduce
1872 // value being transferred along the way, we could have violated htlc_minimum_msat
1873 // on some channels we already passed (assuming dest->source direction). Here, we
1874 // recompute the fees again, so that if that's the case, we match the currently
1875 // underpaid htlc_minimum_msat with fees.
1876 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
1877 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
1878 payment_path.update_value_and_recompute_fees(value_contribution_msat);
1880 // Since a path allows to transfer as much value as
1881 // the smallest channel it has ("bottleneck"), we should recompute
1882 // the fees so sender HTLC don't overpay fees when traversing
1883 // larger channels than the bottleneck. This may happen because
1884 // when we were selecting those channels we were not aware how much value
1885 // this path will transfer, and the relative fee for them
1886 // might have been computed considering a larger value.
1887 // Remember that we used these channels so that we don't rely
1888 // on the same liquidity in future paths.
1889 let mut prevented_redundant_path_selection = false;
1890 let prev_hop_iter = core::iter::once(&our_node_id)
1891 .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
1892 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
1893 let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
1894 let used_liquidity_msat = used_channel_liquidities
1895 .entry((hop.candidate.short_channel_id(), *prev_hop < hop.node_id))
1896 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
1897 .or_insert(spent_on_hop_msat);
1898 let hop_capacity = hop.candidate.effective_capacity();
1899 let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
1900 if *used_liquidity_msat == hop_max_msat {
1901 // If this path used all of this channel's available liquidity, we know
1902 // this path will not be selected again in the next loop iteration.
1903 prevented_redundant_path_selection = true;
1905 debug_assert!(*used_liquidity_msat <= hop_max_msat);
1907 if !prevented_redundant_path_selection {
1908 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1909 // we'll probably end up picking the same path again on the next iteration.
1910 // Decrease the available liquidity of a hop in the middle of the path.
1911 let victim_scid = payment_path.hops[(payment_path.hops.len()) / 2].0.candidate.short_channel_id();
1912 let exhausted = u64::max_value();
1913 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1914 *used_channel_liquidities.entry((victim_scid, false)).or_default() = exhausted;
1915 *used_channel_liquidities.entry((victim_scid, true)).or_default() = exhausted;
1918 // Track the total amount all our collected paths allow to send so that we know
1919 // when to stop looking for more paths
1920 already_collected_value_msat += value_contribution_msat;
1922 payment_paths.push(payment_path);
1923 found_new_path = true;
1924 break 'path_construction;
1927 // If we found a path back to the payee, we shouldn't try to process it again. This is
1928 // the equivalent of the `elem.was_processed` check in
1929 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1930 if node_id == payee_node_id { continue 'path_construction; }
1932 // Otherwise, since the current target node is not us,
1933 // keep "unrolling" the payment graph from payee to payer by
1934 // finding a way to reach the current target from the payer side.
1935 match network_nodes.get(&node_id) {
1938 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
1939 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
1940 total_cltv_delta, path_length_to_node);
1946 if !found_new_path && channel_saturation_pow_half != 0 {
1947 channel_saturation_pow_half = 0;
1948 continue 'paths_collection;
1950 // If we don't support MPP, no use trying to gather more value ever.
1951 break 'paths_collection;
1955 // Stop either when the recommended value is reached or if no new path was found in this
1957 // In the latter case, making another path finding attempt won't help,
1958 // because we deterministically terminated the search due to low liquidity.
1959 if !found_new_path && channel_saturation_pow_half != 0 {
1960 channel_saturation_pow_half = 0;
1961 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1962 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1963 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1964 break 'paths_collection;
1965 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1966 // Further, if this was our first walk of the graph, and we weren't limited by an
1967 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1968 // limited by an htlc_minimum_msat value, find another path with a higher value,
1969 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1970 // still keeping a lower total fee than this path.
1971 if !hit_minimum_limit {
1972 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1973 break 'paths_collection;
1975 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1976 path_value_msat = recommended_value_msat;
1981 if payment_paths.len() == 0 {
1982 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1985 if already_collected_value_msat < final_value_msat {
1986 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1990 let mut selected_route = payment_paths;
1992 debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
1993 let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
1995 // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
1996 // the value they contribute towards the payment amount.
1997 // We sort in descending order as we will remove from the front in `retain`, next.
1998 selected_route.sort_unstable_by(|a, b|
1999 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2000 .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2003 // We should make sure that at least 1 path left.
2004 let mut paths_left = selected_route.len();
2005 selected_route.retain(|path| {
2006 if paths_left == 1 {
2009 let path_value_msat = path.get_value_msat();
2010 if path_value_msat <= overpaid_value_msat {
2011 overpaid_value_msat -= path_value_msat;
2017 debug_assert!(selected_route.len() > 0);
2019 if overpaid_value_msat != 0 {
2021 // Now, subtract the remaining overpaid value from the most-expensive path.
2022 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2023 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2024 selected_route.sort_unstable_by(|a, b| {
2025 let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2026 let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2027 a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2029 let expensive_payment_path = selected_route.first_mut().unwrap();
2031 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2032 // can't go negative.
2033 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2034 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2038 // Sort by the path itself and combine redundant paths.
2039 // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2040 // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2042 selected_route.sort_unstable_by_key(|path| {
2043 let mut key = [0u64; MAX_PATH_LENGTH_ESTIMATE as usize];
2044 debug_assert!(path.hops.len() <= key.len());
2045 for (scid, key) in path.hops.iter().map(|h| h.0.candidate.short_channel_id()).zip(key.iter_mut()) {
2050 for idx in 0..(selected_route.len() - 1) {
2051 if idx + 1 >= selected_route.len() { break; }
2052 if iter_equal(selected_route[idx ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
2053 selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
2054 let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2055 selected_route[idx].update_value_and_recompute_fees(new_value);
2056 selected_route.remove(idx + 1);
2060 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
2061 for payment_path in selected_route {
2062 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
2064 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)})?,
2065 node_features: node_features.clone(),
2066 short_channel_id: payment_hop.candidate.short_channel_id(),
2067 channel_features: payment_hop.candidate.features(),
2068 fee_msat: payment_hop.fee_msat,
2069 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
2071 }).collect::<Vec<_>>();
2072 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2073 // applicable for the previous hop.
2074 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
2075 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
2077 selected_paths.push(path);
2079 // Make sure we would never create a route with more paths than we allow.
2080 debug_assert!(selected_paths.len() <= payment_params.max_path_count.into());
2082 if let Some(features) = &payment_params.features {
2083 for path in selected_paths.iter_mut() {
2084 if let Ok(route_hop) = path.last_mut().unwrap() {
2085 route_hop.node_features = features.to_context();
2090 let mut paths: Vec<Path> = Vec::new();
2091 for results_vec in selected_paths {
2092 let mut hops = Vec::with_capacity(results_vec.len());
2093 for res in results_vec { hops.push(res?); }
2094 paths.push(Path { hops, blinded_tail: None });
2098 payment_params: Some(payment_params.clone()),
2100 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
2104 // When an adversarial intermediary node observes a payment, it may be able to infer its
2105 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2106 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2107 // payment path by adding a randomized 'shadow route' offset to the final hop.
2108 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2109 network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2111 let network_channels = network_graph.channels();
2112 let network_nodes = network_graph.nodes();
2114 for path in route.paths.iter_mut() {
2115 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2117 // Remember the last three nodes of the random walk and avoid looping back on them.
2118 // Init with the last three nodes from the actual path, if possible.
2119 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2120 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2121 NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2123 // Choose the last publicly known node as the starting point for the random walk.
2124 let mut cur_hop: Option<NodeId> = None;
2125 let mut path_nonce = [0u8; 12];
2126 if let Some(starting_hop) = path.hops.iter().rev()
2127 .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2128 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2129 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2132 // Init PRNG with the path-dependant nonce, which is static for private paths.
2133 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2134 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2136 // Pick a random path length in [1 .. 3]
2137 prng.process_in_place(&mut random_path_bytes);
2138 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2140 for random_hop in 0..random_walk_length {
2141 // If we don't find a suitable offset in the public network graph, we default to
2142 // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2143 let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2145 if let Some(cur_node_id) = cur_hop {
2146 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2147 // Randomly choose the next unvisited hop.
2148 prng.process_in_place(&mut random_path_bytes);
2149 if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2150 .checked_rem(cur_node.channels.len())
2151 .and_then(|index| cur_node.channels.get(index))
2152 .and_then(|id| network_channels.get(id)) {
2153 random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2154 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2155 nodes_to_avoid[random_hop] = *next_id;
2156 random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2157 cur_hop = Some(*next_id);
2164 shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2165 .checked_add(random_hop_offset)
2166 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2169 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2170 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2171 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2173 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2174 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2175 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2176 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2177 max_path_offset = cmp::max(
2178 max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2179 max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2180 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2182 // Add 'shadow' CLTV offset to the final hop
2183 if let Some(tail) = path.blinded_tail.as_mut() {
2184 tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2185 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2187 if let Some(last_hop) = path.hops.last_mut() {
2188 last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2189 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2194 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2195 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2197 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2198 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2199 our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2200 network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2201 ) -> Result<Route, LightningError>
2202 where L::Target: Logger, GL::Target: Logger {
2203 let graph_lock = network_graph.read_only();
2204 let mut route = build_route_from_hops_internal(
2205 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2206 route_params.final_value_msat, route_params.payment_params.final_cltv_expiry_delta,
2207 logger, random_seed_bytes)?;
2208 add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2212 fn build_route_from_hops_internal<L: Deref>(
2213 our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2214 network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, final_cltv_expiry_delta: u32,
2215 logger: L, random_seed_bytes: &[u8; 32]
2216 ) -> Result<Route, LightningError> where L::Target: Logger {
2219 our_node_id: NodeId,
2220 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2223 impl Score for HopScorer {
2224 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2225 _usage: ChannelUsage) -> u64
2227 let mut cur_id = self.our_node_id;
2228 for i in 0..self.hop_ids.len() {
2229 if let Some(next_id) = self.hop_ids[i] {
2230 if cur_id == *source && next_id == *target {
2241 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2243 fn payment_path_successful(&mut self, _path: &Path) {}
2245 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2247 fn probe_successful(&mut self, _path: &Path) {}
2250 impl<'a> Writeable for HopScorer {
2252 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2257 if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2258 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2261 let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2262 let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2263 for i in 0..hops.len() {
2264 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2267 let scorer = HopScorer { our_node_id, hop_ids };
2269 get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2270 final_cltv_expiry_delta, logger, &scorer, random_seed_bytes)
2275 use crate::blinded_path::{BlindedHop, BlindedPath};
2276 use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2277 use crate::routing::utxo::UtxoResult;
2278 use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2279 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2280 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2281 use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringParameters};
2282 use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2283 use crate::chain::transaction::OutPoint;
2284 use crate::chain::keysinterface::EntropySource;
2285 use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2286 use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2287 use crate::ln::channelmanager;
2288 use crate::util::config::UserConfig;
2289 use crate::util::test_utils as ln_test_utils;
2290 use crate::util::chacha20::ChaCha20;
2291 use crate::util::ser::{Readable, Writeable};
2293 use crate::util::ser::Writer;
2295 use bitcoin::hashes::Hash;
2296 use bitcoin::network::constants::Network;
2297 use bitcoin::blockdata::constants::genesis_block;
2298 use bitcoin::blockdata::script::Builder;
2299 use bitcoin::blockdata::opcodes;
2300 use bitcoin::blockdata::transaction::TxOut;
2304 use bitcoin::secp256k1::{PublicKey,SecretKey};
2305 use bitcoin::secp256k1::Secp256k1;
2307 use crate::io::Cursor;
2308 use crate::prelude::*;
2309 use crate::sync::Arc;
2311 use core::convert::TryInto;
2313 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2314 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2315 channelmanager::ChannelDetails {
2316 channel_id: [0; 32],
2317 counterparty: channelmanager::ChannelCounterparty {
2320 unspendable_punishment_reserve: 0,
2321 forwarding_info: None,
2322 outbound_htlc_minimum_msat: None,
2323 outbound_htlc_maximum_msat: None,
2325 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2328 outbound_scid_alias: None,
2329 inbound_scid_alias: None,
2330 channel_value_satoshis: 0,
2333 outbound_capacity_msat,
2334 next_outbound_htlc_limit_msat: outbound_capacity_msat,
2335 inbound_capacity_msat: 42,
2336 unspendable_punishment_reserve: None,
2337 confirmations_required: None,
2338 confirmations: None,
2339 force_close_spend_delay: None,
2340 is_outbound: true, is_channel_ready: true,
2341 is_usable: true, is_public: true,
2342 inbound_htlc_minimum_msat: None,
2343 inbound_htlc_maximum_msat: None,
2345 feerate_sat_per_1000_weight: None
2350 fn simple_route_test() {
2351 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2352 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2353 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2354 let scorer = ln_test_utils::TestScorer::new();
2355 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2356 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2358 // Simple route to 2 via 1
2360 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) {
2361 assert_eq!(err, "Cannot send a payment of 0 msat");
2362 } else { panic!(); }
2364 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2365 assert_eq!(route.paths[0].hops.len(), 2);
2367 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2368 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2369 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2370 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2371 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2372 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2374 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2375 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2376 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2377 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2378 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2379 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2383 fn invalid_first_hop_test() {
2384 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2385 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2386 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2387 let scorer = ln_test_utils::TestScorer::new();
2388 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2389 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2391 // Simple route to 2 via 1
2393 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2395 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2396 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) {
2397 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2398 } else { panic!(); }
2400 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2401 assert_eq!(route.paths[0].hops.len(), 2);
2405 fn htlc_minimum_test() {
2406 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2407 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2408 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2409 let scorer = ln_test_utils::TestScorer::new();
2410 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2411 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2413 // Simple route to 2 via 1
2415 // Disable other paths
2416 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2417 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2418 short_channel_id: 12,
2420 flags: 2, // to disable
2421 cltv_expiry_delta: 0,
2422 htlc_minimum_msat: 0,
2423 htlc_maximum_msat: MAX_VALUE_MSAT,
2425 fee_proportional_millionths: 0,
2426 excess_data: Vec::new()
2428 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2429 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2430 short_channel_id: 3,
2432 flags: 2, // to disable
2433 cltv_expiry_delta: 0,
2434 htlc_minimum_msat: 0,
2435 htlc_maximum_msat: MAX_VALUE_MSAT,
2437 fee_proportional_millionths: 0,
2438 excess_data: Vec::new()
2440 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2442 short_channel_id: 13,
2444 flags: 2, // to disable
2445 cltv_expiry_delta: 0,
2446 htlc_minimum_msat: 0,
2447 htlc_maximum_msat: MAX_VALUE_MSAT,
2449 fee_proportional_millionths: 0,
2450 excess_data: Vec::new()
2452 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2454 short_channel_id: 6,
2456 flags: 2, // to disable
2457 cltv_expiry_delta: 0,
2458 htlc_minimum_msat: 0,
2459 htlc_maximum_msat: MAX_VALUE_MSAT,
2461 fee_proportional_millionths: 0,
2462 excess_data: Vec::new()
2464 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2466 short_channel_id: 7,
2468 flags: 2, // to disable
2469 cltv_expiry_delta: 0,
2470 htlc_minimum_msat: 0,
2471 htlc_maximum_msat: MAX_VALUE_MSAT,
2473 fee_proportional_millionths: 0,
2474 excess_data: Vec::new()
2477 // Check against amount_to_transfer_over_msat.
2478 // Set minimal HTLC of 200_000_000 msat.
2479 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2480 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2481 short_channel_id: 2,
2484 cltv_expiry_delta: 0,
2485 htlc_minimum_msat: 200_000_000,
2486 htlc_maximum_msat: MAX_VALUE_MSAT,
2488 fee_proportional_millionths: 0,
2489 excess_data: Vec::new()
2492 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2494 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2495 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2496 short_channel_id: 4,
2499 cltv_expiry_delta: 0,
2500 htlc_minimum_msat: 0,
2501 htlc_maximum_msat: 199_999_999,
2503 fee_proportional_millionths: 0,
2504 excess_data: Vec::new()
2507 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2508 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) {
2509 assert_eq!(err, "Failed to find a path to the given destination");
2510 } else { panic!(); }
2512 // Lift the restriction on the first hop.
2513 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2515 short_channel_id: 2,
2518 cltv_expiry_delta: 0,
2519 htlc_minimum_msat: 0,
2520 htlc_maximum_msat: MAX_VALUE_MSAT,
2522 fee_proportional_millionths: 0,
2523 excess_data: Vec::new()
2526 // A payment above the minimum should pass
2527 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();
2528 assert_eq!(route.paths[0].hops.len(), 2);
2532 fn htlc_minimum_overpay_test() {
2533 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2534 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2535 let config = UserConfig::default();
2536 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
2537 let scorer = ln_test_utils::TestScorer::new();
2538 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2539 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2541 // A route to node#2 via two paths.
2542 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2543 // Thus, they can't send 60 without overpaying.
2544 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2545 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2546 short_channel_id: 2,
2549 cltv_expiry_delta: 0,
2550 htlc_minimum_msat: 35_000,
2551 htlc_maximum_msat: 40_000,
2553 fee_proportional_millionths: 0,
2554 excess_data: Vec::new()
2556 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2557 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2558 short_channel_id: 12,
2561 cltv_expiry_delta: 0,
2562 htlc_minimum_msat: 35_000,
2563 htlc_maximum_msat: 40_000,
2565 fee_proportional_millionths: 0,
2566 excess_data: Vec::new()
2570 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2572 short_channel_id: 13,
2575 cltv_expiry_delta: 0,
2576 htlc_minimum_msat: 0,
2577 htlc_maximum_msat: MAX_VALUE_MSAT,
2579 fee_proportional_millionths: 0,
2580 excess_data: Vec::new()
2582 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2583 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2584 short_channel_id: 4,
2587 cltv_expiry_delta: 0,
2588 htlc_minimum_msat: 0,
2589 htlc_maximum_msat: MAX_VALUE_MSAT,
2591 fee_proportional_millionths: 0,
2592 excess_data: Vec::new()
2595 // Disable other paths
2596 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2597 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2598 short_channel_id: 1,
2600 flags: 2, // to disable
2601 cltv_expiry_delta: 0,
2602 htlc_minimum_msat: 0,
2603 htlc_maximum_msat: MAX_VALUE_MSAT,
2605 fee_proportional_millionths: 0,
2606 excess_data: Vec::new()
2609 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2610 // Overpay fees to hit htlc_minimum_msat.
2611 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2612 // TODO: this could be better balanced to overpay 10k and not 15k.
2613 assert_eq!(overpaid_fees, 15_000);
2615 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2616 // while taking even more fee to match htlc_minimum_msat.
2617 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2618 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2619 short_channel_id: 12,
2622 cltv_expiry_delta: 0,
2623 htlc_minimum_msat: 65_000,
2624 htlc_maximum_msat: 80_000,
2626 fee_proportional_millionths: 0,
2627 excess_data: Vec::new()
2629 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2630 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2631 short_channel_id: 2,
2634 cltv_expiry_delta: 0,
2635 htlc_minimum_msat: 0,
2636 htlc_maximum_msat: MAX_VALUE_MSAT,
2638 fee_proportional_millionths: 0,
2639 excess_data: Vec::new()
2641 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2642 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2643 short_channel_id: 4,
2646 cltv_expiry_delta: 0,
2647 htlc_minimum_msat: 0,
2648 htlc_maximum_msat: MAX_VALUE_MSAT,
2650 fee_proportional_millionths: 100_000,
2651 excess_data: Vec::new()
2654 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2655 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2656 assert_eq!(route.paths.len(), 1);
2657 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
2658 let fees = route.paths[0].hops[0].fee_msat;
2659 assert_eq!(fees, 5_000);
2661 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2662 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2663 // the other channel.
2664 assert_eq!(route.paths.len(), 1);
2665 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2666 let fees = route.paths[0].hops[0].fee_msat;
2667 assert_eq!(fees, 5_000);
2671 fn disable_channels_test() {
2672 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2673 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2674 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2675 let scorer = ln_test_utils::TestScorer::new();
2676 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2677 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2679 // // Disable channels 4 and 12 by flags=2
2680 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2681 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2682 short_channel_id: 4,
2684 flags: 2, // to disable
2685 cltv_expiry_delta: 0,
2686 htlc_minimum_msat: 0,
2687 htlc_maximum_msat: MAX_VALUE_MSAT,
2689 fee_proportional_millionths: 0,
2690 excess_data: Vec::new()
2692 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2693 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2694 short_channel_id: 12,
2696 flags: 2, // to disable
2697 cltv_expiry_delta: 0,
2698 htlc_minimum_msat: 0,
2699 htlc_maximum_msat: MAX_VALUE_MSAT,
2701 fee_proportional_millionths: 0,
2702 excess_data: Vec::new()
2705 // If all the channels require some features we don't understand, route should fail
2706 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) {
2707 assert_eq!(err, "Failed to find a path to the given destination");
2708 } else { panic!(); }
2710 // If we specify a channel to node7, that overrides our local channel view and that gets used
2711 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2712 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();
2713 assert_eq!(route.paths[0].hops.len(), 2);
2715 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
2716 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
2717 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2718 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
2719 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2720 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2722 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2723 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
2724 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2725 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2726 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2727 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
2731 fn disable_node_test() {
2732 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2733 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2734 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2735 let scorer = ln_test_utils::TestScorer::new();
2736 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2737 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2739 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2740 let mut unknown_features = NodeFeatures::empty();
2741 unknown_features.set_unknown_feature_required();
2742 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2743 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2744 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2746 // If all nodes require some features we don't understand, route should fail
2747 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) {
2748 assert_eq!(err, "Failed to find a path to the given destination");
2749 } else { panic!(); }
2751 // If we specify a channel to node7, that overrides our local channel view and that gets used
2752 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2753 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();
2754 assert_eq!(route.paths[0].hops.len(), 2);
2756 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
2757 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
2758 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2759 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
2760 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2761 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2763 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2764 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
2765 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2766 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2767 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2768 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
2770 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2771 // naively) assume that the user checked the feature bits on the invoice, which override
2772 // the node_announcement.
2776 fn our_chans_test() {
2777 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2778 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2779 let scorer = ln_test_utils::TestScorer::new();
2780 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2781 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2783 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2784 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
2785 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2786 assert_eq!(route.paths[0].hops.len(), 3);
2788 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2789 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2790 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2791 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2792 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2793 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2795 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2796 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2797 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2798 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
2799 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2800 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2802 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
2803 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
2804 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
2805 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
2806 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
2807 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
2809 // If we specify a channel to node7, that overrides our local channel view and that gets used
2810 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2811 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2812 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();
2813 assert_eq!(route.paths[0].hops.len(), 2);
2815 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
2816 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
2817 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2818 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
2819 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
2820 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2822 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2823 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
2824 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2825 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2826 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2827 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
2830 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2831 let zero_fees = RoutingFees {
2833 proportional_millionths: 0,
2835 vec![RouteHint(vec![RouteHintHop {
2836 src_node_id: nodes[3],
2837 short_channel_id: 8,
2839 cltv_expiry_delta: (8 << 4) | 1,
2840 htlc_minimum_msat: None,
2841 htlc_maximum_msat: None,
2843 ]), RouteHint(vec![RouteHintHop {
2844 src_node_id: nodes[4],
2845 short_channel_id: 9,
2848 proportional_millionths: 0,
2850 cltv_expiry_delta: (9 << 4) | 1,
2851 htlc_minimum_msat: None,
2852 htlc_maximum_msat: None,
2853 }]), RouteHint(vec![RouteHintHop {
2854 src_node_id: nodes[5],
2855 short_channel_id: 10,
2857 cltv_expiry_delta: (10 << 4) | 1,
2858 htlc_minimum_msat: None,
2859 htlc_maximum_msat: None,
2863 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2864 let zero_fees = RoutingFees {
2866 proportional_millionths: 0,
2868 vec![RouteHint(vec![RouteHintHop {
2869 src_node_id: nodes[2],
2870 short_channel_id: 5,
2873 proportional_millionths: 0,
2875 cltv_expiry_delta: (5 << 4) | 1,
2876 htlc_minimum_msat: None,
2877 htlc_maximum_msat: None,
2879 src_node_id: nodes[3],
2880 short_channel_id: 8,
2882 cltv_expiry_delta: (8 << 4) | 1,
2883 htlc_minimum_msat: None,
2884 htlc_maximum_msat: None,
2886 ]), RouteHint(vec![RouteHintHop {
2887 src_node_id: nodes[4],
2888 short_channel_id: 9,
2891 proportional_millionths: 0,
2893 cltv_expiry_delta: (9 << 4) | 1,
2894 htlc_minimum_msat: None,
2895 htlc_maximum_msat: None,
2896 }]), RouteHint(vec![RouteHintHop {
2897 src_node_id: nodes[5],
2898 short_channel_id: 10,
2900 cltv_expiry_delta: (10 << 4) | 1,
2901 htlc_minimum_msat: None,
2902 htlc_maximum_msat: None,
2907 fn partial_route_hint_test() {
2908 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2909 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2910 let scorer = ln_test_utils::TestScorer::new();
2911 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2912 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2914 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2915 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2916 // RouteHint may be partially used by the algo to build the best path.
2918 // First check that last hop can't have its source as the payee.
2919 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2920 src_node_id: nodes[6],
2921 short_channel_id: 8,
2924 proportional_millionths: 0,
2926 cltv_expiry_delta: (8 << 4) | 1,
2927 htlc_minimum_msat: None,
2928 htlc_maximum_msat: None,
2931 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2932 invalid_last_hops.push(invalid_last_hop);
2934 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops);
2935 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) {
2936 assert_eq!(err, "Route hint cannot have the payee as the source.");
2937 } else { panic!(); }
2940 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes));
2941 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
2942 assert_eq!(route.paths[0].hops.len(), 5);
2944 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2945 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2946 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2947 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2948 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2949 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2951 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2952 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2953 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
2954 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
2955 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2956 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2958 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
2959 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
2960 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
2961 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
2962 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
2963 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
2965 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
2966 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
2967 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
2968 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
2969 // If we have a peer in the node map, we'll use their features here since we don't have
2970 // a way of figuring out their features from the invoice:
2971 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
2972 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
2974 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
2975 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
2976 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
2977 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
2978 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
2979 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2982 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2983 let zero_fees = RoutingFees {
2985 proportional_millionths: 0,
2987 vec![RouteHint(vec![RouteHintHop {
2988 src_node_id: nodes[3],
2989 short_channel_id: 8,
2991 cltv_expiry_delta: (8 << 4) | 1,
2992 htlc_minimum_msat: None,
2993 htlc_maximum_msat: None,
2994 }]), RouteHint(vec![
2996 ]), RouteHint(vec![RouteHintHop {
2997 src_node_id: nodes[5],
2998 short_channel_id: 10,
3000 cltv_expiry_delta: (10 << 4) | 1,
3001 htlc_minimum_msat: None,
3002 htlc_maximum_msat: None,
3007 fn ignores_empty_last_hops_test() {
3008 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3009 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3010 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes));
3011 let scorer = ln_test_utils::TestScorer::new();
3012 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3013 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3015 // Test handling of an empty RouteHint passed in Invoice.
3017 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3018 assert_eq!(route.paths[0].hops.len(), 5);
3020 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3021 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3022 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3023 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3024 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3025 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3027 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3028 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3029 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3030 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3031 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3032 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3034 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3035 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3036 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3037 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3038 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3039 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3041 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3042 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3043 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3044 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3045 // If we have a peer in the node map, we'll use their features here since we don't have
3046 // a way of figuring out their features from the invoice:
3047 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3048 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3050 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3051 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3052 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3053 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3054 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3055 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3058 /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3060 fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3061 let zero_fees = RoutingFees {
3063 proportional_millionths: 0,
3065 vec![RouteHint(vec![RouteHintHop {
3066 src_node_id: hint_hops[0],
3067 short_channel_id: 0xff00,
3070 proportional_millionths: 0,
3072 cltv_expiry_delta: (5 << 4) | 1,
3073 htlc_minimum_msat: None,
3074 htlc_maximum_msat: None,
3076 src_node_id: hint_hops[1],
3077 short_channel_id: 0xff01,
3079 cltv_expiry_delta: (8 << 4) | 1,
3080 htlc_minimum_msat: None,
3081 htlc_maximum_msat: None,
3086 fn multi_hint_last_hops_test() {
3087 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3088 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3089 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3090 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3091 let scorer = ln_test_utils::TestScorer::new();
3092 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3093 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3094 // Test through channels 2, 3, 0xff00, 0xff01.
3095 // Test shows that multiple hop hints are considered.
3097 // Disabling channels 6 & 7 by flags=2
3098 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3099 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3100 short_channel_id: 6,
3102 flags: 2, // to disable
3103 cltv_expiry_delta: 0,
3104 htlc_minimum_msat: 0,
3105 htlc_maximum_msat: MAX_VALUE_MSAT,
3107 fee_proportional_millionths: 0,
3108 excess_data: Vec::new()
3110 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3111 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3112 short_channel_id: 7,
3114 flags: 2, // to disable
3115 cltv_expiry_delta: 0,
3116 htlc_minimum_msat: 0,
3117 htlc_maximum_msat: MAX_VALUE_MSAT,
3119 fee_proportional_millionths: 0,
3120 excess_data: Vec::new()
3123 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3124 assert_eq!(route.paths[0].hops.len(), 4);
3126 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3127 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3128 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3129 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3130 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3131 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3133 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3134 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3135 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3136 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3137 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3138 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3140 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3141 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3142 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3143 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3144 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3145 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3147 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3148 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3149 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3150 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3151 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3152 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3156 fn private_multi_hint_last_hops_test() {
3157 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3158 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3160 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3161 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3163 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3164 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3165 let scorer = ln_test_utils::TestScorer::new();
3166 // Test through channels 2, 3, 0xff00, 0xff01.
3167 // Test shows that multiple hop hints are considered.
3169 // Disabling channels 6 & 7 by flags=2
3170 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3172 short_channel_id: 6,
3174 flags: 2, // to disable
3175 cltv_expiry_delta: 0,
3176 htlc_minimum_msat: 0,
3177 htlc_maximum_msat: MAX_VALUE_MSAT,
3179 fee_proportional_millionths: 0,
3180 excess_data: Vec::new()
3182 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3184 short_channel_id: 7,
3186 flags: 2, // to disable
3187 cltv_expiry_delta: 0,
3188 htlc_minimum_msat: 0,
3189 htlc_maximum_msat: MAX_VALUE_MSAT,
3191 fee_proportional_millionths: 0,
3192 excess_data: Vec::new()
3195 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &[42u8; 32]).unwrap();
3196 assert_eq!(route.paths[0].hops.len(), 4);
3198 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3199 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3200 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3201 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3202 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3203 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3205 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3206 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3207 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3208 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3209 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3210 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3212 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3213 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3214 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3215 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3216 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3217 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3219 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3220 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3221 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3222 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3223 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3224 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3227 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3228 let zero_fees = RoutingFees {
3230 proportional_millionths: 0,
3232 vec![RouteHint(vec![RouteHintHop {
3233 src_node_id: nodes[4],
3234 short_channel_id: 11,
3236 cltv_expiry_delta: (11 << 4) | 1,
3237 htlc_minimum_msat: None,
3238 htlc_maximum_msat: None,
3240 src_node_id: nodes[3],
3241 short_channel_id: 8,
3243 cltv_expiry_delta: (8 << 4) | 1,
3244 htlc_minimum_msat: None,
3245 htlc_maximum_msat: None,
3246 }]), RouteHint(vec![RouteHintHop {
3247 src_node_id: nodes[4],
3248 short_channel_id: 9,
3251 proportional_millionths: 0,
3253 cltv_expiry_delta: (9 << 4) | 1,
3254 htlc_minimum_msat: None,
3255 htlc_maximum_msat: None,
3256 }]), RouteHint(vec![RouteHintHop {
3257 src_node_id: nodes[5],
3258 short_channel_id: 10,
3260 cltv_expiry_delta: (10 << 4) | 1,
3261 htlc_minimum_msat: None,
3262 htlc_maximum_msat: None,
3267 fn last_hops_with_public_channel_test() {
3268 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3269 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3270 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes));
3271 let scorer = ln_test_utils::TestScorer::new();
3272 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3273 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3274 // This test shows that public routes can be present in the invoice
3275 // which would be handled in the same manner.
3277 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3278 assert_eq!(route.paths[0].hops.len(), 5);
3280 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3281 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3282 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3283 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3284 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3285 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3287 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3288 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3289 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3290 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3291 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3292 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3294 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3295 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3296 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3297 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3298 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3299 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3301 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3302 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3303 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3304 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3305 // If we have a peer in the node map, we'll use their features here since we don't have
3306 // a way of figuring out their features from the invoice:
3307 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3308 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3310 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3311 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3312 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3313 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3314 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3315 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3319 fn our_chans_last_hop_connect_test() {
3320 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3321 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3322 let scorer = ln_test_utils::TestScorer::new();
3323 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3324 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3326 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3327 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3328 let mut last_hops = last_hops(&nodes);
3329 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone());
3330 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();
3331 assert_eq!(route.paths[0].hops.len(), 2);
3333 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3334 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3335 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3336 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3337 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3338 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3340 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3341 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3342 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3343 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3344 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3345 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3347 last_hops[0].0[0].fees.base_msat = 1000;
3349 // Revert to via 6 as the fee on 8 goes up
3350 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops);
3351 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3352 assert_eq!(route.paths[0].hops.len(), 4);
3354 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3355 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3356 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3357 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3358 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3359 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3361 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3362 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3363 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3364 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3365 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3366 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3368 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3369 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3370 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3371 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3372 // If we have a peer in the node map, we'll use their features here since we don't have
3373 // a way of figuring out their features from the invoice:
3374 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3375 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3377 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3378 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3379 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3380 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3381 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3382 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3384 // ...but still use 8 for larger payments as 6 has a variable feerate
3385 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3386 assert_eq!(route.paths[0].hops.len(), 5);
3388 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3389 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3390 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3391 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3392 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3393 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3395 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3396 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3397 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3398 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3399 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3400 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3402 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3403 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3404 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3405 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3406 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3407 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3409 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3410 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3411 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3412 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3413 // If we have a peer in the node map, we'll use their features here since we don't have
3414 // a way of figuring out their features from the invoice:
3415 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3416 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3418 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3419 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3420 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3421 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3422 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3423 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3426 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> {
3427 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3428 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3429 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3431 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3432 let last_hops = RouteHint(vec![RouteHintHop {
3433 src_node_id: middle_node_id,
3434 short_channel_id: 8,
3437 proportional_millionths: last_hop_fee_prop,
3439 cltv_expiry_delta: (8 << 4) | 1,
3440 htlc_minimum_msat: None,
3441 htlc_maximum_msat: last_hop_htlc_max,
3443 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]);
3444 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3445 let scorer = ln_test_utils::TestScorer::new();
3446 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3447 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3448 let logger = ln_test_utils::TestLogger::new();
3449 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3450 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3451 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &logger, &scorer, &random_seed_bytes);
3456 fn unannounced_path_test() {
3457 // We should be able to send a payment to a destination without any help of a routing graph
3458 // if we have a channel with a common counterparty that appears in the first and last hop
3460 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3462 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3463 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3464 assert_eq!(route.paths[0].hops.len(), 2);
3466 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3467 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3468 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3469 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3470 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3471 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3473 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3474 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3475 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3476 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3477 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3478 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3482 fn overflow_unannounced_path_test_liquidity_underflow() {
3483 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3484 // the last-hop had a fee which overflowed a u64, we'd panic.
3485 // This was due to us adding the first-hop from us unconditionally, causing us to think
3486 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3487 // In this test, we previously hit a subtraction underflow due to having less available
3488 // liquidity at the last hop than 0.
3489 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());
3493 fn overflow_unannounced_path_test_feerate_overflow() {
3494 // This tests for the same case as above, except instead of hitting a subtraction
3495 // underflow, we hit a case where the fee charged at a hop overflowed.
3496 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());
3500 fn available_amount_while_routing_test() {
3501 // Tests whether we choose the correct available channel amount while routing.
3503 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3504 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3505 let scorer = ln_test_utils::TestScorer::new();
3506 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3507 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3508 let config = UserConfig::default();
3509 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
3511 // We will use a simple single-path route from
3512 // our node to node2 via node0: channels {1, 3}.
3514 // First disable all other paths.
3515 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3517 short_channel_id: 2,
3520 cltv_expiry_delta: 0,
3521 htlc_minimum_msat: 0,
3522 htlc_maximum_msat: 100_000,
3524 fee_proportional_millionths: 0,
3525 excess_data: Vec::new()
3527 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3529 short_channel_id: 12,
3532 cltv_expiry_delta: 0,
3533 htlc_minimum_msat: 0,
3534 htlc_maximum_msat: 100_000,
3536 fee_proportional_millionths: 0,
3537 excess_data: Vec::new()
3540 // Make the first channel (#1) very permissive,
3541 // and we will be testing all limits on the second channel.
3542 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3544 short_channel_id: 1,
3547 cltv_expiry_delta: 0,
3548 htlc_minimum_msat: 0,
3549 htlc_maximum_msat: 1_000_000_000,
3551 fee_proportional_millionths: 0,
3552 excess_data: Vec::new()
3555 // First, let's see if routing works if we have absolutely no idea about the available amount.
3556 // In this case, it should be set to 250_000 sats.
3557 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3559 short_channel_id: 3,
3562 cltv_expiry_delta: 0,
3563 htlc_minimum_msat: 0,
3564 htlc_maximum_msat: 250_000_000,
3566 fee_proportional_millionths: 0,
3567 excess_data: Vec::new()
3571 // Attempt to route more than available results in a failure.
3572 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3573 &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3574 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3575 } else { panic!(); }
3579 // Now, attempt to route an exact amount we have should be fine.
3580 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();
3581 assert_eq!(route.paths.len(), 1);
3582 let path = route.paths.last().unwrap();
3583 assert_eq!(path.hops.len(), 2);
3584 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3585 assert_eq!(path.final_value_msat(), 250_000_000);
3588 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3589 // Disable channel #1 and use another first hop.
3590 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3592 short_channel_id: 1,
3595 cltv_expiry_delta: 0,
3596 htlc_minimum_msat: 0,
3597 htlc_maximum_msat: 1_000_000_000,
3599 fee_proportional_millionths: 0,
3600 excess_data: Vec::new()
3603 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3604 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3607 // Attempt to route more than available results in a failure.
3608 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3609 &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) {
3610 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3611 } else { panic!(); }
3615 // Now, attempt to route an exact amount we have should be fine.
3616 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();
3617 assert_eq!(route.paths.len(), 1);
3618 let path = route.paths.last().unwrap();
3619 assert_eq!(path.hops.len(), 2);
3620 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3621 assert_eq!(path.final_value_msat(), 200_000_000);
3624 // Enable channel #1 back.
3625 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3627 short_channel_id: 1,
3630 cltv_expiry_delta: 0,
3631 htlc_minimum_msat: 0,
3632 htlc_maximum_msat: 1_000_000_000,
3634 fee_proportional_millionths: 0,
3635 excess_data: Vec::new()
3639 // Now let's see if routing works if we know only htlc_maximum_msat.
3640 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3641 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3642 short_channel_id: 3,
3645 cltv_expiry_delta: 0,
3646 htlc_minimum_msat: 0,
3647 htlc_maximum_msat: 15_000,
3649 fee_proportional_millionths: 0,
3650 excess_data: Vec::new()
3654 // Attempt to route more than available results in a failure.
3655 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3656 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3657 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3658 } else { panic!(); }
3662 // Now, attempt to route an exact amount we have should be fine.
3663 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3664 assert_eq!(route.paths.len(), 1);
3665 let path = route.paths.last().unwrap();
3666 assert_eq!(path.hops.len(), 2);
3667 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3668 assert_eq!(path.final_value_msat(), 15_000);
3671 // Now let's see if routing works if we know only capacity from the UTXO.
3673 // We can't change UTXO capacity on the fly, so we'll disable
3674 // the existing channel and add another one with the capacity we need.
3675 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3677 short_channel_id: 3,
3680 cltv_expiry_delta: 0,
3681 htlc_minimum_msat: 0,
3682 htlc_maximum_msat: MAX_VALUE_MSAT,
3684 fee_proportional_millionths: 0,
3685 excess_data: Vec::new()
3688 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3689 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3690 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3691 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3692 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3694 *chain_monitor.utxo_ret.lock().unwrap() =
3695 UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
3696 gossip_sync.add_utxo_lookup(Some(chain_monitor));
3698 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3699 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3700 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3701 short_channel_id: 333,
3704 cltv_expiry_delta: (3 << 4) | 1,
3705 htlc_minimum_msat: 0,
3706 htlc_maximum_msat: 15_000,
3708 fee_proportional_millionths: 0,
3709 excess_data: Vec::new()
3711 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3712 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3713 short_channel_id: 333,
3716 cltv_expiry_delta: (3 << 4) | 2,
3717 htlc_minimum_msat: 0,
3718 htlc_maximum_msat: 15_000,
3720 fee_proportional_millionths: 0,
3721 excess_data: Vec::new()
3725 // Attempt to route more than available results in a failure.
3726 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3727 &our_id, &payment_params, &network_graph.read_only(), None, 15_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3728 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3729 } else { panic!(); }
3733 // Now, attempt to route an exact amount we have should be fine.
3734 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3735 assert_eq!(route.paths.len(), 1);
3736 let path = route.paths.last().unwrap();
3737 assert_eq!(path.hops.len(), 2);
3738 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3739 assert_eq!(path.final_value_msat(), 15_000);
3742 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3743 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3744 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3745 short_channel_id: 333,
3748 cltv_expiry_delta: 0,
3749 htlc_minimum_msat: 0,
3750 htlc_maximum_msat: 10_000,
3752 fee_proportional_millionths: 0,
3753 excess_data: Vec::new()
3757 // Attempt to route more than available results in a failure.
3758 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3759 &our_id, &payment_params, &network_graph.read_only(), None, 10_001, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3760 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3761 } else { panic!(); }
3765 // Now, attempt to route an exact amount we have should be fine.
3766 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3767 assert_eq!(route.paths.len(), 1);
3768 let path = route.paths.last().unwrap();
3769 assert_eq!(path.hops.len(), 2);
3770 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3771 assert_eq!(path.final_value_msat(), 10_000);
3776 fn available_liquidity_last_hop_test() {
3777 // Check that available liquidity properly limits the path even when only
3778 // one of the latter hops is limited.
3779 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3780 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3781 let scorer = ln_test_utils::TestScorer::new();
3782 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3783 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3784 let config = UserConfig::default();
3785 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
3787 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3788 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3789 // Total capacity: 50 sats.
3791 // Disable other potential paths.
3792 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3794 short_channel_id: 2,
3797 cltv_expiry_delta: 0,
3798 htlc_minimum_msat: 0,
3799 htlc_maximum_msat: 100_000,
3801 fee_proportional_millionths: 0,
3802 excess_data: Vec::new()
3804 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3806 short_channel_id: 7,
3809 cltv_expiry_delta: 0,
3810 htlc_minimum_msat: 0,
3811 htlc_maximum_msat: 100_000,
3813 fee_proportional_millionths: 0,
3814 excess_data: Vec::new()
3819 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3820 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3821 short_channel_id: 12,
3824 cltv_expiry_delta: 0,
3825 htlc_minimum_msat: 0,
3826 htlc_maximum_msat: 100_000,
3828 fee_proportional_millionths: 0,
3829 excess_data: Vec::new()
3831 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3832 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3833 short_channel_id: 13,
3836 cltv_expiry_delta: 0,
3837 htlc_minimum_msat: 0,
3838 htlc_maximum_msat: 100_000,
3840 fee_proportional_millionths: 0,
3841 excess_data: Vec::new()
3844 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3845 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3846 short_channel_id: 6,
3849 cltv_expiry_delta: 0,
3850 htlc_minimum_msat: 0,
3851 htlc_maximum_msat: 50_000,
3853 fee_proportional_millionths: 0,
3854 excess_data: Vec::new()
3856 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3858 short_channel_id: 11,
3861 cltv_expiry_delta: 0,
3862 htlc_minimum_msat: 0,
3863 htlc_maximum_msat: 100_000,
3865 fee_proportional_millionths: 0,
3866 excess_data: Vec::new()
3869 // Attempt to route more than available results in a failure.
3870 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3871 &our_id, &payment_params, &network_graph.read_only(), None, 60_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
3872 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3873 } else { panic!(); }
3877 // Now, attempt to route 49 sats (just a bit below the capacity).
3878 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3879 assert_eq!(route.paths.len(), 1);
3880 let mut total_amount_paid_msat = 0;
3881 for path in &route.paths {
3882 assert_eq!(path.hops.len(), 4);
3883 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
3884 total_amount_paid_msat += path.final_value_msat();
3886 assert_eq!(total_amount_paid_msat, 49_000);
3890 // Attempt to route an exact amount is also fine
3891 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3892 assert_eq!(route.paths.len(), 1);
3893 let mut total_amount_paid_msat = 0;
3894 for path in &route.paths {
3895 assert_eq!(path.hops.len(), 4);
3896 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
3897 total_amount_paid_msat += path.final_value_msat();
3899 assert_eq!(total_amount_paid_msat, 50_000);
3904 fn ignore_fee_first_hop_test() {
3905 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3906 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3907 let scorer = ln_test_utils::TestScorer::new();
3908 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3909 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3910 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3912 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3913 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3915 short_channel_id: 1,
3918 cltv_expiry_delta: 0,
3919 htlc_minimum_msat: 0,
3920 htlc_maximum_msat: 100_000,
3921 fee_base_msat: 1_000_000,
3922 fee_proportional_millionths: 0,
3923 excess_data: Vec::new()
3925 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3927 short_channel_id: 3,
3930 cltv_expiry_delta: 0,
3931 htlc_minimum_msat: 0,
3932 htlc_maximum_msat: 50_000,
3934 fee_proportional_millionths: 0,
3935 excess_data: Vec::new()
3939 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
3940 assert_eq!(route.paths.len(), 1);
3941 let mut total_amount_paid_msat = 0;
3942 for path in &route.paths {
3943 assert_eq!(path.hops.len(), 2);
3944 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3945 total_amount_paid_msat += path.final_value_msat();
3947 assert_eq!(total_amount_paid_msat, 50_000);
3952 fn simple_mpp_route_test() {
3953 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3954 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3955 let scorer = ln_test_utils::TestScorer::new();
3956 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3957 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3958 let config = UserConfig::default();
3959 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3960 .with_features(channelmanager::provided_invoice_features(&config));
3962 // We need a route consisting of 3 paths:
3963 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3964 // To achieve this, the amount being transferred should be around
3965 // the total capacity of these 3 paths.
3967 // First, we set limits on these (previously unlimited) channels.
3968 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3970 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3971 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3973 short_channel_id: 1,
3976 cltv_expiry_delta: 0,
3977 htlc_minimum_msat: 0,
3978 htlc_maximum_msat: 100_000,
3980 fee_proportional_millionths: 0,
3981 excess_data: Vec::new()
3983 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3984 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3985 short_channel_id: 3,
3988 cltv_expiry_delta: 0,
3989 htlc_minimum_msat: 0,
3990 htlc_maximum_msat: 50_000,
3992 fee_proportional_millionths: 0,
3993 excess_data: Vec::new()
3996 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3997 // (total limit 60).
3998 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4000 short_channel_id: 12,
4003 cltv_expiry_delta: 0,
4004 htlc_minimum_msat: 0,
4005 htlc_maximum_msat: 60_000,
4007 fee_proportional_millionths: 0,
4008 excess_data: Vec::new()
4010 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4012 short_channel_id: 13,
4015 cltv_expiry_delta: 0,
4016 htlc_minimum_msat: 0,
4017 htlc_maximum_msat: 60_000,
4019 fee_proportional_millionths: 0,
4020 excess_data: Vec::new()
4023 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4024 // (total capacity 180 sats).
4025 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4026 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4027 short_channel_id: 2,
4030 cltv_expiry_delta: 0,
4031 htlc_minimum_msat: 0,
4032 htlc_maximum_msat: 200_000,
4034 fee_proportional_millionths: 0,
4035 excess_data: Vec::new()
4037 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4039 short_channel_id: 4,
4042 cltv_expiry_delta: 0,
4043 htlc_minimum_msat: 0,
4044 htlc_maximum_msat: 180_000,
4046 fee_proportional_millionths: 0,
4047 excess_data: Vec::new()
4051 // Attempt to route more than available results in a failure.
4052 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4053 &our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42,
4054 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4055 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4056 } else { panic!(); }
4060 // Attempt to route while setting max_path_count to 0 results in a failure.
4061 let zero_payment_params = payment_params.clone().with_max_path_count(0);
4062 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4063 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100, 42,
4064 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4065 assert_eq!(err, "Can't find a route with no paths allowed.");
4066 } else { panic!(); }
4070 // Attempt to route while setting max_path_count to 3 results in a failure.
4071 // This is the case because the minimal_value_contribution_msat would require each path
4072 // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4073 let fail_payment_params = payment_params.clone().with_max_path_count(3);
4074 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4075 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000, 42,
4076 Arc::clone(&logger), &scorer, &random_seed_bytes) {
4077 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4078 } else { panic!(); }
4082 // Now, attempt to route 250 sats (just a bit below the capacity).
4083 // Our algorithm should provide us with these 3 paths.
4084 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4085 250_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4086 assert_eq!(route.paths.len(), 3);
4087 let mut total_amount_paid_msat = 0;
4088 for path in &route.paths {
4089 assert_eq!(path.hops.len(), 2);
4090 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4091 total_amount_paid_msat += path.final_value_msat();
4093 assert_eq!(total_amount_paid_msat, 250_000);
4097 // Attempt to route an exact amount is also fine
4098 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4099 290_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4100 assert_eq!(route.paths.len(), 3);
4101 let mut total_amount_paid_msat = 0;
4102 for path in &route.paths {
4103 assert_eq!(path.hops.len(), 2);
4104 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4105 total_amount_paid_msat += path.final_value_msat();
4107 assert_eq!(total_amount_paid_msat, 290_000);
4112 fn long_mpp_route_test() {
4113 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4114 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4115 let scorer = ln_test_utils::TestScorer::new();
4116 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4117 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4118 let config = UserConfig::default();
4119 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4121 // We need a route consisting of 3 paths:
4122 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4123 // Note that these paths overlap (channels 5, 12, 13).
4124 // We will route 300 sats.
4125 // Each path will have 100 sats capacity, those channels which
4126 // are used twice will have 200 sats capacity.
4128 // Disable other potential paths.
4129 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4130 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4131 short_channel_id: 2,
4134 cltv_expiry_delta: 0,
4135 htlc_minimum_msat: 0,
4136 htlc_maximum_msat: 100_000,
4138 fee_proportional_millionths: 0,
4139 excess_data: Vec::new()
4141 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4143 short_channel_id: 7,
4146 cltv_expiry_delta: 0,
4147 htlc_minimum_msat: 0,
4148 htlc_maximum_msat: 100_000,
4150 fee_proportional_millionths: 0,
4151 excess_data: Vec::new()
4154 // Path via {node0, node2} is channels {1, 3, 5}.
4155 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4157 short_channel_id: 1,
4160 cltv_expiry_delta: 0,
4161 htlc_minimum_msat: 0,
4162 htlc_maximum_msat: 100_000,
4164 fee_proportional_millionths: 0,
4165 excess_data: Vec::new()
4167 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4168 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4169 short_channel_id: 3,
4172 cltv_expiry_delta: 0,
4173 htlc_minimum_msat: 0,
4174 htlc_maximum_msat: 100_000,
4176 fee_proportional_millionths: 0,
4177 excess_data: Vec::new()
4180 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4181 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4182 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4184 short_channel_id: 5,
4187 cltv_expiry_delta: 0,
4188 htlc_minimum_msat: 0,
4189 htlc_maximum_msat: 200_000,
4191 fee_proportional_millionths: 0,
4192 excess_data: Vec::new()
4195 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4196 // Add 100 sats to the capacities of {12, 13}, because these channels
4197 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4198 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4200 short_channel_id: 12,
4203 cltv_expiry_delta: 0,
4204 htlc_minimum_msat: 0,
4205 htlc_maximum_msat: 200_000,
4207 fee_proportional_millionths: 0,
4208 excess_data: Vec::new()
4210 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4212 short_channel_id: 13,
4215 cltv_expiry_delta: 0,
4216 htlc_minimum_msat: 0,
4217 htlc_maximum_msat: 200_000,
4219 fee_proportional_millionths: 0,
4220 excess_data: Vec::new()
4223 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4225 short_channel_id: 6,
4228 cltv_expiry_delta: 0,
4229 htlc_minimum_msat: 0,
4230 htlc_maximum_msat: 100_000,
4232 fee_proportional_millionths: 0,
4233 excess_data: Vec::new()
4235 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4237 short_channel_id: 11,
4240 cltv_expiry_delta: 0,
4241 htlc_minimum_msat: 0,
4242 htlc_maximum_msat: 100_000,
4244 fee_proportional_millionths: 0,
4245 excess_data: Vec::new()
4248 // Path via {node7, node2} is channels {12, 13, 5}.
4249 // We already limited them to 200 sats (they are used twice for 100 sats).
4250 // Nothing to do here.
4253 // Attempt to route more than available results in a failure.
4254 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4255 &our_id, &payment_params, &network_graph.read_only(), None, 350_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4256 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4257 } else { panic!(); }
4261 // Now, attempt to route 300 sats (exact amount we can route).
4262 // Our algorithm should provide us with these 3 paths, 100 sats each.
4263 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4264 assert_eq!(route.paths.len(), 3);
4266 let mut total_amount_paid_msat = 0;
4267 for path in &route.paths {
4268 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4269 total_amount_paid_msat += path.final_value_msat();
4271 assert_eq!(total_amount_paid_msat, 300_000);
4277 fn mpp_cheaper_route_test() {
4278 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4279 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4280 let scorer = ln_test_utils::TestScorer::new();
4281 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4282 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4283 let config = UserConfig::default();
4284 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4286 // This test checks that if we have two cheaper paths and one more expensive path,
4287 // so that liquidity-wise any 2 of 3 combination is sufficient,
4288 // two cheaper paths will be taken.
4289 // These paths have equal available liquidity.
4291 // We need a combination of 3 paths:
4292 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4293 // Note that these paths overlap (channels 5, 12, 13).
4294 // Each path will have 100 sats capacity, those channels which
4295 // are used twice will have 200 sats capacity.
4297 // Disable other potential paths.
4298 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4299 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4300 short_channel_id: 2,
4303 cltv_expiry_delta: 0,
4304 htlc_minimum_msat: 0,
4305 htlc_maximum_msat: 100_000,
4307 fee_proportional_millionths: 0,
4308 excess_data: Vec::new()
4310 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4311 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4312 short_channel_id: 7,
4315 cltv_expiry_delta: 0,
4316 htlc_minimum_msat: 0,
4317 htlc_maximum_msat: 100_000,
4319 fee_proportional_millionths: 0,
4320 excess_data: Vec::new()
4323 // Path via {node0, node2} is channels {1, 3, 5}.
4324 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4326 short_channel_id: 1,
4329 cltv_expiry_delta: 0,
4330 htlc_minimum_msat: 0,
4331 htlc_maximum_msat: 100_000,
4333 fee_proportional_millionths: 0,
4334 excess_data: Vec::new()
4336 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4337 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4338 short_channel_id: 3,
4341 cltv_expiry_delta: 0,
4342 htlc_minimum_msat: 0,
4343 htlc_maximum_msat: 100_000,
4345 fee_proportional_millionths: 0,
4346 excess_data: Vec::new()
4349 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4350 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4351 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4352 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4353 short_channel_id: 5,
4356 cltv_expiry_delta: 0,
4357 htlc_minimum_msat: 0,
4358 htlc_maximum_msat: 200_000,
4360 fee_proportional_millionths: 0,
4361 excess_data: Vec::new()
4364 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4365 // Add 100 sats to the capacities of {12, 13}, because these channels
4366 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4367 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4368 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4369 short_channel_id: 12,
4372 cltv_expiry_delta: 0,
4373 htlc_minimum_msat: 0,
4374 htlc_maximum_msat: 200_000,
4376 fee_proportional_millionths: 0,
4377 excess_data: Vec::new()
4379 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4381 short_channel_id: 13,
4384 cltv_expiry_delta: 0,
4385 htlc_minimum_msat: 0,
4386 htlc_maximum_msat: 200_000,
4388 fee_proportional_millionths: 0,
4389 excess_data: Vec::new()
4392 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4394 short_channel_id: 6,
4397 cltv_expiry_delta: 0,
4398 htlc_minimum_msat: 0,
4399 htlc_maximum_msat: 100_000,
4400 fee_base_msat: 1_000,
4401 fee_proportional_millionths: 0,
4402 excess_data: Vec::new()
4404 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4406 short_channel_id: 11,
4409 cltv_expiry_delta: 0,
4410 htlc_minimum_msat: 0,
4411 htlc_maximum_msat: 100_000,
4413 fee_proportional_millionths: 0,
4414 excess_data: Vec::new()
4417 // Path via {node7, node2} is channels {12, 13, 5}.
4418 // We already limited them to 200 sats (they are used twice for 100 sats).
4419 // Nothing to do here.
4422 // Now, attempt to route 180 sats.
4423 // Our algorithm should provide us with these 2 paths.
4424 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4425 assert_eq!(route.paths.len(), 2);
4427 let mut total_value_transferred_msat = 0;
4428 let mut total_paid_msat = 0;
4429 for path in &route.paths {
4430 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4431 total_value_transferred_msat += path.final_value_msat();
4432 for hop in &path.hops {
4433 total_paid_msat += hop.fee_msat;
4436 // If we paid fee, this would be higher.
4437 assert_eq!(total_value_transferred_msat, 180_000);
4438 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4439 assert_eq!(total_fees_paid, 0);
4444 fn fees_on_mpp_route_test() {
4445 // This test makes sure that MPP algorithm properly takes into account
4446 // fees charged on the channels, by making the fees impactful:
4447 // if the fee is not properly accounted for, the behavior is different.
4448 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4449 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4450 let scorer = ln_test_utils::TestScorer::new();
4451 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4452 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4453 let config = UserConfig::default();
4454 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_features(channelmanager::provided_invoice_features(&config));
4456 // We need a route consisting of 2 paths:
4457 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4458 // We will route 200 sats, Each path will have 100 sats capacity.
4460 // This test is not particularly stable: e.g.,
4461 // there's a way to route via {node0, node2, node4}.
4462 // It works while pathfinding is deterministic, but can be broken otherwise.
4463 // It's fine to ignore this concern for now.
4465 // Disable other potential paths.
4466 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4467 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4468 short_channel_id: 2,
4471 cltv_expiry_delta: 0,
4472 htlc_minimum_msat: 0,
4473 htlc_maximum_msat: 100_000,
4475 fee_proportional_millionths: 0,
4476 excess_data: Vec::new()
4479 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4480 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4481 short_channel_id: 7,
4484 cltv_expiry_delta: 0,
4485 htlc_minimum_msat: 0,
4486 htlc_maximum_msat: 100_000,
4488 fee_proportional_millionths: 0,
4489 excess_data: Vec::new()
4492 // Path via {node0, node2} is channels {1, 3, 5}.
4493 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4494 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4495 short_channel_id: 1,
4498 cltv_expiry_delta: 0,
4499 htlc_minimum_msat: 0,
4500 htlc_maximum_msat: 100_000,
4502 fee_proportional_millionths: 0,
4503 excess_data: Vec::new()
4505 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4507 short_channel_id: 3,
4510 cltv_expiry_delta: 0,
4511 htlc_minimum_msat: 0,
4512 htlc_maximum_msat: 100_000,
4514 fee_proportional_millionths: 0,
4515 excess_data: Vec::new()
4518 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4519 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4520 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4521 short_channel_id: 5,
4524 cltv_expiry_delta: 0,
4525 htlc_minimum_msat: 0,
4526 htlc_maximum_msat: 100_000,
4528 fee_proportional_millionths: 0,
4529 excess_data: Vec::new()
4532 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4533 // All channels should be 100 sats capacity. But for the fee experiment,
4534 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4535 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4536 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4537 // so no matter how large are other channels,
4538 // the whole path will be limited by 100 sats with just these 2 conditions:
4539 // - channel 12 capacity is 250 sats
4540 // - fee for channel 6 is 150 sats
4541 // Let's test this by enforcing these 2 conditions and removing other limits.
4542 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4544 short_channel_id: 12,
4547 cltv_expiry_delta: 0,
4548 htlc_minimum_msat: 0,
4549 htlc_maximum_msat: 250_000,
4551 fee_proportional_millionths: 0,
4552 excess_data: Vec::new()
4554 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4555 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4556 short_channel_id: 13,
4559 cltv_expiry_delta: 0,
4560 htlc_minimum_msat: 0,
4561 htlc_maximum_msat: MAX_VALUE_MSAT,
4563 fee_proportional_millionths: 0,
4564 excess_data: Vec::new()
4567 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4568 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4569 short_channel_id: 6,
4572 cltv_expiry_delta: 0,
4573 htlc_minimum_msat: 0,
4574 htlc_maximum_msat: MAX_VALUE_MSAT,
4575 fee_base_msat: 150_000,
4576 fee_proportional_millionths: 0,
4577 excess_data: Vec::new()
4579 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4581 short_channel_id: 11,
4584 cltv_expiry_delta: 0,
4585 htlc_minimum_msat: 0,
4586 htlc_maximum_msat: MAX_VALUE_MSAT,
4588 fee_proportional_millionths: 0,
4589 excess_data: Vec::new()
4593 // Attempt to route more than available results in a failure.
4594 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4595 &our_id, &payment_params, &network_graph.read_only(), None, 210_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4596 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4597 } else { panic!(); }
4601 // Now, attempt to route 200 sats (exact amount we can route).
4602 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4603 assert_eq!(route.paths.len(), 2);
4605 let mut total_amount_paid_msat = 0;
4606 for path in &route.paths {
4607 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4608 total_amount_paid_msat += path.final_value_msat();
4610 assert_eq!(total_amount_paid_msat, 200_000);
4611 assert_eq!(route.get_total_fees(), 150_000);
4616 fn mpp_with_last_hops() {
4617 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4618 // via a single last-hop route hint, we'd fail to route if we first collected routes
4619 // totaling close but not quite enough to fund the full payment.
4621 // This was because we considered last-hop hints to have exactly the sought payment amount
4622 // instead of the amount we were trying to collect, needlessly limiting our path searching
4623 // at the very first hop.
4625 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4626 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4627 // to only have the remaining to-collect amount in available liquidity.
4629 // This bug appeared in production in some specific channel configurations.
4630 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4631 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4632 let scorer = ln_test_utils::TestScorer::new();
4633 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4634 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4635 let config = UserConfig::default();
4636 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_features(channelmanager::provided_invoice_features(&config))
4637 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4638 src_node_id: nodes[2],
4639 short_channel_id: 42,
4640 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4641 cltv_expiry_delta: 42,
4642 htlc_minimum_msat: None,
4643 htlc_maximum_msat: None,
4644 }])]).with_max_channel_saturation_power_of_half(0);
4646 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4647 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4648 // would first use the no-fee route and then fail to find a path along the second route as
4649 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4650 // under 5% of our payment amount.
4651 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4653 short_channel_id: 1,
4656 cltv_expiry_delta: (5 << 4) | 5,
4657 htlc_minimum_msat: 0,
4658 htlc_maximum_msat: 99_000,
4659 fee_base_msat: u32::max_value(),
4660 fee_proportional_millionths: u32::max_value(),
4661 excess_data: Vec::new()
4663 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4664 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4665 short_channel_id: 2,
4668 cltv_expiry_delta: (5 << 4) | 3,
4669 htlc_minimum_msat: 0,
4670 htlc_maximum_msat: 99_000,
4671 fee_base_msat: u32::max_value(),
4672 fee_proportional_millionths: u32::max_value(),
4673 excess_data: Vec::new()
4675 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4677 short_channel_id: 4,
4680 cltv_expiry_delta: (4 << 4) | 1,
4681 htlc_minimum_msat: 0,
4682 htlc_maximum_msat: MAX_VALUE_MSAT,
4684 fee_proportional_millionths: 0,
4685 excess_data: Vec::new()
4687 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4689 short_channel_id: 13,
4691 flags: 0|2, // Channel disabled
4692 cltv_expiry_delta: (13 << 4) | 1,
4693 htlc_minimum_msat: 0,
4694 htlc_maximum_msat: MAX_VALUE_MSAT,
4696 fee_proportional_millionths: 2000000,
4697 excess_data: Vec::new()
4700 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4702 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();
4703 assert_eq!(route.paths.len(), 2);
4704 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
4705 // Paths are manually ordered ordered by SCID, so:
4706 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4707 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4708 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
4709 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4710 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
4711 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
4712 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
4713 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
4714 assert_eq!(route.get_total_fees(), 1);
4715 assert_eq!(route.get_total_amount(), 100_000);
4719 fn drop_lowest_channel_mpp_route_test() {
4720 // This test checks that low-capacity channel is dropped when after
4721 // path finding we realize that we found more capacity than we need.
4722 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4723 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4724 let scorer = ln_test_utils::TestScorer::new();
4725 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4726 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4727 let config = UserConfig::default();
4728 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config))
4729 .with_max_channel_saturation_power_of_half(0);
4731 // We need a route consisting of 3 paths:
4732 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4734 // The first and the second paths should be sufficient, but the third should be
4735 // cheaper, so that we select it but drop later.
4737 // First, we set limits on these (previously unlimited) channels.
4738 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4740 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4741 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4742 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4743 short_channel_id: 1,
4746 cltv_expiry_delta: 0,
4747 htlc_minimum_msat: 0,
4748 htlc_maximum_msat: 100_000,
4750 fee_proportional_millionths: 0,
4751 excess_data: Vec::new()
4753 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4755 short_channel_id: 3,
4758 cltv_expiry_delta: 0,
4759 htlc_minimum_msat: 0,
4760 htlc_maximum_msat: 50_000,
4762 fee_proportional_millionths: 0,
4763 excess_data: Vec::new()
4766 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4767 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4768 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4769 short_channel_id: 12,
4772 cltv_expiry_delta: 0,
4773 htlc_minimum_msat: 0,
4774 htlc_maximum_msat: 60_000,
4776 fee_proportional_millionths: 0,
4777 excess_data: Vec::new()
4779 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4780 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4781 short_channel_id: 13,
4784 cltv_expiry_delta: 0,
4785 htlc_minimum_msat: 0,
4786 htlc_maximum_msat: 60_000,
4788 fee_proportional_millionths: 0,
4789 excess_data: Vec::new()
4792 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4793 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4794 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4795 short_channel_id: 2,
4798 cltv_expiry_delta: 0,
4799 htlc_minimum_msat: 0,
4800 htlc_maximum_msat: 20_000,
4802 fee_proportional_millionths: 0,
4803 excess_data: Vec::new()
4805 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4807 short_channel_id: 4,
4810 cltv_expiry_delta: 0,
4811 htlc_minimum_msat: 0,
4812 htlc_maximum_msat: 20_000,
4814 fee_proportional_millionths: 0,
4815 excess_data: Vec::new()
4819 // Attempt to route more than available results in a failure.
4820 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4821 &our_id, &payment_params, &network_graph.read_only(), None, 150_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes) {
4822 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4823 } else { panic!(); }
4827 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4828 // Our algorithm should provide us with these 3 paths.
4829 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4830 assert_eq!(route.paths.len(), 3);
4831 let mut total_amount_paid_msat = 0;
4832 for path in &route.paths {
4833 assert_eq!(path.hops.len(), 2);
4834 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4835 total_amount_paid_msat += path.final_value_msat();
4837 assert_eq!(total_amount_paid_msat, 125_000);
4841 // Attempt to route without the last small cheap channel
4842 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4843 assert_eq!(route.paths.len(), 2);
4844 let mut total_amount_paid_msat = 0;
4845 for path in &route.paths {
4846 assert_eq!(path.hops.len(), 2);
4847 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4848 total_amount_paid_msat += path.final_value_msat();
4850 assert_eq!(total_amount_paid_msat, 90_000);
4855 fn min_criteria_consistency() {
4856 // Test that we don't use an inconsistent metric between updating and walking nodes during
4857 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4858 // was updated with a different criterion from the heap sorting, resulting in loops in
4859 // calculated paths. We test for that specific case here.
4861 // We construct a network that looks like this:
4863 // node2 -1(3)2- node3
4867 // node1 -1(5)2- node4 -1(1)2- node6
4873 // We create a loop on the side of our real path - our destination is node 6, with a
4874 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4875 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4876 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4877 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4878 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4879 // "previous hop" being set to node 3, creating a loop in the path.
4880 let secp_ctx = Secp256k1::new();
4881 let logger = Arc::new(ln_test_utils::TestLogger::new());
4882 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
4883 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
4884 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4885 let scorer = ln_test_utils::TestScorer::new();
4886 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4887 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4888 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
4890 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4891 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4892 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4893 short_channel_id: 6,
4896 cltv_expiry_delta: (6 << 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[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4905 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4906 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4907 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4908 short_channel_id: 5,
4911 cltv_expiry_delta: (5 << 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[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4920 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4921 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4923 short_channel_id: 4,
4926 cltv_expiry_delta: (4 << 4) | 0,
4927 htlc_minimum_msat: 0,
4928 htlc_maximum_msat: MAX_VALUE_MSAT,
4930 fee_proportional_millionths: 0,
4931 excess_data: Vec::new()
4933 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4935 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4936 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4938 short_channel_id: 3,
4941 cltv_expiry_delta: (3 << 4) | 0,
4942 htlc_minimum_msat: 0,
4943 htlc_maximum_msat: MAX_VALUE_MSAT,
4945 fee_proportional_millionths: 0,
4946 excess_data: Vec::new()
4948 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4950 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4951 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4953 short_channel_id: 2,
4956 cltv_expiry_delta: (2 << 4) | 0,
4957 htlc_minimum_msat: 0,
4958 htlc_maximum_msat: MAX_VALUE_MSAT,
4960 fee_proportional_millionths: 0,
4961 excess_data: Vec::new()
4964 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4965 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4967 short_channel_id: 1,
4970 cltv_expiry_delta: (1 << 4) | 0,
4971 htlc_minimum_msat: 100,
4972 htlc_maximum_msat: MAX_VALUE_MSAT,
4974 fee_proportional_millionths: 0,
4975 excess_data: Vec::new()
4977 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4980 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4981 let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
4982 assert_eq!(route.paths.len(), 1);
4983 assert_eq!(route.paths[0].hops.len(), 3);
4985 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4986 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
4987 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4988 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
4989 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
4990 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
4992 assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
4993 assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
4994 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4995 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
4996 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
4997 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
4999 assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5000 assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5001 assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5002 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5003 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5004 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5010 fn exact_fee_liquidity_limit() {
5011 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5012 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5013 // we calculated fees on a higher value, resulting in us ignoring such paths.
5014 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5015 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5016 let scorer = ln_test_utils::TestScorer::new();
5017 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5018 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5019 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5021 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5023 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5024 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5025 short_channel_id: 2,
5028 cltv_expiry_delta: 0,
5029 htlc_minimum_msat: 0,
5030 htlc_maximum_msat: 85_000,
5032 fee_proportional_millionths: 0,
5033 excess_data: Vec::new()
5036 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5037 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5038 short_channel_id: 12,
5041 cltv_expiry_delta: (4 << 4) | 1,
5042 htlc_minimum_msat: 0,
5043 htlc_maximum_msat: 270_000,
5045 fee_proportional_millionths: 1000000,
5046 excess_data: Vec::new()
5050 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5051 // 200% fee charged channel 13 in the 1-to-2 direction.
5052 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5053 assert_eq!(route.paths.len(), 1);
5054 assert_eq!(route.paths[0].hops.len(), 2);
5056 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5057 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5058 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5059 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5060 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5061 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5063 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5064 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5065 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5066 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5067 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5068 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5073 fn htlc_max_reduction_below_min() {
5074 // Test that if, while walking the graph, we reduce the value being sent to meet an
5075 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5076 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5077 // resulting in us thinking there is no possible path, even if other paths exist.
5078 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5079 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5080 let scorer = ln_test_utils::TestScorer::new();
5081 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5082 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5083 let config = UserConfig::default();
5084 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
5086 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5087 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5088 // then try to send 90_000.
5089 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5090 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5091 short_channel_id: 2,
5094 cltv_expiry_delta: 0,
5095 htlc_minimum_msat: 0,
5096 htlc_maximum_msat: 80_000,
5098 fee_proportional_millionths: 0,
5099 excess_data: Vec::new()
5101 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5103 short_channel_id: 4,
5106 cltv_expiry_delta: (4 << 4) | 1,
5107 htlc_minimum_msat: 90_000,
5108 htlc_maximum_msat: MAX_VALUE_MSAT,
5110 fee_proportional_millionths: 0,
5111 excess_data: Vec::new()
5115 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5116 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5117 // expensive) channels 12-13 path.
5118 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5119 assert_eq!(route.paths.len(), 1);
5120 assert_eq!(route.paths[0].hops.len(), 2);
5122 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5123 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5124 assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5125 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5126 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5127 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5129 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5130 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5131 assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5132 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5133 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5134 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5139 fn multiple_direct_first_hops() {
5140 // Previously we'd only ever considered one first hop path per counterparty.
5141 // However, as we don't restrict users to one channel per peer, we really need to support
5142 // looking at all first hop paths.
5143 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5144 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5145 // route over multiple channels with the same first hop.
5146 let secp_ctx = Secp256k1::new();
5147 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5148 let logger = Arc::new(ln_test_utils::TestLogger::new());
5149 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5150 let scorer = ln_test_utils::TestScorer::new();
5151 let config = UserConfig::default();
5152 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_features(channelmanager::provided_invoice_features(&config));
5153 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5154 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5157 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5158 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5159 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5160 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5161 assert_eq!(route.paths.len(), 1);
5162 assert_eq!(route.paths[0].hops.len(), 1);
5164 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5165 assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5166 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5169 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5170 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5171 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5172 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5173 assert_eq!(route.paths.len(), 2);
5174 assert_eq!(route.paths[0].hops.len(), 1);
5175 assert_eq!(route.paths[1].hops.len(), 1);
5177 assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5178 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5180 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5181 assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5183 assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5184 assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5188 // If we have a bunch of outbound channels to the same node, where most are not
5189 // sufficient to pay the full payment, but one is, we should default to just using the
5190 // one single channel that has sufficient balance, avoiding MPP.
5192 // If we have several options above the 3xpayment value threshold, we should pick the
5193 // smallest of them, avoiding further fragmenting our available outbound balance to
5195 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5196 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5197 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5198 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5199 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5200 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5201 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5202 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5203 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5204 ]), 100_000, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5205 assert_eq!(route.paths.len(), 1);
5206 assert_eq!(route.paths[0].hops.len(), 1);
5208 assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5209 assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5210 assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5215 fn prefers_shorter_route_with_higher_fees() {
5216 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5217 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5218 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5220 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5221 let scorer = ln_test_utils::TestScorer::new();
5222 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5223 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5224 let route = get_route(
5225 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5226 Arc::clone(&logger), &scorer, &random_seed_bytes
5228 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5230 assert_eq!(route.get_total_fees(), 100);
5231 assert_eq!(route.get_total_amount(), 100);
5232 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5234 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5235 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5236 let scorer = FixedPenaltyScorer::with_penalty(100);
5237 let route = get_route(
5238 &our_id, &payment_params, &network_graph.read_only(), None, 100, 42,
5239 Arc::clone(&logger), &scorer, &random_seed_bytes
5241 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5243 assert_eq!(route.get_total_fees(), 300);
5244 assert_eq!(route.get_total_amount(), 100);
5245 assert_eq!(path, vec![2, 4, 7, 10]);
5248 struct BadChannelScorer {
5249 short_channel_id: u64,
5253 impl Writeable for BadChannelScorer {
5254 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5256 impl Score for BadChannelScorer {
5257 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage) -> u64 {
5258 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5261 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5262 fn payment_path_successful(&mut self, _path: &Path) {}
5263 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5264 fn probe_successful(&mut self, _path: &Path) {}
5267 struct BadNodeScorer {
5272 impl Writeable for BadNodeScorer {
5273 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5276 impl Score for BadNodeScorer {
5277 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage) -> u64 {
5278 if *target == self.node_id { u64::max_value() } else { 0 }
5281 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5282 fn payment_path_successful(&mut self, _path: &Path) {}
5283 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5284 fn probe_successful(&mut self, _path: &Path) {}
5288 fn avoids_routing_through_bad_channels_and_nodes() {
5289 let (secp_ctx, network, _, _, logger) = build_graph();
5290 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5291 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5292 let network_graph = network.read_only();
5294 // A path to nodes[6] exists when no penalties are applied to any channel.
5295 let scorer = ln_test_utils::TestScorer::new();
5296 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5297 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5298 let route = get_route(
5299 &our_id, &payment_params, &network_graph, None, 100, 42,
5300 Arc::clone(&logger), &scorer, &random_seed_bytes
5302 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5304 assert_eq!(route.get_total_fees(), 100);
5305 assert_eq!(route.get_total_amount(), 100);
5306 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5308 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5309 let scorer = BadChannelScorer { short_channel_id: 6 };
5310 let route = get_route(
5311 &our_id, &payment_params, &network_graph, None, 100, 42,
5312 Arc::clone(&logger), &scorer, &random_seed_bytes
5314 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5316 assert_eq!(route.get_total_fees(), 300);
5317 assert_eq!(route.get_total_amount(), 100);
5318 assert_eq!(path, vec![2, 4, 7, 10]);
5320 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5321 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5323 &our_id, &payment_params, &network_graph, None, 100, 42,
5324 Arc::clone(&logger), &scorer, &random_seed_bytes
5326 Err(LightningError { err, .. } ) => {
5327 assert_eq!(err, "Failed to find a path to the given destination");
5329 Ok(_) => panic!("Expected error"),
5334 fn total_fees_single_path() {
5336 paths: vec![Path { hops: vec![
5338 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5339 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5340 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5343 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5344 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5345 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5348 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5349 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5350 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5352 ], blinded_tail: None }],
5353 payment_params: None,
5356 assert_eq!(route.get_total_fees(), 250);
5357 assert_eq!(route.get_total_amount(), 225);
5361 fn total_fees_multi_path() {
5363 paths: vec![Path { hops: vec![
5365 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5366 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5367 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5370 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5371 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5372 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5374 ], blinded_tail: None }, Path { hops: vec![
5376 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5377 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5378 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5381 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5382 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5383 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5385 ], blinded_tail: None }],
5386 payment_params: None,
5389 assert_eq!(route.get_total_fees(), 200);
5390 assert_eq!(route.get_total_amount(), 300);
5394 fn total_empty_route_no_panic() {
5395 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5396 // would both panic if the route was completely empty. We test to ensure they return 0
5397 // here, even though its somewhat nonsensical as a route.
5398 let route = Route { paths: Vec::new(), payment_params: None };
5400 assert_eq!(route.get_total_fees(), 0);
5401 assert_eq!(route.get_total_amount(), 0);
5405 fn limits_total_cltv_delta() {
5406 let (secp_ctx, network, _, _, logger) = build_graph();
5407 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5408 let network_graph = network.read_only();
5410 let scorer = ln_test_utils::TestScorer::new();
5412 // Make sure that generally there is at least one route available
5413 let feasible_max_total_cltv_delta = 1008;
5414 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5415 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5416 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5417 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5418 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5419 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5420 assert_ne!(path.len(), 0);
5422 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5423 let fail_max_total_cltv_delta = 23;
5424 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5425 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5426 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes)
5428 Err(LightningError { err, .. } ) => {
5429 assert_eq!(err, "Failed to find a path to the given destination");
5431 Ok(_) => panic!("Expected error"),
5436 fn avoids_recently_failed_paths() {
5437 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5438 // randomly inserting channels into it until we can't find a route anymore.
5439 let (secp_ctx, network, _, _, logger) = build_graph();
5440 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5441 let network_graph = network.read_only();
5443 let scorer = ln_test_utils::TestScorer::new();
5444 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes))
5445 .with_max_path_count(1);
5446 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5447 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5449 // We should be able to find a route initially, and then after we fail a few random
5450 // channels eventually we won't be able to any longer.
5451 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes).is_ok());
5453 if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, 0, Arc::clone(&logger), &scorer, &random_seed_bytes) {
5454 for chan in route.paths[0].hops.iter() {
5455 assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5457 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5458 % route.paths[0].hops.len();
5459 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5465 fn limits_path_length() {
5466 let (secp_ctx, network, _, _, logger) = build_line_graph();
5467 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5468 let network_graph = network.read_only();
5470 let scorer = ln_test_utils::TestScorer::new();
5471 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5472 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5474 // First check we can actually create a long route on this graph.
5475 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5476 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 0,
5477 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5478 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5479 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5481 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5482 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5483 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 0,
5484 Arc::clone(&logger), &scorer, &random_seed_bytes)
5486 Err(LightningError { err, .. } ) => {
5487 assert_eq!(err, "Failed to find a path to the given destination");
5489 Ok(_) => panic!("Expected error"),
5494 fn adds_and_limits_cltv_offset() {
5495 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5496 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5498 let scorer = ln_test_utils::TestScorer::new();
5500 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes));
5501 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5502 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5503 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5504 assert_eq!(route.paths.len(), 1);
5506 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5508 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5509 let mut route_default = route.clone();
5510 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5511 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5512 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5513 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5514 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5516 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5517 let mut route_limited = route.clone();
5518 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5519 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5520 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5521 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5522 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5526 fn adds_plausible_cltv_offset() {
5527 let (secp_ctx, network, _, _, logger) = build_graph();
5528 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5529 let network_graph = network.read_only();
5530 let network_nodes = network_graph.nodes();
5531 let network_channels = network_graph.channels();
5532 let scorer = ln_test_utils::TestScorer::new();
5533 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5534 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5535 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5537 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100, 0,
5538 Arc::clone(&logger), &scorer, &random_seed_bytes).unwrap();
5539 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5541 let mut path_plausibility = vec![];
5543 for p in route.paths {
5544 // 1. Select random observation point
5545 let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5546 let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5548 prng.process_in_place(&mut random_bytes);
5549 let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5550 let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5552 // 2. Calculate what CLTV expiry delta we would observe there
5553 let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5555 // 3. Starting from the observation point, find candidate paths
5556 let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5557 candidates.push_back((observation_point, vec![]));
5559 let mut found_plausible_candidate = false;
5561 'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5562 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5563 if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5564 found_plausible_candidate = true;
5565 break 'candidate_loop;
5569 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5570 for channel_id in &cur_node.channels {
5571 if let Some(channel_info) = network_channels.get(&channel_id) {
5572 if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5573 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5574 if cur_path_cltv_deltas.iter().sum::<u32>()
5575 .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5576 let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5577 new_path_cltv_deltas.push(next_cltv_expiry_delta);
5578 candidates.push_back((*next_id, new_path_cltv_deltas));
5586 path_plausibility.push(found_plausible_candidate);
5588 assert!(path_plausibility.iter().all(|x| *x));
5592 fn builds_correct_path_from_hops() {
5593 let (secp_ctx, network, _, _, logger) = build_graph();
5594 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5595 let network_graph = network.read_only();
5597 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5598 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5600 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5601 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5602 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5603 &network_graph, 100, 0, Arc::clone(&logger), &random_seed_bytes).unwrap();
5604 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5605 assert_eq!(hops.len(), route.paths[0].hops.len());
5606 for (idx, hop_pubkey) in hops.iter().enumerate() {
5607 assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5612 fn avoids_saturating_channels() {
5613 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5614 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5616 let scorer = ProbabilisticScorer::new(Default::default(), &*network_graph, Arc::clone(&logger));
5618 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5619 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5620 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5621 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5622 short_channel_id: 4,
5625 cltv_expiry_delta: (4 << 4) | 1,
5626 htlc_minimum_msat: 0,
5627 htlc_maximum_msat: 250_000_000,
5629 fee_proportional_millionths: 0,
5630 excess_data: Vec::new()
5632 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5633 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5634 short_channel_id: 13,
5637 cltv_expiry_delta: (13 << 4) | 1,
5638 htlc_minimum_msat: 0,
5639 htlc_maximum_msat: 250_000_000,
5641 fee_proportional_millionths: 0,
5642 excess_data: Vec::new()
5645 let config = UserConfig::default();
5646 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_features(channelmanager::provided_invoice_features(&config));
5647 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5648 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5649 // 100,000 sats is less than the available liquidity on each channel, set above.
5650 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();
5651 assert_eq!(route.paths.len(), 2);
5652 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
5653 (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
5656 #[cfg(not(feature = "no-std"))]
5657 pub(super) fn random_init_seed() -> u64 {
5658 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5659 use core::hash::{BuildHasher, Hasher};
5660 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5661 println!("Using seed of {}", seed);
5664 #[cfg(not(feature = "no-std"))]
5665 use crate::util::ser::ReadableArgs;
5668 #[cfg(not(feature = "no-std"))]
5669 fn generate_routes() {
5670 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5672 let mut d = match super::bench_utils::get_route_file() {
5679 let logger = ln_test_utils::TestLogger::new();
5680 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5681 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5682 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5684 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5685 let mut seed = random_init_seed() as usize;
5686 let nodes = graph.read_only().nodes().clone();
5687 'load_endpoints: for _ in 0..10 {
5689 seed = seed.overflowing_mul(0xdeadbeef).0;
5690 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5691 seed = seed.overflowing_mul(0xdeadbeef).0;
5692 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5693 let payment_params = PaymentParameters::from_node_id(dst, 42);
5694 let amt = seed as u64 % 200_000_000;
5695 let params = ProbabilisticScoringParameters::default();
5696 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5697 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5698 continue 'load_endpoints;
5705 #[cfg(not(feature = "no-std"))]
5706 fn generate_routes_mpp() {
5707 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
5709 let mut d = match super::bench_utils::get_route_file() {
5716 let logger = ln_test_utils::TestLogger::new();
5717 let graph = NetworkGraph::read(&mut d, &logger).unwrap();
5718 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5719 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5720 let config = UserConfig::default();
5722 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5723 let mut seed = random_init_seed() as usize;
5724 let nodes = graph.read_only().nodes().clone();
5725 'load_endpoints: for _ in 0..10 {
5727 seed = seed.overflowing_mul(0xdeadbeef).0;
5728 let src = &PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5729 seed = seed.overflowing_mul(0xdeadbeef).0;
5730 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5731 let payment_params = PaymentParameters::from_node_id(dst, 42).with_features(channelmanager::provided_invoice_features(&config));
5732 let amt = seed as u64 % 200_000_000;
5733 let params = ProbabilisticScoringParameters::default();
5734 let scorer = ProbabilisticScorer::new(params, &graph, &logger);
5735 if get_route(src, &payment_params, &graph.read_only(), None, amt, 42, &logger, &scorer, &random_seed_bytes).is_ok() {
5736 continue 'load_endpoints;
5743 fn honors_manual_penalties() {
5744 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
5745 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5747 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5748 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5750 let scorer_params = ProbabilisticScoringParameters::default();
5751 let mut scorer = ProbabilisticScorer::new(scorer_params, Arc::clone(&network_graph), Arc::clone(&logger));
5753 // First check set manual penalties are returned by the scorer.
5754 let usage = ChannelUsage {
5756 inflight_htlc_msat: 0,
5757 effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
5759 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
5760 scorer.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
5761 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage), 456);
5763 // Then check we can get a normal route
5764 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
5765 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5766 assert!(route.is_ok());
5768 // Then check that we can't get a route if we ban an intermediate node.
5769 scorer.add_banned(&NodeId::from_pubkey(&nodes[3]));
5770 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5771 assert!(route.is_err());
5773 // Finally make sure we can route again, when we remove the ban.
5774 scorer.remove_banned(&NodeId::from_pubkey(&nodes[3]));
5775 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, 42, Arc::clone(&logger), &scorer, &random_seed_bytes);
5776 assert!(route.is_ok());
5780 fn blinded_route_ser() {
5781 let blinded_path_1 = BlindedPath {
5782 introduction_node_id: ln_test_utils::pubkey(42),
5783 blinding_point: ln_test_utils::pubkey(43),
5785 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
5786 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
5789 let blinded_path_2 = BlindedPath {
5790 introduction_node_id: ln_test_utils::pubkey(46),
5791 blinding_point: ln_test_utils::pubkey(47),
5793 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
5794 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
5797 // (De)serialize a Route with 1 blinded path out of two total paths.
5798 let mut route = Route { paths: vec![Path {
5799 hops: vec![RouteHop {
5800 pubkey: ln_test_utils::pubkey(50),
5801 node_features: NodeFeatures::empty(),
5802 short_channel_id: 42,
5803 channel_features: ChannelFeatures::empty(),
5805 cltv_expiry_delta: 0,
5807 blinded_tail: Some(BlindedTail {
5808 hops: blinded_path_1.blinded_hops,
5809 blinding_point: blinded_path_1.blinding_point,
5810 excess_final_cltv_expiry_delta: 40,
5811 final_value_msat: 100,
5813 hops: vec![RouteHop {
5814 pubkey: ln_test_utils::pubkey(51),
5815 node_features: NodeFeatures::empty(),
5816 short_channel_id: 43,
5817 channel_features: ChannelFeatures::empty(),
5819 cltv_expiry_delta: 0,
5820 }], blinded_tail: None }],
5821 payment_params: None,
5823 let encoded_route = route.encode();
5824 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
5825 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
5826 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
5828 // (De)serialize a Route with two paths, each containing a blinded tail.
5829 route.paths[1].blinded_tail = Some(BlindedTail {
5830 hops: blinded_path_2.blinded_hops,
5831 blinding_point: blinded_path_2.blinding_point,
5832 excess_final_cltv_expiry_delta: 41,
5833 final_value_msat: 101,
5835 let encoded_route = route.encode();
5836 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
5837 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
5838 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
5842 fn blinded_path_inflight_processing() {
5843 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
5844 // account for the blinded tail's final amount_msat.
5845 let mut inflight_htlcs = InFlightHtlcs::new();
5846 let blinded_path = BlindedPath {
5847 introduction_node_id: ln_test_utils::pubkey(43),
5848 blinding_point: ln_test_utils::pubkey(48),
5849 blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
5852 hops: vec![RouteHop {
5853 pubkey: ln_test_utils::pubkey(42),
5854 node_features: NodeFeatures::empty(),
5855 short_channel_id: 42,
5856 channel_features: ChannelFeatures::empty(),
5858 cltv_expiry_delta: 0,
5861 pubkey: blinded_path.introduction_node_id,
5862 node_features: NodeFeatures::empty(),
5863 short_channel_id: 43,
5864 channel_features: ChannelFeatures::empty(),
5866 cltv_expiry_delta: 0,
5868 blinded_tail: Some(BlindedTail {
5869 hops: blinded_path.blinded_hops,
5870 blinding_point: blinded_path.blinding_point,
5871 excess_final_cltv_expiry_delta: 0,
5872 final_value_msat: 200,
5875 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
5876 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
5877 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
5881 fn blinded_path_cltv_shadow_offset() {
5882 // Make sure we add a shadow offset when sending to blinded paths.
5883 let blinded_path = BlindedPath {
5884 introduction_node_id: ln_test_utils::pubkey(43),
5885 blinding_point: ln_test_utils::pubkey(44),
5887 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
5888 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
5891 let mut route = Route { paths: vec![Path {
5892 hops: vec![RouteHop {
5893 pubkey: ln_test_utils::pubkey(42),
5894 node_features: NodeFeatures::empty(),
5895 short_channel_id: 42,
5896 channel_features: ChannelFeatures::empty(),
5898 cltv_expiry_delta: 0,
5901 pubkey: blinded_path.introduction_node_id,
5902 node_features: NodeFeatures::empty(),
5903 short_channel_id: 43,
5904 channel_features: ChannelFeatures::empty(),
5906 cltv_expiry_delta: 0,
5909 blinded_tail: Some(BlindedTail {
5910 hops: blinded_path.blinded_hops,
5911 blinding_point: blinded_path.blinding_point,
5912 excess_final_cltv_expiry_delta: 0,
5913 final_value_msat: 200,
5915 }], payment_params: None};
5917 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
5918 let (_, network_graph, _, _, _) = build_line_graph();
5919 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
5920 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
5921 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
5925 #[cfg(all(test, not(feature = "no-std")))]
5926 pub(crate) mod bench_utils {
5928 /// Tries to open a network graph file, or panics with a URL to fetch it.
5929 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5930 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
5931 .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
5932 .or_else(|_| { // Fall back to guessing based on the binary location
5933 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5934 let mut path = std::env::current_exe().unwrap();
5935 path.pop(); // lightning-...
5937 path.pop(); // debug
5938 path.pop(); // target
5939 path.push("lightning");
5940 path.push("net_graph-2023-01-18.bin");
5941 eprintln!("{}", path.to_str().unwrap());
5944 .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");
5945 #[cfg(require_route_graph_test)]
5946 return Ok(res.unwrap());
5947 #[cfg(not(require_route_graph_test))]
5952 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5955 use bitcoin::hashes::Hash;
5956 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5957 use crate::chain::transaction::OutPoint;
5958 use crate::chain::keysinterface::{EntropySource, KeysManager};
5959 use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
5960 use crate::ln::features::InvoiceFeatures;
5961 use crate::routing::gossip::NetworkGraph;
5962 use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters};
5963 use crate::util::config::UserConfig;
5964 use crate::util::logger::{Logger, Record};
5965 use crate::util::ser::ReadableArgs;
5969 struct DummyLogger {}
5970 impl Logger for DummyLogger {
5971 fn log(&self, _record: &Record) {}
5974 fn read_network_graph(logger: &DummyLogger) -> NetworkGraph<&DummyLogger> {
5975 let mut d = bench_utils::get_route_file().unwrap();
5976 NetworkGraph::read(&mut d, logger).unwrap()
5979 fn payer_pubkey() -> PublicKey {
5980 let secp_ctx = Secp256k1::new();
5981 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5985 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5987 channel_id: [0; 32],
5988 counterparty: ChannelCounterparty {
5989 features: channelmanager::provided_init_features(&UserConfig::default()),
5991 unspendable_punishment_reserve: 0,
5992 forwarding_info: None,
5993 outbound_htlc_minimum_msat: None,
5994 outbound_htlc_maximum_msat: None,
5996 funding_txo: Some(OutPoint {
5997 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6000 short_channel_id: Some(1),
6001 inbound_scid_alias: None,
6002 outbound_scid_alias: None,
6003 channel_value_satoshis: 10_000_000,
6005 balance_msat: 10_000_000,
6006 outbound_capacity_msat: 10_000_000,
6007 next_outbound_htlc_limit_msat: 10_000_000,
6008 inbound_capacity_msat: 0,
6009 unspendable_punishment_reserve: None,
6010 confirmations_required: None,
6011 confirmations: None,
6012 force_close_spend_delay: None,
6014 is_channel_ready: true,
6017 inbound_htlc_minimum_msat: None,
6018 inbound_htlc_maximum_msat: None,
6020 feerate_sat_per_1000_weight: None,
6025 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
6026 let logger = DummyLogger {};
6027 let network_graph = read_network_graph(&logger);
6028 let scorer = FixedPenaltyScorer::with_penalty(0);
6029 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
6033 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
6034 let logger = DummyLogger {};
6035 let network_graph = read_network_graph(&logger);
6036 let scorer = FixedPenaltyScorer::with_penalty(0);
6037 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
6041 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
6042 let logger = DummyLogger {};
6043 let network_graph = read_network_graph(&logger);
6044 let params = ProbabilisticScoringParameters::default();
6045 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
6046 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
6050 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
6051 let logger = DummyLogger {};
6052 let network_graph = read_network_graph(&logger);
6053 let params = ProbabilisticScoringParameters::default();
6054 let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
6055 generate_routes(bench, &network_graph, scorer, channelmanager::provided_invoice_features(&UserConfig::default()));
6058 fn generate_routes<S: Score>(
6059 bench: &mut Bencher, graph: &NetworkGraph<&DummyLogger>, mut scorer: S,
6060 features: InvoiceFeatures
6062 let nodes = graph.read_only().nodes().clone();
6063 let payer = payer_pubkey();
6064 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6065 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6067 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
6068 let mut routes = Vec::new();
6069 let mut route_endpoints = Vec::new();
6070 let mut seed: usize = 0xdeadbeef;
6071 'load_endpoints: for _ in 0..150 {
6074 let src = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
6076 let dst = PublicKey::from_slice(nodes.unordered_keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
6077 let params = PaymentParameters::from_node_id(dst, 42).with_features(features.clone());
6078 let first_hop = first_hop(src);
6079 let amt = seed as u64 % 1_000_000;
6080 if let Ok(route) = get_route(&payer, ¶ms, &graph.read_only(), Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes) {
6082 route_endpoints.push((first_hop, params, amt));
6083 continue 'load_endpoints;
6088 // ...and seed the scorer with success and failure data...
6089 for route in routes {
6090 let amount = route.get_total_amount();
6091 if amount < 250_000 {
6092 for path in route.paths {
6093 scorer.payment_path_successful(&path);
6095 } else if amount > 750_000 {
6096 for path in route.paths {
6097 let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6098 scorer.payment_path_failed(&path, short_channel_id);
6103 // Because we've changed channel scores, its possible we'll take different routes to the
6104 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
6105 // requires a too-high CLTV delta.
6106 route_endpoints.retain(|(first_hop, params, amt)| {
6107 get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok()
6109 route_endpoints.truncate(100);
6110 assert_eq!(route_endpoints.len(), 100);
6112 // ...then benchmark finding paths between the nodes we learned.
6115 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
6116 assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer, &random_seed_bytes).is_ok());