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 top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::scoring::Score;
21 use routing::network_graph::{DirectedChannelInfoWithUpdate, EffectiveCapacity, NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payment_params` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payment_params: Option<PaymentParameters>,
81 pub(crate) trait RoutePath {
82 /// Gets the fees for a given path, excluding any excess paid to the recipient.
83 fn get_path_fees(&self) -> u64;
85 impl RoutePath for Vec<RouteHop> {
86 fn get_path_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
89 .iter().map(|hop| &hop.fee_msat)
95 /// Returns the total amount of fees paid on this [`Route`].
97 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
98 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
99 pub fn get_total_fees(&self) -> u64 {
100 self.paths.iter().map(|path| path.get_path_fees()).sum()
103 /// Returns the total amount paid on this [`Route`], excluding the fees.
104 pub fn get_total_amount(&self) -> u64 {
105 return self.paths.iter()
106 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
111 const SERIALIZATION_VERSION: u8 = 1;
112 const MIN_SERIALIZATION_VERSION: u8 = 1;
114 impl Writeable for Route {
115 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
116 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
117 (self.paths.len() as u64).write(writer)?;
118 for hops in self.paths.iter() {
119 (hops.len() as u8).write(writer)?;
120 for hop in hops.iter() {
124 write_tlv_fields!(writer, {
125 (1, self.payment_params, option),
131 impl Readable for Route {
132 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
133 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
134 let path_count: u64 = Readable::read(reader)?;
135 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
136 for _ in 0..path_count {
137 let hop_count: u8 = Readable::read(reader)?;
138 let mut hops = Vec::with_capacity(hop_count as usize);
139 for _ in 0..hop_count {
140 hops.push(Readable::read(reader)?);
144 let mut payment_params = None;
145 read_tlv_fields!(reader, {
146 (1, payment_params, option),
148 Ok(Route { paths, payment_params })
152 /// Parameters needed to find a [`Route`].
154 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
157 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
158 #[derive(Clone, Debug)]
159 pub struct RouteParameters {
160 /// The parameters of the failed payment path.
161 pub payment_params: PaymentParameters,
163 /// The amount in msats sent on the failed payment path.
164 pub final_value_msat: u64,
166 /// The CLTV on the final hop of the failed payment path.
167 pub final_cltv_expiry_delta: u32,
170 impl_writeable_tlv_based!(RouteParameters, {
171 (0, payment_params, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// Maximum total CTLV difference we allow for a full payment path.
177 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
179 /// The recipient of a payment.
180 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
181 pub struct PaymentParameters {
182 /// The node id of the payee.
183 pub payee_pubkey: PublicKey,
185 /// Features supported by the payee.
187 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
188 /// does not contain any features.
190 /// [`for_keysend`]: Self::for_keysend
191 pub features: Option<InvoiceFeatures>,
193 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
194 pub route_hints: Vec<RouteHint>,
196 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
197 pub expiry_time: Option<u64>,
199 /// The maximum total CLTV delta we accept for the route.
200 pub max_total_cltv_expiry_delta: u32,
203 impl_writeable_tlv_based!(PaymentParameters, {
204 (0, payee_pubkey, required),
205 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
206 (2, features, option),
207 (4, route_hints, vec_type),
208 (6, expiry_time, option),
211 impl PaymentParameters {
212 /// Creates a payee with the node id of the given `pubkey`.
213 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
219 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
223 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
224 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
225 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
228 /// Includes the payee's features.
230 /// (C-not exported) since bindings don't support move semantics
231 pub fn with_features(self, features: InvoiceFeatures) -> Self {
232 Self { features: Some(features), ..self }
235 /// Includes hints for routing to the payee.
237 /// (C-not exported) since bindings don't support move semantics
238 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
239 Self { route_hints, ..self }
242 /// Includes a payment expiration in seconds relative to the UNIX epoch.
244 /// (C-not exported) since bindings don't support move semantics
245 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
246 Self { expiry_time: Some(expiry_time), ..self }
249 /// Includes a limit for the total CLTV expiry delta which is considered during routing
251 /// (C-not exported) since bindings don't support move semantics
252 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
253 Self { max_total_cltv_expiry_delta, ..self }
257 /// A list of hops along a payment path terminating with a channel to the recipient.
258 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
259 pub struct RouteHint(pub Vec<RouteHintHop>);
262 impl Writeable for RouteHint {
263 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
264 (self.0.len() as u64).write(writer)?;
265 for hop in self.0.iter() {
272 impl Readable for RouteHint {
273 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
274 let hop_count: u64 = Readable::read(reader)?;
275 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
276 for _ in 0..hop_count {
277 hops.push(Readable::read(reader)?);
283 /// A channel descriptor for a hop along a payment path.
284 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
285 pub struct RouteHintHop {
286 /// The node_id of the non-target end of the route
287 pub src_node_id: PublicKey,
288 /// The short_channel_id of this channel
289 pub short_channel_id: u64,
290 /// The fees which must be paid to use this channel
291 pub fees: RoutingFees,
292 /// The difference in CLTV values between this node and the next node.
293 pub cltv_expiry_delta: u16,
294 /// The minimum value, in msat, which must be relayed to the next hop.
295 pub htlc_minimum_msat: Option<u64>,
296 /// The maximum value in msat available for routing with a single HTLC.
297 pub htlc_maximum_msat: Option<u64>,
300 impl_writeable_tlv_based!(RouteHintHop, {
301 (0, src_node_id, required),
302 (1, htlc_minimum_msat, option),
303 (2, short_channel_id, required),
304 (3, htlc_maximum_msat, option),
306 (6, cltv_expiry_delta, required),
309 #[derive(Eq, PartialEq)]
310 struct RouteGraphNode {
312 lowest_fee_to_peer_through_node: u64,
313 lowest_fee_to_node: u64,
314 total_cltv_delta: u32,
315 // The maximum value a yet-to-be-constructed payment path might flow through this node.
316 // This value is upper-bounded by us by:
317 // - how much is needed for a path being constructed
318 // - how much value can channels following this node (up to the destination) can contribute,
319 // considering their capacity and fees
320 value_contribution_msat: u64,
321 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
322 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
323 path_htlc_minimum_msat: u64,
324 /// All penalties incurred from this hop on the way to the destination, as calculated using
326 path_penalty_msat: u64,
329 impl cmp::Ord for RouteGraphNode {
330 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
331 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
332 .checked_add(other.path_penalty_msat)
333 .unwrap_or_else(|| u64::max_value());
334 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
335 .checked_add(self.path_penalty_msat)
336 .unwrap_or_else(|| u64::max_value());
337 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
341 impl cmp::PartialOrd for RouteGraphNode {
342 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
343 Some(self.cmp(other))
347 /// A wrapper around the various hop representations.
349 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
350 #[derive(Clone, Debug)]
351 enum CandidateRouteHop<'a> {
352 /// A hop from the payer, where the outbound liquidity is known.
354 details: &'a ChannelDetails,
356 /// A hop found in the [`NetworkGraph`], where the channel capacity may or may not be known.
358 info: DirectedChannelInfoWithUpdate<'a>,
359 short_channel_id: u64,
361 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
363 hint: &'a RouteHintHop,
367 impl<'a> CandidateRouteHop<'a> {
368 fn short_channel_id(&self) -> u64 {
370 CandidateRouteHop::FirstHop { details } => details.short_channel_id.unwrap(),
371 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
372 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
376 // NOTE: This may alloc memory so avoid calling it in a hot code path.
377 fn features(&self) -> ChannelFeatures {
379 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
380 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
381 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
385 fn cltv_expiry_delta(&self) -> u32 {
387 CandidateRouteHop::FirstHop { .. } => 0,
388 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
389 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
393 fn htlc_minimum_msat(&self) -> u64 {
395 CandidateRouteHop::FirstHop { .. } => 0,
396 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
397 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
401 fn fees(&self) -> RoutingFees {
403 CandidateRouteHop::FirstHop { .. } => RoutingFees {
404 base_msat: 0, proportional_millionths: 0,
406 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
407 CandidateRouteHop::PrivateHop { hint } => hint.fees,
411 fn effective_capacity(&self) -> EffectiveCapacity {
413 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
414 liquidity_msat: details.outbound_capacity_msat,
416 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
417 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
422 /// It's useful to keep track of the hops associated with the fees required to use them,
423 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
424 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
425 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
427 struct PathBuildingHop<'a> {
428 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
429 // is a larger refactor and will require careful performance analysis.
431 candidate: CandidateRouteHop<'a>,
434 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
435 src_lowest_inbound_fees: RoutingFees,
436 /// All the fees paid *after* this channel on the way to the destination
437 next_hops_fee_msat: u64,
438 /// Fee paid for the use of the current channel (see candidate.fees()).
439 /// The value will be actually deducted from the counterparty balance on the previous link.
440 hop_use_fee_msat: u64,
441 /// Used to compare channels when choosing the for routing.
442 /// Includes paying for the use of a hop and the following hops, as well as
443 /// an estimated cost of reaching this hop.
444 /// Might get stale when fees are recomputed. Primarily for internal use.
446 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
447 /// walk and may be invalid thereafter.
448 path_htlc_minimum_msat: u64,
449 /// All penalties incurred from this channel on the way to the destination, as calculated using
451 path_penalty_msat: u64,
452 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
453 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
454 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
455 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
456 /// avoid processing them again.
458 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
459 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
460 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
461 // value_contribution_msat, which requires tracking it here. See comments below where it is
462 // used for more info.
463 value_contribution_msat: u64,
466 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
467 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
468 f.debug_struct("PathBuildingHop")
469 .field("node_id", &self.node_id)
470 .field("short_channel_id", &self.candidate.short_channel_id())
471 .field("total_fee_msat", &self.total_fee_msat)
472 .field("next_hops_fee_msat", &self.next_hops_fee_msat)
473 .field("hop_use_fee_msat", &self.hop_use_fee_msat)
474 .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)))
475 .field("path_penalty_msat", &self.path_penalty_msat)
476 .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
477 .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta())
482 // Instantiated with a list of hops with correct data in them collected during path finding,
483 // an instance of this struct should be further modified only via given methods.
485 struct PaymentPath<'a> {
486 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
489 impl<'a> PaymentPath<'a> {
490 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
491 fn get_value_msat(&self) -> u64 {
492 self.hops.last().unwrap().0.fee_msat
495 fn get_total_fee_paid_msat(&self) -> u64 {
496 if self.hops.len() < 1 {
500 // Can't use next_hops_fee_msat because it gets outdated.
501 for (i, (hop, _)) in self.hops.iter().enumerate() {
502 if i != self.hops.len() - 1 {
503 result += hop.fee_msat;
509 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
510 // to change fees may result in an inconsistency.
512 // Sometimes we call this function right after constructing a path which is inconsistent in
513 // that it the value being transferred has decreased while we were doing path finding, leading
514 // to the fees being paid not lining up with the actual limits.
516 // Note that this function is not aware of the available_liquidity limit, and thus does not
517 // support increasing the value being transferred.
518 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
519 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
521 let mut total_fee_paid_msat = 0 as u64;
522 for i in (0..self.hops.len()).rev() {
523 let last_hop = i == self.hops.len() - 1;
525 // For non-last-hop, this value will represent the fees paid on the current hop. It
526 // will consist of the fees for the use of the next hop, and extra fees to match
527 // htlc_minimum_msat of the current channel. Last hop is handled separately.
528 let mut cur_hop_fees_msat = 0;
530 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
533 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
534 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
535 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
536 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
537 // set it too high just to maliciously take more fees by exploiting this
538 // match htlc_minimum_msat logic.
539 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
540 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
541 // Note that there is a risk that *previous hops* (those closer to us, as we go
542 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
544 // This might make us end up with a broken route, although this should be super-rare
545 // in practice, both because of how healthy channels look like, and how we pick
546 // channels in add_entry.
547 // Also, this can't be exploited more heavily than *announce a free path and fail
549 cur_hop_transferred_amount_msat += extra_fees_msat;
550 total_fee_paid_msat += extra_fees_msat;
551 cur_hop_fees_msat += extra_fees_msat;
555 // Final hop is a special case: it usually has just value_msat (by design), but also
556 // it still could overpay for the htlc_minimum_msat.
557 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
559 // Propagate updated fees for the use of the channels to one hop back, where they
560 // will be actually paid (fee_msat). The last hop is handled above separately.
561 cur_hop.fee_msat = cur_hop_fees_msat;
564 // Fee for the use of the current hop which will be deducted on the previous hop.
565 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
566 // this channel is free for us.
568 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
569 cur_hop.hop_use_fee_msat = new_fee;
570 total_fee_paid_msat += new_fee;
572 // It should not be possible because this function is called only to reduce the
573 // value. In that case, compute_fee was already called with the same fees for
574 // larger amount and there was no overflow.
582 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
583 let proportional_fee_millions =
584 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
585 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
586 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
590 // This function may be (indirectly) called without any verification,
591 // with channel_fees provided by a caller. We should handle it gracefully.
596 /// Finds a route from us (payer) to the given target node (payee).
598 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
599 /// Without this, MPP will only be used if the payee's features are available in the network graph.
601 /// Private routing paths between a public node and the target may be included in `params.payee`.
603 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
604 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
605 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
607 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
608 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
609 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
613 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
614 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
619 /// Panics if first_hops contains channels without short_channel_ids;
620 /// [`ChannelManager::list_usable_channels`] will never include such channels.
622 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
623 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
624 pub fn find_route<L: Deref, S: Score>(
625 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
626 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
627 ) -> Result<Route, LightningError>
628 where L::Target: Logger {
630 our_node_pubkey, &route_params.payment_params, network, first_hops, route_params.final_value_msat,
631 route_params.final_cltv_expiry_delta, logger, scorer
635 pub(crate) fn get_route<L: Deref, S: Score>(
636 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network: &NetworkGraph,
637 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
638 logger: L, scorer: &S
639 ) -> Result<Route, LightningError>
640 where L::Target: Logger {
641 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
642 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
644 if payee_node_id == our_node_id {
645 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
648 if final_value_msat > MAX_VALUE_MSAT {
649 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
652 if final_value_msat == 0 {
653 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
656 for route in payment_params.route_hints.iter() {
657 for hop in &route.0 {
658 if hop.src_node_id == payment_params.payee_pubkey {
659 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
664 // The general routing idea is the following:
665 // 1. Fill first/last hops communicated by the caller.
666 // 2. Attempt to construct a path from payer to payee for transferring
667 // any ~sufficient (described later) value.
668 // If succeed, remember which channels were used and how much liquidity they have available,
669 // so that future paths don't rely on the same liquidity.
670 // 3. Proceed to the next step if:
671 // - we hit the recommended target value;
672 // - OR if we could not construct a new path. Any next attempt will fail too.
673 // Otherwise, repeat step 2.
674 // 4. See if we managed to collect paths which aggregately are able to transfer target value
675 // (not recommended value). If yes, proceed. If not, fail routing.
676 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
677 // 6. Of all the found paths, select only those with the lowest total fee.
678 // 7. The last path in every selected route is likely to be more than we need.
679 // Reduce its value-to-transfer and recompute fees.
680 // 8. Choose the best route by the lowest total fee.
682 // As for the actual search algorithm,
683 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
684 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
686 // We are not a faithful Dijkstra's implementation because we can change values which impact
687 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
688 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
689 // the value we are currently attempting to send over a path, we simply reduce the value being
690 // sent along the path for any hops after that channel. This may imply that later fees (which
691 // we've already tabulated) are lower because a smaller value is passing through the channels
692 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
693 // channels which were selected earlier (and which may still be used for other paths without a
694 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
697 // One potentially problematic case for this algorithm would be if there are many
698 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
699 // graph walking), we may never find a path which is not liquidity-limited and has lower
700 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
701 // Because we only consider paths with at least 5% of the total value being sent, the damage
702 // from such a case should be limited, however this could be further reduced in the future by
703 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
704 // limits for the purposes of fee calculation.
706 // Alternatively, we could store more detailed path information in the heap (targets, below)
707 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
708 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
709 // and practically (as we would need to store dynamically-allocated path information in heap
710 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
711 // results of such an algorithm would likely be biased towards lower-value paths.
713 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
714 // outside of our current search value, running a path search more times to gather candidate
715 // paths at different values. While this may be acceptable, further path searches may increase
716 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
717 // graph for candidate paths, calculating the maximum value which can realistically be sent at
718 // the same time, remaining generic across different payment values.
720 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
721 // to use as the A* heuristic beyond just the cost to get one node further than the current
724 let network_graph = network.read_only();
725 let network_channels = network_graph.channels();
726 let network_nodes = network_graph.nodes();
728 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
729 // it. If the payee supports it they're supposed to include it in the invoice, so that should
731 let allow_mpp = if let Some(features) = &payment_params.features {
732 features.supports_basic_mpp()
733 } else if let Some(node) = network_nodes.get(&payee_node_id) {
734 if let Some(node_info) = node.announcement_info.as_ref() {
735 node_info.features.supports_basic_mpp()
738 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
739 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
740 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
743 // Prepare the data we'll use for payee-to-payer search by
744 // inserting first hops suggested by the caller as targets.
745 // Our search will then attempt to reach them while traversing from the payee node.
746 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
747 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
748 if let Some(hops) = first_hops {
750 if chan.short_channel_id.is_none() {
751 panic!("first_hops should be filled in with usable channels, not pending ones");
753 if chan.counterparty.node_id == *our_node_pubkey {
754 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
757 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
758 .or_insert(Vec::new())
761 if first_hop_targets.is_empty() {
762 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
766 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
767 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
768 // adding duplicate entries when we find a better path to a given node.
769 let mut targets = BinaryHeap::new();
771 // Map from node_id to information about the best current path to that node, including feerate
773 let mut dist = HashMap::with_capacity(network_nodes.len());
775 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
776 // indicating that we may wish to try again with a higher value, potentially paying to meet an
777 // htlc_minimum with extra fees while still finding a cheaper path.
778 let mut hit_minimum_limit;
780 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
781 // We start with a path_value of the exact amount we want, and if that generates a route we may
782 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
783 // amount we want in total across paths, selecting the best subset at the end.
784 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
785 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
786 let mut path_value_msat = final_value_msat;
788 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
789 // This map allows paths to be aware of the channel use by other paths in the same call.
790 // This would help to make a better path finding decisions and not "overbook" channels.
791 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
792 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
794 // Keeping track of how much value we already collected across other paths. Helps to decide:
795 // - how much a new path should be transferring (upper bound);
796 // - whether a channel should be disregarded because
797 // it's available liquidity is too small comparing to how much more we need to collect;
798 // - when we want to stop looking for new paths.
799 let mut already_collected_value_msat = 0;
801 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
803 macro_rules! add_entry {
804 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
805 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
806 // since that value has to be transferred over this channel.
807 // Returns whether this channel caused an update to `targets`.
808 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
809 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
810 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
811 // We "return" whether we updated the path at the end, via this:
812 let mut did_add_update_path_to_src_node = false;
813 // Channels to self should not be used. This is more of belt-and-suspenders, because in
814 // practice these cases should be caught earlier:
815 // - for regular channels at channel announcement (TODO)
816 // - for first and last hops early in get_route
817 if $src_node_id != $dest_node_id {
818 let short_channel_id = $candidate.short_channel_id();
819 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
820 .entry(short_channel_id)
821 .or_insert_with(|| $candidate.effective_capacity().as_msat());
823 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
824 // It may be misleading because we might later choose to reduce the value transferred
825 // over these channels, and the channel which was insufficient might become sufficient.
826 // Worst case: we drop a good channel here because it can't cover the high following
827 // fees caused by one expensive channel, but then this channel could have been used
828 // if the amount being transferred over this path is lower.
829 // We do this for now, but this is a subject for removal.
830 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
832 // Routing Fragmentation Mitigation heuristic:
834 // Routing fragmentation across many payment paths increases the overall routing
835 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
836 // Taking too many smaller paths also increases the chance of payment failure.
837 // Thus to avoid this effect, we require from our collected links to provide
838 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
840 // This requirement is currently 5% of the remaining-to-be-collected value.
841 // This means as we successfully advance in our collection,
842 // the absolute liquidity contribution is lowered,
843 // thus increasing the number of potential channels to be selected.
845 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
846 // or 100% if we're not allowed to do multipath payments.
847 let minimal_value_contribution_msat: u64 = if allow_mpp {
848 (recommended_value_msat - already_collected_value_msat + 19) / 20
852 // Verify the liquidity offered by this channel complies to the minimal contribution.
853 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
855 // Do not consider candidates that exceed the maximum total cltv expiry limit.
856 let max_total_cltv_expiry_delta = payment_params.max_total_cltv_expiry_delta;
857 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
858 .checked_add($candidate.cltv_expiry_delta())
859 .unwrap_or(u32::max_value());
860 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
862 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
863 // Includes paying fees for the use of the following channels.
864 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
865 Some(result) => result,
866 // Can't overflow due to how the values were computed right above.
867 None => unreachable!(),
869 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
870 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
871 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
873 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
874 // bother considering this channel.
875 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
876 // be only reduced later (not increased), so this channel should just be skipped
877 // as not sufficient.
878 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
879 hit_minimum_limit = true;
880 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
881 // Note that low contribution here (limited by available_liquidity_msat)
882 // might violate htlc_minimum_msat on the hops which are next along the
883 // payment path (upstream to the payee). To avoid that, we recompute
884 // path fees knowing the final path contribution after constructing it.
885 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
886 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
887 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
888 .unwrap_or_else(|| u64::max_value());
889 let hm_entry = dist.entry($src_node_id);
890 let old_entry = hm_entry.or_insert_with(|| {
891 // If there was previously no known way to access the source node
892 // (recall it goes payee-to-payer) of short_channel_id, first add a
893 // semi-dummy record just to compute the fees to reach the source node.
894 // This will affect our decision on selecting short_channel_id
895 // as a way to reach the $dest_node_id.
896 let mut fee_base_msat = u32::max_value();
897 let mut fee_proportional_millionths = u32::max_value();
898 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
899 fee_base_msat = fees.base_msat;
900 fee_proportional_millionths = fees.proportional_millionths;
903 node_id: $dest_node_id.clone(),
904 candidate: $candidate.clone(),
906 src_lowest_inbound_fees: RoutingFees {
907 base_msat: fee_base_msat,
908 proportional_millionths: fee_proportional_millionths,
910 next_hops_fee_msat: u64::max_value(),
911 hop_use_fee_msat: u64::max_value(),
912 total_fee_msat: u64::max_value(),
913 path_htlc_minimum_msat,
914 path_penalty_msat: u64::max_value(),
915 was_processed: false,
916 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
917 value_contribution_msat,
921 #[allow(unused_mut)] // We only use the mut in cfg(test)
922 let mut should_process = !old_entry.was_processed;
923 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
925 // In test/fuzzing builds, we do extra checks to make sure the skipping
926 // of already-seen nodes only happens in cases we expect (see below).
927 if !should_process { should_process = true; }
931 let mut hop_use_fee_msat = 0;
932 let mut total_fee_msat = $next_hops_fee_msat;
934 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
935 // will have the same effective-fee
936 if $src_node_id != our_node_id {
937 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
938 // max_value means we'll always fail
939 // the old_entry.total_fee_msat > total_fee_msat check
940 None => total_fee_msat = u64::max_value(),
942 hop_use_fee_msat = fee_msat;
943 total_fee_msat += hop_use_fee_msat;
944 // When calculating the lowest inbound fees to a node, we
945 // calculate fees here not based on the actual value we think
946 // will flow over this channel, but on the minimum value that
947 // we'll accept flowing over it. The minimum accepted value
948 // is a constant through each path collection run, ensuring
949 // consistent basis. Otherwise we may later find a
950 // different path to the source node that is more expensive,
951 // but which we consider to be cheaper because we are capacity
952 // constrained and the relative fee becomes lower.
953 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
954 .map(|a| a.checked_add(total_fee_msat)) {
959 total_fee_msat = u64::max_value();
966 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
967 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
968 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
969 let new_graph_node = RouteGraphNode {
970 node_id: $src_node_id,
971 lowest_fee_to_peer_through_node: total_fee_msat,
972 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
973 total_cltv_delta: hop_total_cltv_delta,
974 value_contribution_msat: value_contribution_msat,
975 path_htlc_minimum_msat,
979 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
980 // if this way is cheaper than the already known
981 // (considering the cost to "reach" this channel from the route destination,
982 // the cost of using this channel,
983 // and the cost of routing to the source node of this channel).
984 // Also, consider that htlc_minimum_msat_difference, because we might end up
985 // paying it. Consider the following exploit:
986 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
987 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
988 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
989 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
991 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
992 // but it may require additional tracking - we don't want to double-count
993 // the fees included in $next_hops_path_htlc_minimum_msat, but also
994 // can't use something that may decrease on future hops.
995 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
996 .checked_add(old_entry.path_penalty_msat)
997 .unwrap_or_else(|| u64::max_value());
998 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
999 .checked_add(path_penalty_msat)
1000 .unwrap_or_else(|| u64::max_value());
1002 if !old_entry.was_processed && new_cost < old_cost {
1003 targets.push(new_graph_node);
1004 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1005 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1006 old_entry.total_fee_msat = total_fee_msat;
1007 old_entry.node_id = $dest_node_id.clone();
1008 old_entry.candidate = $candidate.clone();
1009 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1010 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1011 old_entry.path_penalty_msat = path_penalty_msat;
1012 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1014 old_entry.value_contribution_msat = value_contribution_msat;
1016 did_add_update_path_to_src_node = true;
1017 } else if old_entry.was_processed && new_cost < old_cost {
1018 #[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
1020 // If we're skipping processing a node which was previously
1021 // processed even though we found another path to it with a
1022 // cheaper fee, check that it was because the second path we
1023 // found (which we are processing now) has a lower value
1024 // contribution due to an HTLC minimum limit.
1026 // e.g. take a graph with two paths from node 1 to node 2, one
1027 // through channel A, and one through channel B. Channel A and
1028 // B are both in the to-process heap, with their scores set by
1029 // a higher htlc_minimum than fee.
1030 // Channel A is processed first, and the channels onwards from
1031 // node 1 are added to the to-process heap. Thereafter, we pop
1032 // Channel B off of the heap, note that it has a much more
1033 // restrictive htlc_maximum_msat, and recalculate the fees for
1034 // all of node 1's channels using the new, reduced, amount.
1036 // This would be bogus - we'd be selecting a higher-fee path
1037 // with a lower htlc_maximum_msat instead of the one we'd
1038 // already decided to use.
1039 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1041 value_contribution_msat + path_penalty_msat <
1042 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1050 did_add_update_path_to_src_node
1054 let empty_node_features = NodeFeatures::empty();
1055 // Find ways (channels with destination) to reach a given node and store them
1056 // in the corresponding data structures (routing graph etc).
1057 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1058 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1059 // This data can later be helpful to optimize routing (pay lower fees).
1060 macro_rules! add_entries_to_cheapest_to_target_node {
1061 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => {
1062 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1063 let was_processed = elem.was_processed;
1064 elem.was_processed = true;
1067 // Entries are added to dist in add_entry!() when there is a channel from a node.
1068 // Because there are no channels from payee, it will not have a dist entry at this point.
1069 // If we're processing any other node, it is always be the result of a channel from it.
1070 assert_eq!($node_id, payee_node_id);
1075 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1076 for details in first_channels {
1077 let candidate = CandidateRouteHop::FirstHop { details };
1078 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1082 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1085 &empty_node_features
1088 if !features.requires_unknown_bits() {
1089 for chan_id in $node.channels.iter() {
1090 let chan = network_channels.get(chan_id).unwrap();
1091 if !chan.features.requires_unknown_bits() {
1092 let (directed_channel, source) =
1093 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1094 if first_hops.is_none() || *source != our_node_id {
1095 if let Some(direction) = directed_channel.direction() {
1096 if direction.enabled {
1097 let candidate = CandidateRouteHop::PublicHop {
1098 info: directed_channel.with_update().unwrap(),
1099 short_channel_id: *chan_id,
1101 add_entry!(candidate, *source, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1112 let mut payment_paths = Vec::<PaymentPath>::new();
1114 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1115 'paths_collection: loop {
1116 // For every new path, start from scratch, except
1117 // bookkept_channels_liquidity_available_msat, which will improve
1118 // the further iterations of path finding. Also don't erase first_hop_targets.
1121 hit_minimum_limit = false;
1123 // If first hop is a private channel and the only way to reach the payee, this is the only
1124 // place where it could be added.
1125 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1126 for details in first_channels {
1127 let candidate = CandidateRouteHop::FirstHop { details };
1128 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1129 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1133 // Add the payee as a target, so that the payee-to-payer
1134 // search algorithm knows what to start with.
1135 match network_nodes.get(&payee_node_id) {
1136 // The payee is not in our network graph, so nothing to add here.
1137 // There is still a chance of reaching them via last_hops though,
1138 // so don't yet fail the payment here.
1139 // If not, targets.pop() will not even let us enter the loop in step 2.
1142 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1147 // If a caller provided us with last hops, add them to routing targets. Since this happens
1148 // earlier than general path finding, they will be somewhat prioritized, although currently
1149 // it matters only if the fees are exactly the same.
1150 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1151 let first_hop_in_route = &(route.0)[0];
1152 let have_hop_src_in_graph =
1153 // Only add the hops in this route to our candidate set if either
1154 // we have a direct channel to the first hop or the first hop is
1155 // in the regular network graph.
1156 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1157 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1158 if have_hop_src_in_graph {
1159 // We start building the path from reverse, i.e., from payee
1160 // to the first RouteHintHop in the path.
1161 let hop_iter = route.0.iter().rev();
1162 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1163 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1164 let mut hop_used = true;
1165 let mut aggregate_next_hops_fee_msat: u64 = 0;
1166 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1167 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1168 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1170 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1171 let source = NodeId::from_pubkey(&hop.src_node_id);
1172 let target = NodeId::from_pubkey(&prev_hop_id);
1173 let candidate = network_channels
1174 .get(&hop.short_channel_id)
1175 .and_then(|channel| channel.as_directed_to(&target))
1176 .and_then(|(channel, _)| channel.with_update())
1177 .map(|info| CandidateRouteHop::PublicHop {
1179 short_channel_id: hop.short_channel_id,
1181 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1182 let capacity_msat = candidate.effective_capacity().as_msat();
1183 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1184 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1185 .unwrap_or_else(|| u64::max_value());
1187 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1188 .checked_add(hop.cltv_expiry_delta as u32)
1189 .unwrap_or_else(|| u32::max_value());
1191 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta) {
1192 // If this hop was not used then there is no use checking the preceding hops
1193 // in the RouteHint. We can break by just searching for a direct channel between
1194 // last checked hop and first_hop_targets
1198 // Searching for a direct channel between last checked hop and first_hop_targets
1199 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1200 for details in first_channels {
1201 let candidate = CandidateRouteHop::FirstHop { details };
1202 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1210 // In the next values of the iterator, the aggregate fees already reflects
1211 // the sum of value sent from payer (final_value_msat) and routing fees
1212 // for the last node in the RouteHint. We need to just add the fees to
1213 // route through the current node so that the preceeding node (next iteration)
1215 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1216 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1217 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1219 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1220 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1221 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1222 .checked_add(hop_htlc_minimum_msat_inc);
1223 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1225 if idx == route.0.len() - 1 {
1226 // The last hop in this iterator is the first hop in
1227 // overall RouteHint.
1228 // If this hop connects to a node with which we have a direct channel,
1229 // ignore the network graph and, if the last hop was added, add our
1230 // direct channel to the candidate set.
1232 // Note that we *must* check if the last hop was added as `add_entry`
1233 // always assumes that the third argument is a node to which we have a
1235 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1236 for details in first_channels {
1237 let candidate = CandidateRouteHop::FirstHop { details };
1238 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&hop.src_node_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1246 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1248 // At this point, targets are filled with the data from first and
1249 // last hops communicated by the caller, and the payment receiver.
1250 let mut found_new_path = false;
1253 // If this loop terminates due the exhaustion of targets, two situations are possible:
1254 // - not enough outgoing liquidity:
1255 // 0 < already_collected_value_msat < final_value_msat
1256 // - enough outgoing liquidity:
1257 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1258 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1259 // paths_collection will be stopped because found_new_path==false.
1260 // This is not necessarily a routing failure.
1261 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1263 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1264 // traversing the graph and arrange the path out of what we found.
1265 if node_id == our_node_id {
1266 let mut new_entry = dist.remove(&our_node_id).unwrap();
1267 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1270 let mut features_set = false;
1271 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1272 for details in first_channels {
1273 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1274 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1275 features_set = true;
1281 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1282 if let Some(node_info) = node.announcement_info.as_ref() {
1283 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1285 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1288 // We should be able to fill in features for everything except the last
1289 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1290 // should be able to extend it further as BOLT 11 does have feature
1291 // flags for the last hop node itself).
1292 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1296 // Means we succesfully traversed from the payer to the payee, now
1297 // save this path for the payment route. Also, update the liquidity
1298 // remaining on the used hops, so that we take them into account
1299 // while looking for more paths.
1300 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1304 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1305 Some(payment_hop) => payment_hop,
1306 // We can't arrive at None because, if we ever add an entry to targets,
1307 // we also fill in the entry in dist (see add_entry!).
1308 None => unreachable!(),
1310 // We "propagate" the fees one hop backward (topologically) here,
1311 // so that fees paid for a HTLC forwarding on the current channel are
1312 // associated with the previous channel (where they will be subtracted).
1313 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1314 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1316 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1317 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1319 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1320 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1322 let mut payment_path = PaymentPath {hops: ordered_hops};
1324 // We could have possibly constructed a slightly inconsistent path: since we reduce
1325 // value being transferred along the way, we could have violated htlc_minimum_msat
1326 // on some channels we already passed (assuming dest->source direction). Here, we
1327 // recompute the fees again, so that if that's the case, we match the currently
1328 // underpaid htlc_minimum_msat with fees.
1329 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1331 // Since a path allows to transfer as much value as
1332 // the smallest channel it has ("bottleneck"), we should recompute
1333 // the fees so sender HTLC don't overpay fees when traversing
1334 // larger channels than the bottleneck. This may happen because
1335 // when we were selecting those channels we were not aware how much value
1336 // this path will transfer, and the relative fee for them
1337 // might have been computed considering a larger value.
1338 // Remember that we used these channels so that we don't rely
1339 // on the same liquidity in future paths.
1340 let mut prevented_redundant_path_selection = false;
1341 for (payment_hop, _) in payment_path.hops.iter() {
1342 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1343 let mut spent_on_hop_msat = value_contribution_msat;
1344 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1345 spent_on_hop_msat += next_hops_fee_msat;
1346 if spent_on_hop_msat == *channel_liquidity_available_msat {
1347 // If this path used all of this channel's available liquidity, we know
1348 // this path will not be selected again in the next loop iteration.
1349 prevented_redundant_path_selection = true;
1351 *channel_liquidity_available_msat -= spent_on_hop_msat;
1353 if !prevented_redundant_path_selection {
1354 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1355 // we'll probably end up picking the same path again on the next iteration.
1356 // Decrease the available liquidity of a hop in the middle of the path.
1357 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1358 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1359 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1360 *victim_liquidity = 0;
1363 // Track the total amount all our collected paths allow to send so that we:
1364 // - know when to stop looking for more paths
1365 // - know which of the hops are useless considering how much more sats we need
1366 // (contributes_sufficient_value)
1367 already_collected_value_msat += value_contribution_msat;
1369 payment_paths.push(payment_path);
1370 found_new_path = true;
1371 break 'path_construction;
1374 // If we found a path back to the payee, we shouldn't try to process it again. This is
1375 // the equivalent of the `elem.was_processed` check in
1376 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1377 if node_id == payee_node_id { continue 'path_construction; }
1379 // Otherwise, since the current target node is not us,
1380 // keep "unrolling" the payment graph from payee to payer by
1381 // finding a way to reach the current target from the payer side.
1382 match network_nodes.get(&node_id) {
1385 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, total_cltv_delta);
1391 // If we don't support MPP, no use trying to gather more value ever.
1392 break 'paths_collection;
1396 // Stop either when the recommended value is reached or if no new path was found in this
1398 // In the latter case, making another path finding attempt won't help,
1399 // because we deterministically terminated the search due to low liquidity.
1400 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1401 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1402 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1403 break 'paths_collection;
1404 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1405 // Further, if this was our first walk of the graph, and we weren't limited by an
1406 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1407 // limited by an htlc_minimum_msat value, find another path with a higher value,
1408 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1409 // still keeping a lower total fee than this path.
1410 if !hit_minimum_limit {
1411 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1412 break 'paths_collection;
1414 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1415 path_value_msat = recommended_value_msat;
1420 if payment_paths.len() == 0 {
1421 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1424 if already_collected_value_msat < final_value_msat {
1425 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1428 // Sort by total fees and take the best paths.
1429 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1430 if payment_paths.len() > 50 {
1431 payment_paths.truncate(50);
1434 // Draw multiple sufficient routes by randomly combining the selected paths.
1435 let mut drawn_routes = Vec::new();
1436 for i in 0..payment_paths.len() {
1437 let mut cur_route = Vec::<PaymentPath>::new();
1438 let mut aggregate_route_value_msat = 0;
1441 // TODO: real random shuffle
1442 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1443 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1446 for payment_path in cur_payment_paths {
1447 cur_route.push(payment_path.clone());
1448 aggregate_route_value_msat += payment_path.get_value_msat();
1449 if aggregate_route_value_msat > final_value_msat {
1450 // Last path likely overpaid. Substract it from the most expensive
1451 // (in terms of proportional fee) path in this route and recompute fees.
1452 // This might be not the most economically efficient way, but fewer paths
1453 // also makes routing more reliable.
1454 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1456 // First, drop some expensive low-value paths entirely if possible.
1457 // Sort by value so that we drop many really-low values first, since
1458 // fewer paths is better: the payment is less likely to fail.
1459 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1460 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1461 cur_route.sort_by_key(|path| path.get_value_msat());
1462 // We should make sure that at least 1 path left.
1463 let mut paths_left = cur_route.len();
1464 cur_route.retain(|path| {
1465 if paths_left == 1 {
1468 let mut keep = true;
1469 let path_value_msat = path.get_value_msat();
1470 if path_value_msat <= overpaid_value_msat {
1472 overpaid_value_msat -= path_value_msat;
1478 if overpaid_value_msat == 0 {
1482 assert!(cur_route.len() > 0);
1485 // Now, substract the overpaid value from the most-expensive path.
1486 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1487 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1488 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1489 let expensive_payment_path = cur_route.first_mut().unwrap();
1490 // We already dropped all the small channels above, meaning all the
1491 // remaining channels are larger than remaining overpaid_value_msat.
1492 // Thus, this can't be negative.
1493 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1494 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1498 drawn_routes.push(cur_route);
1502 // Select the best route by lowest total fee.
1503 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1504 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1505 for payment_path in drawn_routes.first().unwrap() {
1506 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1508 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)})?,
1509 node_features: node_features.clone(),
1510 short_channel_id: payment_hop.candidate.short_channel_id(),
1511 channel_features: payment_hop.candidate.features(),
1512 fee_msat: payment_hop.fee_msat,
1513 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1515 }).collect::<Vec<_>>();
1516 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1517 // applicable for the previous hop.
1518 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1519 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1521 selected_paths.push(path);
1524 if let Some(features) = &payment_params.features {
1525 for path in selected_paths.iter_mut() {
1526 if let Ok(route_hop) = path.last_mut().unwrap() {
1527 route_hop.node_features = features.to_context();
1533 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1534 payment_params: Some(payment_params.clone()),
1536 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1542 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters, Score};
1543 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1544 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1545 use chain::transaction::OutPoint;
1546 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1547 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1548 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1549 use ln::channelmanager;
1550 use util::test_utils;
1551 use util::ser::Writeable;
1553 use util::ser::Writer;
1555 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1556 use bitcoin::hashes::Hash;
1557 use bitcoin::network::constants::Network;
1558 use bitcoin::blockdata::constants::genesis_block;
1559 use bitcoin::blockdata::script::Builder;
1560 use bitcoin::blockdata::opcodes;
1561 use bitcoin::blockdata::transaction::TxOut;
1565 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1566 use bitcoin::secp256k1::{Secp256k1, All};
1569 use sync::{self, Arc};
1571 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1572 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1573 channelmanager::ChannelDetails {
1574 channel_id: [0; 32],
1575 counterparty: channelmanager::ChannelCounterparty {
1578 unspendable_punishment_reserve: 0,
1579 forwarding_info: None,
1581 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1583 channel_value_satoshis: 0,
1586 outbound_capacity_msat,
1587 inbound_capacity_msat: 42,
1588 unspendable_punishment_reserve: None,
1589 confirmations_required: None,
1590 force_close_spend_delay: None,
1591 is_outbound: true, is_funding_locked: true,
1592 is_usable: true, is_public: true,
1596 // Using the same keys for LN and BTC ids
1598 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1599 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1601 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1602 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1604 let unsigned_announcement = UnsignedChannelAnnouncement {
1606 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1610 bitcoin_key_1: node_id_1,
1611 bitcoin_key_2: node_id_2,
1612 excess_data: Vec::new(),
1615 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1616 let valid_announcement = ChannelAnnouncement {
1617 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1618 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1619 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1620 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1621 contents: unsigned_announcement.clone(),
1623 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1624 Ok(res) => assert!(res),
1630 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1631 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1633 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1634 let valid_channel_update = ChannelUpdate {
1635 signature: secp_ctx.sign(&msghash, node_privkey),
1636 contents: update.clone()
1639 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1640 Ok(res) => assert!(res),
1645 fn add_or_update_node(
1646 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1647 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1649 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1650 let unsigned_announcement = UnsignedNodeAnnouncement {
1656 addresses: Vec::new(),
1657 excess_address_data: Vec::new(),
1658 excess_data: Vec::new(),
1660 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1661 let valid_announcement = NodeAnnouncement {
1662 signature: secp_ctx.sign(&msghash, node_privkey),
1663 contents: unsigned_announcement.clone()
1666 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1672 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1673 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1674 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1677 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1679 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1680 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1682 (our_privkey, our_id, privkeys, pubkeys)
1685 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1686 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1687 // test for it later.
1688 let idx = (id - 1) * 2 + 1;
1690 vec![1 << (idx - 8*3), 0, 0, 0]
1691 } else if idx > 8*2 {
1692 vec![1 << (idx - 8*2), 0, 0]
1693 } else if idx > 8*1 {
1694 vec![1 << (idx - 8*1), 0]
1700 fn build_graph() -> (
1702 sync::Arc<NetworkGraph>,
1703 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1704 sync::Arc<test_utils::TestChainSource>,
1705 sync::Arc<test_utils::TestLogger>,
1707 let secp_ctx = Secp256k1::new();
1708 let logger = Arc::new(test_utils::TestLogger::new());
1709 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1710 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1711 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1712 // Build network from our_id to node6:
1714 // -1(1)2- node0 -1(3)2-
1716 // our_id -1(12)2- node7 -1(13)2--- node2
1718 // -1(2)2- node1 -1(4)2-
1721 // chan1 1-to-2: disabled
1722 // chan1 2-to-1: enabled, 0 fee
1724 // chan2 1-to-2: enabled, ignored fee
1725 // chan2 2-to-1: enabled, 0 fee
1727 // chan3 1-to-2: enabled, 0 fee
1728 // chan3 2-to-1: enabled, 100 msat fee
1730 // chan4 1-to-2: enabled, 100% fee
1731 // chan4 2-to-1: enabled, 0 fee
1733 // chan12 1-to-2: enabled, ignored fee
1734 // chan12 2-to-1: enabled, 0 fee
1736 // chan13 1-to-2: enabled, 200% fee
1737 // chan13 2-to-1: enabled, 0 fee
1740 // -1(5)2- node3 -1(8)2--
1744 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1746 // -1(7)2- node5 -1(10)2-
1748 // Channels 5, 8, 9 and 10 are private channels.
1750 // chan5 1-to-2: enabled, 100 msat fee
1751 // chan5 2-to-1: enabled, 0 fee
1753 // chan6 1-to-2: enabled, 0 fee
1754 // chan6 2-to-1: enabled, 0 fee
1756 // chan7 1-to-2: enabled, 100% fee
1757 // chan7 2-to-1: enabled, 0 fee
1759 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1760 // chan8 2-to-1: enabled, 0 fee
1762 // chan9 1-to-2: enabled, 1001 msat fee
1763 // chan9 2-to-1: enabled, 0 fee
1765 // chan10 1-to-2: enabled, 0 fee
1766 // chan10 2-to-1: enabled, 0 fee
1768 // chan11 1-to-2: enabled, 0 fee
1769 // chan11 2-to-1: enabled, 0 fee
1771 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1773 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1774 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1776 short_channel_id: 1,
1779 cltv_expiry_delta: 0,
1780 htlc_minimum_msat: 0,
1781 htlc_maximum_msat: OptionalField::Absent,
1783 fee_proportional_millionths: 0,
1784 excess_data: Vec::new()
1787 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1789 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1790 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1792 short_channel_id: 2,
1795 cltv_expiry_delta: (5 << 4) | 3,
1796 htlc_minimum_msat: 0,
1797 htlc_maximum_msat: OptionalField::Absent,
1798 fee_base_msat: u32::max_value(),
1799 fee_proportional_millionths: u32::max_value(),
1800 excess_data: Vec::new()
1802 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1804 short_channel_id: 2,
1807 cltv_expiry_delta: 0,
1808 htlc_minimum_msat: 0,
1809 htlc_maximum_msat: OptionalField::Absent,
1811 fee_proportional_millionths: 0,
1812 excess_data: Vec::new()
1815 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1817 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1818 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1820 short_channel_id: 12,
1823 cltv_expiry_delta: (5 << 4) | 3,
1824 htlc_minimum_msat: 0,
1825 htlc_maximum_msat: OptionalField::Absent,
1826 fee_base_msat: u32::max_value(),
1827 fee_proportional_millionths: u32::max_value(),
1828 excess_data: Vec::new()
1830 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1832 short_channel_id: 12,
1835 cltv_expiry_delta: 0,
1836 htlc_minimum_msat: 0,
1837 htlc_maximum_msat: OptionalField::Absent,
1839 fee_proportional_millionths: 0,
1840 excess_data: Vec::new()
1843 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1845 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1846 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1848 short_channel_id: 3,
1851 cltv_expiry_delta: (3 << 4) | 1,
1852 htlc_minimum_msat: 0,
1853 htlc_maximum_msat: OptionalField::Absent,
1855 fee_proportional_millionths: 0,
1856 excess_data: Vec::new()
1858 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1860 short_channel_id: 3,
1863 cltv_expiry_delta: (3 << 4) | 2,
1864 htlc_minimum_msat: 0,
1865 htlc_maximum_msat: OptionalField::Absent,
1867 fee_proportional_millionths: 0,
1868 excess_data: Vec::new()
1871 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1872 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1873 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1874 short_channel_id: 4,
1877 cltv_expiry_delta: (4 << 4) | 1,
1878 htlc_minimum_msat: 0,
1879 htlc_maximum_msat: OptionalField::Absent,
1881 fee_proportional_millionths: 1000000,
1882 excess_data: Vec::new()
1884 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1885 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1886 short_channel_id: 4,
1889 cltv_expiry_delta: (4 << 4) | 2,
1890 htlc_minimum_msat: 0,
1891 htlc_maximum_msat: OptionalField::Absent,
1893 fee_proportional_millionths: 0,
1894 excess_data: Vec::new()
1897 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1900 short_channel_id: 13,
1903 cltv_expiry_delta: (13 << 4) | 1,
1904 htlc_minimum_msat: 0,
1905 htlc_maximum_msat: OptionalField::Absent,
1907 fee_proportional_millionths: 2000000,
1908 excess_data: Vec::new()
1910 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1912 short_channel_id: 13,
1915 cltv_expiry_delta: (13 << 4) | 2,
1916 htlc_minimum_msat: 0,
1917 htlc_maximum_msat: OptionalField::Absent,
1919 fee_proportional_millionths: 0,
1920 excess_data: Vec::new()
1923 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1925 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1926 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1928 short_channel_id: 6,
1931 cltv_expiry_delta: (6 << 4) | 1,
1932 htlc_minimum_msat: 0,
1933 htlc_maximum_msat: OptionalField::Absent,
1935 fee_proportional_millionths: 0,
1936 excess_data: Vec::new()
1938 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1939 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1940 short_channel_id: 6,
1943 cltv_expiry_delta: (6 << 4) | 2,
1944 htlc_minimum_msat: 0,
1945 htlc_maximum_msat: OptionalField::Absent,
1947 fee_proportional_millionths: 0,
1948 excess_data: Vec::new(),
1951 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1952 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1953 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1954 short_channel_id: 11,
1957 cltv_expiry_delta: (11 << 4) | 1,
1958 htlc_minimum_msat: 0,
1959 htlc_maximum_msat: OptionalField::Absent,
1961 fee_proportional_millionths: 0,
1962 excess_data: Vec::new()
1964 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1966 short_channel_id: 11,
1969 cltv_expiry_delta: (11 << 4) | 2,
1970 htlc_minimum_msat: 0,
1971 htlc_maximum_msat: OptionalField::Absent,
1973 fee_proportional_millionths: 0,
1974 excess_data: Vec::new()
1977 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1979 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1981 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1982 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1984 short_channel_id: 7,
1987 cltv_expiry_delta: (7 << 4) | 1,
1988 htlc_minimum_msat: 0,
1989 htlc_maximum_msat: OptionalField::Absent,
1991 fee_proportional_millionths: 1000000,
1992 excess_data: Vec::new()
1994 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1995 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1996 short_channel_id: 7,
1999 cltv_expiry_delta: (7 << 4) | 2,
2000 htlc_minimum_msat: 0,
2001 htlc_maximum_msat: OptionalField::Absent,
2003 fee_proportional_millionths: 0,
2004 excess_data: Vec::new()
2007 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2009 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2013 fn simple_route_test() {
2014 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2015 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2016 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2017 let scorer = test_utils::TestScorer::with_penalty(0);
2019 // Simple route to 2 via 1
2021 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
2022 assert_eq!(err, "Cannot send a payment of 0 msat");
2023 } else { panic!(); }
2025 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2026 assert_eq!(route.paths[0].len(), 2);
2028 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2029 assert_eq!(route.paths[0][0].short_channel_id, 2);
2030 assert_eq!(route.paths[0][0].fee_msat, 100);
2031 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2032 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2033 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2035 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2036 assert_eq!(route.paths[0][1].short_channel_id, 4);
2037 assert_eq!(route.paths[0][1].fee_msat, 100);
2038 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2039 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2040 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2044 fn invalid_first_hop_test() {
2045 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2046 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2047 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2048 let scorer = test_utils::TestScorer::with_penalty(0);
2050 // Simple route to 2 via 1
2052 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2054 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
2055 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2056 } else { panic!(); }
2058 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2059 assert_eq!(route.paths[0].len(), 2);
2063 fn htlc_minimum_test() {
2064 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2065 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2066 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2067 let scorer = test_utils::TestScorer::with_penalty(0);
2069 // Simple route to 2 via 1
2071 // Disable other paths
2072 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2074 short_channel_id: 12,
2076 flags: 2, // to disable
2077 cltv_expiry_delta: 0,
2078 htlc_minimum_msat: 0,
2079 htlc_maximum_msat: OptionalField::Absent,
2081 fee_proportional_millionths: 0,
2082 excess_data: Vec::new()
2084 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2085 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2086 short_channel_id: 3,
2088 flags: 2, // to disable
2089 cltv_expiry_delta: 0,
2090 htlc_minimum_msat: 0,
2091 htlc_maximum_msat: OptionalField::Absent,
2093 fee_proportional_millionths: 0,
2094 excess_data: Vec::new()
2096 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2097 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2098 short_channel_id: 13,
2100 flags: 2, // to disable
2101 cltv_expiry_delta: 0,
2102 htlc_minimum_msat: 0,
2103 htlc_maximum_msat: OptionalField::Absent,
2105 fee_proportional_millionths: 0,
2106 excess_data: Vec::new()
2108 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2109 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2110 short_channel_id: 6,
2112 flags: 2, // to disable
2113 cltv_expiry_delta: 0,
2114 htlc_minimum_msat: 0,
2115 htlc_maximum_msat: OptionalField::Absent,
2117 fee_proportional_millionths: 0,
2118 excess_data: Vec::new()
2120 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2121 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2122 short_channel_id: 7,
2124 flags: 2, // to disable
2125 cltv_expiry_delta: 0,
2126 htlc_minimum_msat: 0,
2127 htlc_maximum_msat: OptionalField::Absent,
2129 fee_proportional_millionths: 0,
2130 excess_data: Vec::new()
2133 // Check against amount_to_transfer_over_msat.
2134 // Set minimal HTLC of 200_000_000 msat.
2135 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2137 short_channel_id: 2,
2140 cltv_expiry_delta: 0,
2141 htlc_minimum_msat: 200_000_000,
2142 htlc_maximum_msat: OptionalField::Absent,
2144 fee_proportional_millionths: 0,
2145 excess_data: Vec::new()
2148 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2150 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2151 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2152 short_channel_id: 4,
2155 cltv_expiry_delta: 0,
2156 htlc_minimum_msat: 0,
2157 htlc_maximum_msat: OptionalField::Present(199_999_999),
2159 fee_proportional_millionths: 0,
2160 excess_data: Vec::new()
2163 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2164 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2165 assert_eq!(err, "Failed to find a path to the given destination");
2166 } else { panic!(); }
2168 // Lift the restriction on the first hop.
2169 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2170 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2171 short_channel_id: 2,
2174 cltv_expiry_delta: 0,
2175 htlc_minimum_msat: 0,
2176 htlc_maximum_msat: OptionalField::Absent,
2178 fee_proportional_millionths: 0,
2179 excess_data: Vec::new()
2182 // A payment above the minimum should pass
2183 let route = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2184 assert_eq!(route.paths[0].len(), 2);
2188 fn htlc_minimum_overpay_test() {
2189 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2190 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2191 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2192 let scorer = test_utils::TestScorer::with_penalty(0);
2194 // A route to node#2 via two paths.
2195 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2196 // Thus, they can't send 60 without overpaying.
2197 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2199 short_channel_id: 2,
2202 cltv_expiry_delta: 0,
2203 htlc_minimum_msat: 35_000,
2204 htlc_maximum_msat: OptionalField::Present(40_000),
2206 fee_proportional_millionths: 0,
2207 excess_data: Vec::new()
2209 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2210 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2211 short_channel_id: 12,
2214 cltv_expiry_delta: 0,
2215 htlc_minimum_msat: 35_000,
2216 htlc_maximum_msat: OptionalField::Present(40_000),
2218 fee_proportional_millionths: 0,
2219 excess_data: Vec::new()
2223 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2225 short_channel_id: 13,
2228 cltv_expiry_delta: 0,
2229 htlc_minimum_msat: 0,
2230 htlc_maximum_msat: OptionalField::Absent,
2232 fee_proportional_millionths: 0,
2233 excess_data: Vec::new()
2235 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2236 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2237 short_channel_id: 4,
2240 cltv_expiry_delta: 0,
2241 htlc_minimum_msat: 0,
2242 htlc_maximum_msat: OptionalField::Absent,
2244 fee_proportional_millionths: 0,
2245 excess_data: Vec::new()
2248 // Disable other paths
2249 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2251 short_channel_id: 1,
2253 flags: 2, // to disable
2254 cltv_expiry_delta: 0,
2255 htlc_minimum_msat: 0,
2256 htlc_maximum_msat: OptionalField::Absent,
2258 fee_proportional_millionths: 0,
2259 excess_data: Vec::new()
2262 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2263 // Overpay fees to hit htlc_minimum_msat.
2264 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2265 // TODO: this could be better balanced to overpay 10k and not 15k.
2266 assert_eq!(overpaid_fees, 15_000);
2268 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2269 // while taking even more fee to match htlc_minimum_msat.
2270 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2272 short_channel_id: 12,
2275 cltv_expiry_delta: 0,
2276 htlc_minimum_msat: 65_000,
2277 htlc_maximum_msat: OptionalField::Present(80_000),
2279 fee_proportional_millionths: 0,
2280 excess_data: Vec::new()
2282 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2283 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2284 short_channel_id: 2,
2287 cltv_expiry_delta: 0,
2288 htlc_minimum_msat: 0,
2289 htlc_maximum_msat: OptionalField::Absent,
2291 fee_proportional_millionths: 0,
2292 excess_data: Vec::new()
2294 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2295 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2296 short_channel_id: 4,
2299 cltv_expiry_delta: 0,
2300 htlc_minimum_msat: 0,
2301 htlc_maximum_msat: OptionalField::Absent,
2303 fee_proportional_millionths: 100_000,
2304 excess_data: Vec::new()
2307 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2308 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2309 assert_eq!(route.paths.len(), 1);
2310 assert_eq!(route.paths[0][0].short_channel_id, 12);
2311 let fees = route.paths[0][0].fee_msat;
2312 assert_eq!(fees, 5_000);
2314 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2315 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2316 // the other channel.
2317 assert_eq!(route.paths.len(), 1);
2318 assert_eq!(route.paths[0][0].short_channel_id, 2);
2319 let fees = route.paths[0][0].fee_msat;
2320 assert_eq!(fees, 5_000);
2324 fn disable_channels_test() {
2325 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2326 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2327 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2328 let scorer = test_utils::TestScorer::with_penalty(0);
2330 // // Disable channels 4 and 12 by flags=2
2331 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2333 short_channel_id: 4,
2335 flags: 2, // to disable
2336 cltv_expiry_delta: 0,
2337 htlc_minimum_msat: 0,
2338 htlc_maximum_msat: OptionalField::Absent,
2340 fee_proportional_millionths: 0,
2341 excess_data: Vec::new()
2343 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2344 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2345 short_channel_id: 12,
2347 flags: 2, // to disable
2348 cltv_expiry_delta: 0,
2349 htlc_minimum_msat: 0,
2350 htlc_maximum_msat: OptionalField::Absent,
2352 fee_proportional_millionths: 0,
2353 excess_data: Vec::new()
2356 // If all the channels require some features we don't understand, route should fail
2357 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2358 assert_eq!(err, "Failed to find a path to the given destination");
2359 } else { panic!(); }
2361 // If we specify a channel to node7, that overrides our local channel view and that gets used
2362 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2363 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2364 assert_eq!(route.paths[0].len(), 2);
2366 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2367 assert_eq!(route.paths[0][0].short_channel_id, 42);
2368 assert_eq!(route.paths[0][0].fee_msat, 200);
2369 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2370 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2371 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2373 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2374 assert_eq!(route.paths[0][1].short_channel_id, 13);
2375 assert_eq!(route.paths[0][1].fee_msat, 100);
2376 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2377 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2378 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2382 fn disable_node_test() {
2383 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2384 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2385 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2386 let scorer = test_utils::TestScorer::with_penalty(0);
2388 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2389 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2390 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2391 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2392 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2394 // If all nodes require some features we don't understand, route should fail
2395 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2396 assert_eq!(err, "Failed to find a path to the given destination");
2397 } else { panic!(); }
2399 // If we specify a channel to node7, that overrides our local channel view and that gets used
2400 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2401 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2402 assert_eq!(route.paths[0].len(), 2);
2404 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2405 assert_eq!(route.paths[0][0].short_channel_id, 42);
2406 assert_eq!(route.paths[0][0].fee_msat, 200);
2407 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2408 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2409 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2411 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2412 assert_eq!(route.paths[0][1].short_channel_id, 13);
2413 assert_eq!(route.paths[0][1].fee_msat, 100);
2414 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2415 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2416 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2418 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2419 // naively) assume that the user checked the feature bits on the invoice, which override
2420 // the node_announcement.
2424 fn our_chans_test() {
2425 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2426 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2427 let scorer = test_utils::TestScorer::with_penalty(0);
2429 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2430 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2431 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2432 assert_eq!(route.paths[0].len(), 3);
2434 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2435 assert_eq!(route.paths[0][0].short_channel_id, 2);
2436 assert_eq!(route.paths[0][0].fee_msat, 200);
2437 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2438 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2439 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2441 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2442 assert_eq!(route.paths[0][1].short_channel_id, 4);
2443 assert_eq!(route.paths[0][1].fee_msat, 100);
2444 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2445 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2446 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2448 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2449 assert_eq!(route.paths[0][2].short_channel_id, 3);
2450 assert_eq!(route.paths[0][2].fee_msat, 100);
2451 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2452 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2453 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2455 // If we specify a channel to node7, that overrides our local channel view and that gets used
2456 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2457 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2458 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2459 assert_eq!(route.paths[0].len(), 2);
2461 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2462 assert_eq!(route.paths[0][0].short_channel_id, 42);
2463 assert_eq!(route.paths[0][0].fee_msat, 200);
2464 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2465 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2466 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2468 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2469 assert_eq!(route.paths[0][1].short_channel_id, 13);
2470 assert_eq!(route.paths[0][1].fee_msat, 100);
2471 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2472 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2473 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2476 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2477 let zero_fees = RoutingFees {
2479 proportional_millionths: 0,
2481 vec![RouteHint(vec![RouteHintHop {
2482 src_node_id: nodes[3],
2483 short_channel_id: 8,
2485 cltv_expiry_delta: (8 << 4) | 1,
2486 htlc_minimum_msat: None,
2487 htlc_maximum_msat: None,
2489 ]), RouteHint(vec![RouteHintHop {
2490 src_node_id: nodes[4],
2491 short_channel_id: 9,
2494 proportional_millionths: 0,
2496 cltv_expiry_delta: (9 << 4) | 1,
2497 htlc_minimum_msat: None,
2498 htlc_maximum_msat: None,
2499 }]), RouteHint(vec![RouteHintHop {
2500 src_node_id: nodes[5],
2501 short_channel_id: 10,
2503 cltv_expiry_delta: (10 << 4) | 1,
2504 htlc_minimum_msat: None,
2505 htlc_maximum_msat: None,
2509 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2510 let zero_fees = RoutingFees {
2512 proportional_millionths: 0,
2514 vec![RouteHint(vec![RouteHintHop {
2515 src_node_id: nodes[2],
2516 short_channel_id: 5,
2519 proportional_millionths: 0,
2521 cltv_expiry_delta: (5 << 4) | 1,
2522 htlc_minimum_msat: None,
2523 htlc_maximum_msat: None,
2525 src_node_id: nodes[3],
2526 short_channel_id: 8,
2528 cltv_expiry_delta: (8 << 4) | 1,
2529 htlc_minimum_msat: None,
2530 htlc_maximum_msat: None,
2532 ]), RouteHint(vec![RouteHintHop {
2533 src_node_id: nodes[4],
2534 short_channel_id: 9,
2537 proportional_millionths: 0,
2539 cltv_expiry_delta: (9 << 4) | 1,
2540 htlc_minimum_msat: None,
2541 htlc_maximum_msat: None,
2542 }]), RouteHint(vec![RouteHintHop {
2543 src_node_id: nodes[5],
2544 short_channel_id: 10,
2546 cltv_expiry_delta: (10 << 4) | 1,
2547 htlc_minimum_msat: None,
2548 htlc_maximum_msat: None,
2553 fn partial_route_hint_test() {
2554 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2555 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2556 let scorer = test_utils::TestScorer::with_penalty(0);
2558 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2559 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2560 // RouteHint may be partially used by the algo to build the best path.
2562 // First check that last hop can't have its source as the payee.
2563 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2564 src_node_id: nodes[6],
2565 short_channel_id: 8,
2568 proportional_millionths: 0,
2570 cltv_expiry_delta: (8 << 4) | 1,
2571 htlc_minimum_msat: None,
2572 htlc_maximum_msat: None,
2575 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2576 invalid_last_hops.push(invalid_last_hop);
2578 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2579 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2580 assert_eq!(err, "Route hint cannot have the payee as the source.");
2581 } else { panic!(); }
2584 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2585 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2586 assert_eq!(route.paths[0].len(), 5);
2588 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2589 assert_eq!(route.paths[0][0].short_channel_id, 2);
2590 assert_eq!(route.paths[0][0].fee_msat, 100);
2591 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2592 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2593 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2595 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2596 assert_eq!(route.paths[0][1].short_channel_id, 4);
2597 assert_eq!(route.paths[0][1].fee_msat, 0);
2598 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2599 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2600 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2602 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2603 assert_eq!(route.paths[0][2].short_channel_id, 6);
2604 assert_eq!(route.paths[0][2].fee_msat, 0);
2605 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2606 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2607 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2609 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2610 assert_eq!(route.paths[0][3].short_channel_id, 11);
2611 assert_eq!(route.paths[0][3].fee_msat, 0);
2612 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2613 // If we have a peer in the node map, we'll use their features here since we don't have
2614 // a way of figuring out their features from the invoice:
2615 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2616 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2618 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2619 assert_eq!(route.paths[0][4].short_channel_id, 8);
2620 assert_eq!(route.paths[0][4].fee_msat, 100);
2621 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2622 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2623 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2626 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2627 let zero_fees = RoutingFees {
2629 proportional_millionths: 0,
2631 vec![RouteHint(vec![RouteHintHop {
2632 src_node_id: nodes[3],
2633 short_channel_id: 8,
2635 cltv_expiry_delta: (8 << 4) | 1,
2636 htlc_minimum_msat: None,
2637 htlc_maximum_msat: None,
2638 }]), RouteHint(vec![
2640 ]), RouteHint(vec![RouteHintHop {
2641 src_node_id: nodes[5],
2642 short_channel_id: 10,
2644 cltv_expiry_delta: (10 << 4) | 1,
2645 htlc_minimum_msat: None,
2646 htlc_maximum_msat: None,
2651 fn ignores_empty_last_hops_test() {
2652 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2653 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2654 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2655 let scorer = test_utils::TestScorer::with_penalty(0);
2657 // Test handling of an empty RouteHint passed in Invoice.
2659 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2660 assert_eq!(route.paths[0].len(), 5);
2662 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2663 assert_eq!(route.paths[0][0].short_channel_id, 2);
2664 assert_eq!(route.paths[0][0].fee_msat, 100);
2665 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2666 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2667 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2669 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2670 assert_eq!(route.paths[0][1].short_channel_id, 4);
2671 assert_eq!(route.paths[0][1].fee_msat, 0);
2672 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2673 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2674 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2676 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2677 assert_eq!(route.paths[0][2].short_channel_id, 6);
2678 assert_eq!(route.paths[0][2].fee_msat, 0);
2679 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2680 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2681 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2683 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2684 assert_eq!(route.paths[0][3].short_channel_id, 11);
2685 assert_eq!(route.paths[0][3].fee_msat, 0);
2686 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2687 // If we have a peer in the node map, we'll use their features here since we don't have
2688 // a way of figuring out their features from the invoice:
2689 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2690 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2692 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2693 assert_eq!(route.paths[0][4].short_channel_id, 8);
2694 assert_eq!(route.paths[0][4].fee_msat, 100);
2695 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2696 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2697 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2700 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2701 let zero_fees = RoutingFees {
2703 proportional_millionths: 0,
2705 vec![RouteHint(vec![RouteHintHop {
2706 src_node_id: nodes[2],
2707 short_channel_id: 5,
2710 proportional_millionths: 0,
2712 cltv_expiry_delta: (5 << 4) | 1,
2713 htlc_minimum_msat: None,
2714 htlc_maximum_msat: None,
2716 src_node_id: nodes[3],
2717 short_channel_id: 8,
2719 cltv_expiry_delta: (8 << 4) | 1,
2720 htlc_minimum_msat: None,
2721 htlc_maximum_msat: None,
2722 }]), RouteHint(vec![RouteHintHop {
2723 src_node_id: nodes[5],
2724 short_channel_id: 10,
2726 cltv_expiry_delta: (10 << 4) | 1,
2727 htlc_minimum_msat: None,
2728 htlc_maximum_msat: None,
2733 fn multi_hint_last_hops_test() {
2734 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2735 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2736 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2737 let scorer = test_utils::TestScorer::with_penalty(0);
2738 // Test through channels 2, 3, 5, 8.
2739 // Test shows that multiple hop hints are considered.
2741 // Disabling channels 6 & 7 by flags=2
2742 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2743 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2744 short_channel_id: 6,
2746 flags: 2, // to disable
2747 cltv_expiry_delta: 0,
2748 htlc_minimum_msat: 0,
2749 htlc_maximum_msat: OptionalField::Absent,
2751 fee_proportional_millionths: 0,
2752 excess_data: Vec::new()
2754 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2755 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2756 short_channel_id: 7,
2758 flags: 2, // to disable
2759 cltv_expiry_delta: 0,
2760 htlc_minimum_msat: 0,
2761 htlc_maximum_msat: OptionalField::Absent,
2763 fee_proportional_millionths: 0,
2764 excess_data: Vec::new()
2767 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2768 assert_eq!(route.paths[0].len(), 4);
2770 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2771 assert_eq!(route.paths[0][0].short_channel_id, 2);
2772 assert_eq!(route.paths[0][0].fee_msat, 200);
2773 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2774 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2775 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2777 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2778 assert_eq!(route.paths[0][1].short_channel_id, 4);
2779 assert_eq!(route.paths[0][1].fee_msat, 100);
2780 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2781 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2782 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2784 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2785 assert_eq!(route.paths[0][2].short_channel_id, 5);
2786 assert_eq!(route.paths[0][2].fee_msat, 0);
2787 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2788 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2789 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2791 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2792 assert_eq!(route.paths[0][3].short_channel_id, 8);
2793 assert_eq!(route.paths[0][3].fee_msat, 100);
2794 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2795 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2796 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2799 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2800 let zero_fees = RoutingFees {
2802 proportional_millionths: 0,
2804 vec![RouteHint(vec![RouteHintHop {
2805 src_node_id: nodes[4],
2806 short_channel_id: 11,
2808 cltv_expiry_delta: (11 << 4) | 1,
2809 htlc_minimum_msat: None,
2810 htlc_maximum_msat: None,
2812 src_node_id: nodes[3],
2813 short_channel_id: 8,
2815 cltv_expiry_delta: (8 << 4) | 1,
2816 htlc_minimum_msat: None,
2817 htlc_maximum_msat: None,
2818 }]), RouteHint(vec![RouteHintHop {
2819 src_node_id: nodes[4],
2820 short_channel_id: 9,
2823 proportional_millionths: 0,
2825 cltv_expiry_delta: (9 << 4) | 1,
2826 htlc_minimum_msat: None,
2827 htlc_maximum_msat: None,
2828 }]), RouteHint(vec![RouteHintHop {
2829 src_node_id: nodes[5],
2830 short_channel_id: 10,
2832 cltv_expiry_delta: (10 << 4) | 1,
2833 htlc_minimum_msat: None,
2834 htlc_maximum_msat: None,
2839 fn last_hops_with_public_channel_test() {
2840 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2841 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2842 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2843 let scorer = test_utils::TestScorer::with_penalty(0);
2844 // This test shows that public routes can be present in the invoice
2845 // which would be handled in the same manner.
2847 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2848 assert_eq!(route.paths[0].len(), 5);
2850 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2851 assert_eq!(route.paths[0][0].short_channel_id, 2);
2852 assert_eq!(route.paths[0][0].fee_msat, 100);
2853 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2854 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2855 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2857 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2858 assert_eq!(route.paths[0][1].short_channel_id, 4);
2859 assert_eq!(route.paths[0][1].fee_msat, 0);
2860 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2861 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2862 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2864 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2865 assert_eq!(route.paths[0][2].short_channel_id, 6);
2866 assert_eq!(route.paths[0][2].fee_msat, 0);
2867 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2868 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2869 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2871 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2872 assert_eq!(route.paths[0][3].short_channel_id, 11);
2873 assert_eq!(route.paths[0][3].fee_msat, 0);
2874 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2875 // If we have a peer in the node map, we'll use their features here since we don't have
2876 // a way of figuring out their features from the invoice:
2877 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2878 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2880 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2881 assert_eq!(route.paths[0][4].short_channel_id, 8);
2882 assert_eq!(route.paths[0][4].fee_msat, 100);
2883 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2884 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2885 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2889 fn our_chans_last_hop_connect_test() {
2890 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2891 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2892 let scorer = test_utils::TestScorer::with_penalty(0);
2894 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2895 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2896 let mut last_hops = last_hops(&nodes);
2897 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2898 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2899 assert_eq!(route.paths[0].len(), 2);
2901 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2902 assert_eq!(route.paths[0][0].short_channel_id, 42);
2903 assert_eq!(route.paths[0][0].fee_msat, 0);
2904 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2905 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2906 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2908 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2909 assert_eq!(route.paths[0][1].short_channel_id, 8);
2910 assert_eq!(route.paths[0][1].fee_msat, 100);
2911 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2912 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2913 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2915 last_hops[0].0[0].fees.base_msat = 1000;
2917 // Revert to via 6 as the fee on 8 goes up
2918 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
2919 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2920 assert_eq!(route.paths[0].len(), 4);
2922 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2923 assert_eq!(route.paths[0][0].short_channel_id, 2);
2924 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2925 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2926 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2927 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2929 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2930 assert_eq!(route.paths[0][1].short_channel_id, 4);
2931 assert_eq!(route.paths[0][1].fee_msat, 100);
2932 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
2933 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2934 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2936 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2937 assert_eq!(route.paths[0][2].short_channel_id, 7);
2938 assert_eq!(route.paths[0][2].fee_msat, 0);
2939 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
2940 // If we have a peer in the node map, we'll use their features here since we don't have
2941 // a way of figuring out their features from the invoice:
2942 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2943 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2945 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2946 assert_eq!(route.paths[0][3].short_channel_id, 10);
2947 assert_eq!(route.paths[0][3].fee_msat, 100);
2948 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2949 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2950 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2952 // ...but still use 8 for larger payments as 6 has a variable feerate
2953 let route = get_route(&our_id, &payment_params, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2954 assert_eq!(route.paths[0].len(), 5);
2956 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2957 assert_eq!(route.paths[0][0].short_channel_id, 2);
2958 assert_eq!(route.paths[0][0].fee_msat, 3000);
2959 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2960 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2961 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2963 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2964 assert_eq!(route.paths[0][1].short_channel_id, 4);
2965 assert_eq!(route.paths[0][1].fee_msat, 0);
2966 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2967 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2968 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2970 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2971 assert_eq!(route.paths[0][2].short_channel_id, 6);
2972 assert_eq!(route.paths[0][2].fee_msat, 0);
2973 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2974 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2975 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2977 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2978 assert_eq!(route.paths[0][3].short_channel_id, 11);
2979 assert_eq!(route.paths[0][3].fee_msat, 1000);
2980 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2981 // If we have a peer in the node map, we'll use their features here since we don't have
2982 // a way of figuring out their features from the invoice:
2983 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2984 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2986 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2987 assert_eq!(route.paths[0][4].short_channel_id, 8);
2988 assert_eq!(route.paths[0][4].fee_msat, 2000);
2989 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2990 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2991 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2994 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> {
2995 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2996 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2997 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2999 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3000 let last_hops = RouteHint(vec![RouteHintHop {
3001 src_node_id: middle_node_id,
3002 short_channel_id: 8,
3005 proportional_millionths: last_hop_fee_prop,
3007 cltv_expiry_delta: (8 << 4) | 1,
3008 htlc_minimum_msat: None,
3009 htlc_maximum_msat: last_hop_htlc_max,
3011 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3012 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3013 let scorer = test_utils::TestScorer::with_penalty(0);
3014 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer)
3018 fn unannounced_path_test() {
3019 // We should be able to send a payment to a destination without any help of a routing graph
3020 // if we have a channel with a common counterparty that appears in the first and last hop
3022 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3024 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3025 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3026 assert_eq!(route.paths[0].len(), 2);
3028 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3029 assert_eq!(route.paths[0][0].short_channel_id, 42);
3030 assert_eq!(route.paths[0][0].fee_msat, 1001);
3031 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3032 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3033 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3035 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3036 assert_eq!(route.paths[0][1].short_channel_id, 8);
3037 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3038 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3039 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3040 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3044 fn overflow_unannounced_path_test_liquidity_underflow() {
3045 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3046 // the last-hop had a fee which overflowed a u64, we'd panic.
3047 // This was due to us adding the first-hop from us unconditionally, causing us to think
3048 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3049 // In this test, we previously hit a subtraction underflow due to having less available
3050 // liquidity at the last hop than 0.
3051 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());
3055 fn overflow_unannounced_path_test_feerate_overflow() {
3056 // This tests for the same case as above, except instead of hitting a subtraction
3057 // underflow, we hit a case where the fee charged at a hop overflowed.
3058 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());
3062 fn available_amount_while_routing_test() {
3063 // Tests whether we choose the correct available channel amount while routing.
3065 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3066 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3067 let scorer = test_utils::TestScorer::with_penalty(0);
3068 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3070 // We will use a simple single-path route from
3071 // our node to node2 via node0: channels {1, 3}.
3073 // First disable all other paths.
3074 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3076 short_channel_id: 2,
3079 cltv_expiry_delta: 0,
3080 htlc_minimum_msat: 0,
3081 htlc_maximum_msat: OptionalField::Present(100_000),
3083 fee_proportional_millionths: 0,
3084 excess_data: Vec::new()
3086 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3087 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3088 short_channel_id: 12,
3091 cltv_expiry_delta: 0,
3092 htlc_minimum_msat: 0,
3093 htlc_maximum_msat: OptionalField::Present(100_000),
3095 fee_proportional_millionths: 0,
3096 excess_data: Vec::new()
3099 // Make the first channel (#1) very permissive,
3100 // and we will be testing all limits on the second channel.
3101 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3103 short_channel_id: 1,
3106 cltv_expiry_delta: 0,
3107 htlc_minimum_msat: 0,
3108 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3110 fee_proportional_millionths: 0,
3111 excess_data: Vec::new()
3114 // First, let's see if routing works if we have absolutely no idea about the available amount.
3115 // In this case, it should be set to 250_000 sats.
3116 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3118 short_channel_id: 3,
3121 cltv_expiry_delta: 0,
3122 htlc_minimum_msat: 0,
3123 htlc_maximum_msat: OptionalField::Absent,
3125 fee_proportional_millionths: 0,
3126 excess_data: Vec::new()
3130 // Attempt to route more than available results in a failure.
3131 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3132 &our_id, &payment_params, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3133 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3134 } else { panic!(); }
3138 // Now, attempt to route an exact amount we have should be fine.
3139 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3140 assert_eq!(route.paths.len(), 1);
3141 let path = route.paths.last().unwrap();
3142 assert_eq!(path.len(), 2);
3143 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3144 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3147 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3148 // Disable channel #1 and use another first hop.
3149 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3150 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3151 short_channel_id: 1,
3154 cltv_expiry_delta: 0,
3155 htlc_minimum_msat: 0,
3156 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3158 fee_proportional_millionths: 0,
3159 excess_data: Vec::new()
3162 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3163 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3166 // Attempt to route more than available results in a failure.
3167 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3168 &our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3169 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3170 } else { panic!(); }
3174 // Now, attempt to route an exact amount we have should be fine.
3175 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3176 assert_eq!(route.paths.len(), 1);
3177 let path = route.paths.last().unwrap();
3178 assert_eq!(path.len(), 2);
3179 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3180 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3183 // Enable channel #1 back.
3184 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3186 short_channel_id: 1,
3189 cltv_expiry_delta: 0,
3190 htlc_minimum_msat: 0,
3191 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3193 fee_proportional_millionths: 0,
3194 excess_data: Vec::new()
3198 // Now let's see if routing works if we know only htlc_maximum_msat.
3199 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3201 short_channel_id: 3,
3204 cltv_expiry_delta: 0,
3205 htlc_minimum_msat: 0,
3206 htlc_maximum_msat: OptionalField::Present(15_000),
3208 fee_proportional_millionths: 0,
3209 excess_data: Vec::new()
3213 // Attempt to route more than available results in a failure.
3214 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3215 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3216 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3217 } else { panic!(); }
3221 // Now, attempt to route an exact amount we have should be fine.
3222 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3223 assert_eq!(route.paths.len(), 1);
3224 let path = route.paths.last().unwrap();
3225 assert_eq!(path.len(), 2);
3226 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3227 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3230 // Now let's see if routing works if we know only capacity from the UTXO.
3232 // We can't change UTXO capacity on the fly, so we'll disable
3233 // the existing channel and add another one with the capacity we need.
3234 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3236 short_channel_id: 3,
3239 cltv_expiry_delta: 0,
3240 htlc_minimum_msat: 0,
3241 htlc_maximum_msat: OptionalField::Absent,
3243 fee_proportional_millionths: 0,
3244 excess_data: Vec::new()
3247 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3248 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3249 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3250 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3251 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3253 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3254 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3256 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3257 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3259 short_channel_id: 333,
3262 cltv_expiry_delta: (3 << 4) | 1,
3263 htlc_minimum_msat: 0,
3264 htlc_maximum_msat: OptionalField::Absent,
3266 fee_proportional_millionths: 0,
3267 excess_data: Vec::new()
3269 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3271 short_channel_id: 333,
3274 cltv_expiry_delta: (3 << 4) | 2,
3275 htlc_minimum_msat: 0,
3276 htlc_maximum_msat: OptionalField::Absent,
3278 fee_proportional_millionths: 0,
3279 excess_data: Vec::new()
3283 // Attempt to route more than available results in a failure.
3284 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3285 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3286 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3287 } else { panic!(); }
3291 // Now, attempt to route an exact amount we have should be fine.
3292 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3293 assert_eq!(route.paths.len(), 1);
3294 let path = route.paths.last().unwrap();
3295 assert_eq!(path.len(), 2);
3296 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3297 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3300 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3301 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3302 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3303 short_channel_id: 333,
3306 cltv_expiry_delta: 0,
3307 htlc_minimum_msat: 0,
3308 htlc_maximum_msat: OptionalField::Present(10_000),
3310 fee_proportional_millionths: 0,
3311 excess_data: Vec::new()
3315 // Attempt to route more than available results in a failure.
3316 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3317 &our_id, &payment_params, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3318 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3319 } else { panic!(); }
3323 // Now, attempt to route an exact amount we have should be fine.
3324 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3325 assert_eq!(route.paths.len(), 1);
3326 let path = route.paths.last().unwrap();
3327 assert_eq!(path.len(), 2);
3328 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3329 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3334 fn available_liquidity_last_hop_test() {
3335 // Check that available liquidity properly limits the path even when only
3336 // one of the latter hops is limited.
3337 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3338 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3339 let scorer = test_utils::TestScorer::with_penalty(0);
3340 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3342 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3343 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3344 // Total capacity: 50 sats.
3346 // Disable other potential paths.
3347 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3349 short_channel_id: 2,
3352 cltv_expiry_delta: 0,
3353 htlc_minimum_msat: 0,
3354 htlc_maximum_msat: OptionalField::Present(100_000),
3356 fee_proportional_millionths: 0,
3357 excess_data: Vec::new()
3359 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3360 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3361 short_channel_id: 7,
3364 cltv_expiry_delta: 0,
3365 htlc_minimum_msat: 0,
3366 htlc_maximum_msat: OptionalField::Present(100_000),
3368 fee_proportional_millionths: 0,
3369 excess_data: Vec::new()
3374 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3376 short_channel_id: 12,
3379 cltv_expiry_delta: 0,
3380 htlc_minimum_msat: 0,
3381 htlc_maximum_msat: OptionalField::Present(100_000),
3383 fee_proportional_millionths: 0,
3384 excess_data: Vec::new()
3386 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3387 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3388 short_channel_id: 13,
3391 cltv_expiry_delta: 0,
3392 htlc_minimum_msat: 0,
3393 htlc_maximum_msat: OptionalField::Present(100_000),
3395 fee_proportional_millionths: 0,
3396 excess_data: Vec::new()
3399 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3400 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3401 short_channel_id: 6,
3404 cltv_expiry_delta: 0,
3405 htlc_minimum_msat: 0,
3406 htlc_maximum_msat: OptionalField::Present(50_000),
3408 fee_proportional_millionths: 0,
3409 excess_data: Vec::new()
3411 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3412 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3413 short_channel_id: 11,
3416 cltv_expiry_delta: 0,
3417 htlc_minimum_msat: 0,
3418 htlc_maximum_msat: OptionalField::Present(100_000),
3420 fee_proportional_millionths: 0,
3421 excess_data: Vec::new()
3424 // Attempt to route more than available results in a failure.
3425 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3426 &our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3427 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3428 } else { panic!(); }
3432 // Now, attempt to route 49 sats (just a bit below the capacity).
3433 let route = get_route(&our_id, &payment_params, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3434 assert_eq!(route.paths.len(), 1);
3435 let mut total_amount_paid_msat = 0;
3436 for path in &route.paths {
3437 assert_eq!(path.len(), 4);
3438 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3439 total_amount_paid_msat += path.last().unwrap().fee_msat;
3441 assert_eq!(total_amount_paid_msat, 49_000);
3445 // Attempt to route an exact amount is also fine
3446 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3447 assert_eq!(route.paths.len(), 1);
3448 let mut total_amount_paid_msat = 0;
3449 for path in &route.paths {
3450 assert_eq!(path.len(), 4);
3451 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3452 total_amount_paid_msat += path.last().unwrap().fee_msat;
3454 assert_eq!(total_amount_paid_msat, 50_000);
3459 fn ignore_fee_first_hop_test() {
3460 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3461 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3462 let scorer = test_utils::TestScorer::with_penalty(0);
3463 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3465 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3466 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3467 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3468 short_channel_id: 1,
3471 cltv_expiry_delta: 0,
3472 htlc_minimum_msat: 0,
3473 htlc_maximum_msat: OptionalField::Present(100_000),
3474 fee_base_msat: 1_000_000,
3475 fee_proportional_millionths: 0,
3476 excess_data: Vec::new()
3478 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3480 short_channel_id: 3,
3483 cltv_expiry_delta: 0,
3484 htlc_minimum_msat: 0,
3485 htlc_maximum_msat: OptionalField::Present(50_000),
3487 fee_proportional_millionths: 0,
3488 excess_data: Vec::new()
3492 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3493 assert_eq!(route.paths.len(), 1);
3494 let mut total_amount_paid_msat = 0;
3495 for path in &route.paths {
3496 assert_eq!(path.len(), 2);
3497 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3498 total_amount_paid_msat += path.last().unwrap().fee_msat;
3500 assert_eq!(total_amount_paid_msat, 50_000);
3505 fn simple_mpp_route_test() {
3506 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3507 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3508 let scorer = test_utils::TestScorer::with_penalty(0);
3509 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3511 // We need a route consisting of 3 paths:
3512 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3513 // To achieve this, the amount being transferred should be around
3514 // the total capacity of these 3 paths.
3516 // First, we set limits on these (previously unlimited) channels.
3517 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3519 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3520 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3521 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3522 short_channel_id: 1,
3525 cltv_expiry_delta: 0,
3526 htlc_minimum_msat: 0,
3527 htlc_maximum_msat: OptionalField::Present(100_000),
3529 fee_proportional_millionths: 0,
3530 excess_data: Vec::new()
3532 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3533 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3534 short_channel_id: 3,
3537 cltv_expiry_delta: 0,
3538 htlc_minimum_msat: 0,
3539 htlc_maximum_msat: OptionalField::Present(50_000),
3541 fee_proportional_millionths: 0,
3542 excess_data: Vec::new()
3545 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3546 // (total limit 60).
3547 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3548 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3549 short_channel_id: 12,
3552 cltv_expiry_delta: 0,
3553 htlc_minimum_msat: 0,
3554 htlc_maximum_msat: OptionalField::Present(60_000),
3556 fee_proportional_millionths: 0,
3557 excess_data: Vec::new()
3559 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3560 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3561 short_channel_id: 13,
3564 cltv_expiry_delta: 0,
3565 htlc_minimum_msat: 0,
3566 htlc_maximum_msat: OptionalField::Present(60_000),
3568 fee_proportional_millionths: 0,
3569 excess_data: Vec::new()
3572 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3573 // (total capacity 180 sats).
3574 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3576 short_channel_id: 2,
3579 cltv_expiry_delta: 0,
3580 htlc_minimum_msat: 0,
3581 htlc_maximum_msat: OptionalField::Present(200_000),
3583 fee_proportional_millionths: 0,
3584 excess_data: Vec::new()
3586 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3588 short_channel_id: 4,
3591 cltv_expiry_delta: 0,
3592 htlc_minimum_msat: 0,
3593 htlc_maximum_msat: OptionalField::Present(180_000),
3595 fee_proportional_millionths: 0,
3596 excess_data: Vec::new()
3600 // Attempt to route more than available results in a failure.
3601 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3602 &our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3603 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3604 } else { panic!(); }
3608 // Now, attempt to route 250 sats (just a bit below the capacity).
3609 // Our algorithm should provide us with these 3 paths.
3610 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3611 assert_eq!(route.paths.len(), 3);
3612 let mut total_amount_paid_msat = 0;
3613 for path in &route.paths {
3614 assert_eq!(path.len(), 2);
3615 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3616 total_amount_paid_msat += path.last().unwrap().fee_msat;
3618 assert_eq!(total_amount_paid_msat, 250_000);
3622 // Attempt to route an exact amount is also fine
3623 let route = get_route(&our_id, &payment_params, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3624 assert_eq!(route.paths.len(), 3);
3625 let mut total_amount_paid_msat = 0;
3626 for path in &route.paths {
3627 assert_eq!(path.len(), 2);
3628 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3629 total_amount_paid_msat += path.last().unwrap().fee_msat;
3631 assert_eq!(total_amount_paid_msat, 290_000);
3636 fn long_mpp_route_test() {
3637 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3638 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3639 let scorer = test_utils::TestScorer::with_penalty(0);
3640 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3642 // We need a route consisting of 3 paths:
3643 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3644 // Note that these paths overlap (channels 5, 12, 13).
3645 // We will route 300 sats.
3646 // Each path will have 100 sats capacity, those channels which
3647 // are used twice will have 200 sats capacity.
3649 // Disable other potential paths.
3650 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3652 short_channel_id: 2,
3655 cltv_expiry_delta: 0,
3656 htlc_minimum_msat: 0,
3657 htlc_maximum_msat: OptionalField::Present(100_000),
3659 fee_proportional_millionths: 0,
3660 excess_data: Vec::new()
3662 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3663 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3664 short_channel_id: 7,
3667 cltv_expiry_delta: 0,
3668 htlc_minimum_msat: 0,
3669 htlc_maximum_msat: OptionalField::Present(100_000),
3671 fee_proportional_millionths: 0,
3672 excess_data: Vec::new()
3675 // Path via {node0, node2} is channels {1, 3, 5}.
3676 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3677 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3678 short_channel_id: 1,
3681 cltv_expiry_delta: 0,
3682 htlc_minimum_msat: 0,
3683 htlc_maximum_msat: OptionalField::Present(100_000),
3685 fee_proportional_millionths: 0,
3686 excess_data: Vec::new()
3688 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3689 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3690 short_channel_id: 3,
3693 cltv_expiry_delta: 0,
3694 htlc_minimum_msat: 0,
3695 htlc_maximum_msat: OptionalField::Present(100_000),
3697 fee_proportional_millionths: 0,
3698 excess_data: Vec::new()
3701 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3702 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3703 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3705 short_channel_id: 5,
3708 cltv_expiry_delta: 0,
3709 htlc_minimum_msat: 0,
3710 htlc_maximum_msat: OptionalField::Present(200_000),
3712 fee_proportional_millionths: 0,
3713 excess_data: Vec::new()
3716 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3717 // Add 100 sats to the capacities of {12, 13}, because these channels
3718 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3719 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3720 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3721 short_channel_id: 12,
3724 cltv_expiry_delta: 0,
3725 htlc_minimum_msat: 0,
3726 htlc_maximum_msat: OptionalField::Present(200_000),
3728 fee_proportional_millionths: 0,
3729 excess_data: Vec::new()
3731 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3732 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3733 short_channel_id: 13,
3736 cltv_expiry_delta: 0,
3737 htlc_minimum_msat: 0,
3738 htlc_maximum_msat: OptionalField::Present(200_000),
3740 fee_proportional_millionths: 0,
3741 excess_data: Vec::new()
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 6,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: OptionalField::Present(100_000),
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3756 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3758 short_channel_id: 11,
3761 cltv_expiry_delta: 0,
3762 htlc_minimum_msat: 0,
3763 htlc_maximum_msat: OptionalField::Present(100_000),
3765 fee_proportional_millionths: 0,
3766 excess_data: Vec::new()
3769 // Path via {node7, node2} is channels {12, 13, 5}.
3770 // We already limited them to 200 sats (they are used twice for 100 sats).
3771 // Nothing to do here.
3774 // Attempt to route more than available results in a failure.
3775 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3776 &our_id, &payment_params, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3777 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3778 } else { panic!(); }
3782 // Now, attempt to route 300 sats (exact amount we can route).
3783 // Our algorithm should provide us with these 3 paths, 100 sats each.
3784 let route = get_route(&our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3785 assert_eq!(route.paths.len(), 3);
3787 let mut total_amount_paid_msat = 0;
3788 for path in &route.paths {
3789 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3790 total_amount_paid_msat += path.last().unwrap().fee_msat;
3792 assert_eq!(total_amount_paid_msat, 300_000);
3798 fn mpp_cheaper_route_test() {
3799 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3800 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3801 let scorer = test_utils::TestScorer::with_penalty(0);
3802 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3804 // This test checks that if we have two cheaper paths and one more expensive path,
3805 // so that liquidity-wise any 2 of 3 combination is sufficient,
3806 // two cheaper paths will be taken.
3807 // These paths have equal available liquidity.
3809 // We need a combination of 3 paths:
3810 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3811 // Note that these paths overlap (channels 5, 12, 13).
3812 // Each path will have 100 sats capacity, those channels which
3813 // are used twice will have 200 sats capacity.
3815 // Disable other potential paths.
3816 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3818 short_channel_id: 2,
3821 cltv_expiry_delta: 0,
3822 htlc_minimum_msat: 0,
3823 htlc_maximum_msat: OptionalField::Present(100_000),
3825 fee_proportional_millionths: 0,
3826 excess_data: Vec::new()
3828 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3829 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3830 short_channel_id: 7,
3833 cltv_expiry_delta: 0,
3834 htlc_minimum_msat: 0,
3835 htlc_maximum_msat: OptionalField::Present(100_000),
3837 fee_proportional_millionths: 0,
3838 excess_data: Vec::new()
3841 // Path via {node0, node2} is channels {1, 3, 5}.
3842 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3844 short_channel_id: 1,
3847 cltv_expiry_delta: 0,
3848 htlc_minimum_msat: 0,
3849 htlc_maximum_msat: OptionalField::Present(100_000),
3851 fee_proportional_millionths: 0,
3852 excess_data: Vec::new()
3854 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3856 short_channel_id: 3,
3859 cltv_expiry_delta: 0,
3860 htlc_minimum_msat: 0,
3861 htlc_maximum_msat: OptionalField::Present(100_000),
3863 fee_proportional_millionths: 0,
3864 excess_data: Vec::new()
3867 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3868 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3869 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3870 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3871 short_channel_id: 5,
3874 cltv_expiry_delta: 0,
3875 htlc_minimum_msat: 0,
3876 htlc_maximum_msat: OptionalField::Present(200_000),
3878 fee_proportional_millionths: 0,
3879 excess_data: Vec::new()
3882 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3883 // Add 100 sats to the capacities of {12, 13}, because these channels
3884 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3885 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3886 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3887 short_channel_id: 12,
3890 cltv_expiry_delta: 0,
3891 htlc_minimum_msat: 0,
3892 htlc_maximum_msat: OptionalField::Present(200_000),
3894 fee_proportional_millionths: 0,
3895 excess_data: Vec::new()
3897 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3899 short_channel_id: 13,
3902 cltv_expiry_delta: 0,
3903 htlc_minimum_msat: 0,
3904 htlc_maximum_msat: OptionalField::Present(200_000),
3906 fee_proportional_millionths: 0,
3907 excess_data: Vec::new()
3910 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3912 short_channel_id: 6,
3915 cltv_expiry_delta: 0,
3916 htlc_minimum_msat: 0,
3917 htlc_maximum_msat: OptionalField::Present(100_000),
3918 fee_base_msat: 1_000,
3919 fee_proportional_millionths: 0,
3920 excess_data: Vec::new()
3922 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3924 short_channel_id: 11,
3927 cltv_expiry_delta: 0,
3928 htlc_minimum_msat: 0,
3929 htlc_maximum_msat: OptionalField::Present(100_000),
3931 fee_proportional_millionths: 0,
3932 excess_data: Vec::new()
3935 // Path via {node7, node2} is channels {12, 13, 5}.
3936 // We already limited them to 200 sats (they are used twice for 100 sats).
3937 // Nothing to do here.
3940 // Now, attempt to route 180 sats.
3941 // Our algorithm should provide us with these 2 paths.
3942 let route = get_route(&our_id, &payment_params, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3943 assert_eq!(route.paths.len(), 2);
3945 let mut total_value_transferred_msat = 0;
3946 let mut total_paid_msat = 0;
3947 for path in &route.paths {
3948 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3949 total_value_transferred_msat += path.last().unwrap().fee_msat;
3951 total_paid_msat += hop.fee_msat;
3954 // If we paid fee, this would be higher.
3955 assert_eq!(total_value_transferred_msat, 180_000);
3956 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3957 assert_eq!(total_fees_paid, 0);
3962 fn fees_on_mpp_route_test() {
3963 // This test makes sure that MPP algorithm properly takes into account
3964 // fees charged on the channels, by making the fees impactful:
3965 // if the fee is not properly accounted for, the behavior is different.
3966 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3967 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3968 let scorer = test_utils::TestScorer::with_penalty(0);
3969 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3971 // We need a route consisting of 2 paths:
3972 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3973 // We will route 200 sats, Each path will have 100 sats capacity.
3975 // This test is not particularly stable: e.g.,
3976 // there's a way to route via {node0, node2, node4}.
3977 // It works while pathfinding is deterministic, but can be broken otherwise.
3978 // It's fine to ignore this concern for now.
3980 // Disable other potential paths.
3981 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3982 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3983 short_channel_id: 2,
3986 cltv_expiry_delta: 0,
3987 htlc_minimum_msat: 0,
3988 htlc_maximum_msat: OptionalField::Present(100_000),
3990 fee_proportional_millionths: 0,
3991 excess_data: Vec::new()
3994 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3995 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3996 short_channel_id: 7,
3999 cltv_expiry_delta: 0,
4000 htlc_minimum_msat: 0,
4001 htlc_maximum_msat: OptionalField::Present(100_000),
4003 fee_proportional_millionths: 0,
4004 excess_data: Vec::new()
4007 // Path via {node0, node2} is channels {1, 3, 5}.
4008 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4009 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4010 short_channel_id: 1,
4013 cltv_expiry_delta: 0,
4014 htlc_minimum_msat: 0,
4015 htlc_maximum_msat: OptionalField::Present(100_000),
4017 fee_proportional_millionths: 0,
4018 excess_data: Vec::new()
4020 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4022 short_channel_id: 3,
4025 cltv_expiry_delta: 0,
4026 htlc_minimum_msat: 0,
4027 htlc_maximum_msat: OptionalField::Present(100_000),
4029 fee_proportional_millionths: 0,
4030 excess_data: Vec::new()
4033 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4034 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4036 short_channel_id: 5,
4039 cltv_expiry_delta: 0,
4040 htlc_minimum_msat: 0,
4041 htlc_maximum_msat: OptionalField::Present(100_000),
4043 fee_proportional_millionths: 0,
4044 excess_data: Vec::new()
4047 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4048 // All channels should be 100 sats capacity. But for the fee experiment,
4049 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4050 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4051 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4052 // so no matter how large are other channels,
4053 // the whole path will be limited by 100 sats with just these 2 conditions:
4054 // - channel 12 capacity is 250 sats
4055 // - fee for channel 6 is 150 sats
4056 // Let's test this by enforcing these 2 conditions and removing other limits.
4057 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4059 short_channel_id: 12,
4062 cltv_expiry_delta: 0,
4063 htlc_minimum_msat: 0,
4064 htlc_maximum_msat: OptionalField::Present(250_000),
4066 fee_proportional_millionths: 0,
4067 excess_data: Vec::new()
4069 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4071 short_channel_id: 13,
4074 cltv_expiry_delta: 0,
4075 htlc_minimum_msat: 0,
4076 htlc_maximum_msat: OptionalField::Absent,
4078 fee_proportional_millionths: 0,
4079 excess_data: Vec::new()
4082 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4084 short_channel_id: 6,
4087 cltv_expiry_delta: 0,
4088 htlc_minimum_msat: 0,
4089 htlc_maximum_msat: OptionalField::Absent,
4090 fee_base_msat: 150_000,
4091 fee_proportional_millionths: 0,
4092 excess_data: Vec::new()
4094 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4095 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4096 short_channel_id: 11,
4099 cltv_expiry_delta: 0,
4100 htlc_minimum_msat: 0,
4101 htlc_maximum_msat: OptionalField::Absent,
4103 fee_proportional_millionths: 0,
4104 excess_data: Vec::new()
4108 // Attempt to route more than available results in a failure.
4109 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4110 &our_id, &payment_params, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4111 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4112 } else { panic!(); }
4116 // Now, attempt to route 200 sats (exact amount we can route).
4117 let route = get_route(&our_id, &payment_params, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4118 assert_eq!(route.paths.len(), 2);
4120 let mut total_amount_paid_msat = 0;
4121 for path in &route.paths {
4122 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4123 total_amount_paid_msat += path.last().unwrap().fee_msat;
4125 assert_eq!(total_amount_paid_msat, 200_000);
4126 assert_eq!(route.get_total_fees(), 150_000);
4131 fn mpp_with_last_hops() {
4132 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4133 // via a single last-hop route hint, we'd fail to route if we first collected routes
4134 // totaling close but not quite enough to fund the full payment.
4136 // This was because we considered last-hop hints to have exactly the sought payment amount
4137 // instead of the amount we were trying to collect, needlessly limiting our path searching
4138 // at the very first hop.
4140 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4141 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4142 // to only have the remaining to-collect amount in available liquidity.
4144 // This bug appeared in production in some specific channel configurations.
4145 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4146 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4147 let scorer = test_utils::TestScorer::with_penalty(0);
4148 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4149 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4150 src_node_id: nodes[2],
4151 short_channel_id: 42,
4152 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4153 cltv_expiry_delta: 42,
4154 htlc_minimum_msat: None,
4155 htlc_maximum_msat: None,
4158 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4159 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4160 // would first use the no-fee route and then fail to find a path along the second route as
4161 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4162 // under 5% of our payment amount.
4163 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4165 short_channel_id: 1,
4168 cltv_expiry_delta: (5 << 4) | 5,
4169 htlc_minimum_msat: 0,
4170 htlc_maximum_msat: OptionalField::Present(99_000),
4171 fee_base_msat: u32::max_value(),
4172 fee_proportional_millionths: u32::max_value(),
4173 excess_data: Vec::new()
4175 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4177 short_channel_id: 2,
4180 cltv_expiry_delta: (5 << 4) | 3,
4181 htlc_minimum_msat: 0,
4182 htlc_maximum_msat: OptionalField::Present(99_000),
4183 fee_base_msat: u32::max_value(),
4184 fee_proportional_millionths: u32::max_value(),
4185 excess_data: Vec::new()
4187 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4188 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4189 short_channel_id: 4,
4192 cltv_expiry_delta: (4 << 4) | 1,
4193 htlc_minimum_msat: 0,
4194 htlc_maximum_msat: OptionalField::Absent,
4196 fee_proportional_millionths: 0,
4197 excess_data: Vec::new()
4199 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4201 short_channel_id: 13,
4203 flags: 0|2, // Channel disabled
4204 cltv_expiry_delta: (13 << 4) | 1,
4205 htlc_minimum_msat: 0,
4206 htlc_maximum_msat: OptionalField::Absent,
4208 fee_proportional_millionths: 2000000,
4209 excess_data: Vec::new()
4212 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4214 let route = get_route(&our_id, &payment_params, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4215 assert_eq!(route.paths.len(), 2);
4216 // Paths are somewhat randomly ordered, but:
4217 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4218 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4219 assert_eq!(route.paths[0][0].short_channel_id, 2);
4220 assert_eq!(route.paths[0][0].fee_msat, 1);
4221 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4222 assert_eq!(route.paths[1][0].short_channel_id, 1);
4223 assert_eq!(route.paths[1][0].fee_msat, 0);
4224 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4225 assert_eq!(route.get_total_fees(), 1);
4226 assert_eq!(route.get_total_amount(), 100_000);
4230 fn drop_lowest_channel_mpp_route_test() {
4231 // This test checks that low-capacity channel is dropped when after
4232 // path finding we realize that we found more capacity than we need.
4233 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4234 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4235 let scorer = test_utils::TestScorer::with_penalty(0);
4236 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4238 // We need a route consisting of 3 paths:
4239 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4241 // The first and the second paths should be sufficient, but the third should be
4242 // cheaper, so that we select it but drop later.
4244 // First, we set limits on these (previously unlimited) channels.
4245 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4247 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4248 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4250 short_channel_id: 1,
4253 cltv_expiry_delta: 0,
4254 htlc_minimum_msat: 0,
4255 htlc_maximum_msat: OptionalField::Present(100_000),
4257 fee_proportional_millionths: 0,
4258 excess_data: Vec::new()
4260 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4261 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4262 short_channel_id: 3,
4265 cltv_expiry_delta: 0,
4266 htlc_minimum_msat: 0,
4267 htlc_maximum_msat: OptionalField::Present(50_000),
4269 fee_proportional_millionths: 0,
4270 excess_data: Vec::new()
4273 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4274 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4276 short_channel_id: 12,
4279 cltv_expiry_delta: 0,
4280 htlc_minimum_msat: 0,
4281 htlc_maximum_msat: OptionalField::Present(60_000),
4283 fee_proportional_millionths: 0,
4284 excess_data: Vec::new()
4286 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4288 short_channel_id: 13,
4291 cltv_expiry_delta: 0,
4292 htlc_minimum_msat: 0,
4293 htlc_maximum_msat: OptionalField::Present(60_000),
4295 fee_proportional_millionths: 0,
4296 excess_data: Vec::new()
4299 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4300 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4302 short_channel_id: 2,
4305 cltv_expiry_delta: 0,
4306 htlc_minimum_msat: 0,
4307 htlc_maximum_msat: OptionalField::Present(20_000),
4309 fee_proportional_millionths: 0,
4310 excess_data: Vec::new()
4312 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4314 short_channel_id: 4,
4317 cltv_expiry_delta: 0,
4318 htlc_minimum_msat: 0,
4319 htlc_maximum_msat: OptionalField::Present(20_000),
4321 fee_proportional_millionths: 0,
4322 excess_data: Vec::new()
4326 // Attempt to route more than available results in a failure.
4327 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4328 &our_id, &payment_params, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4329 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4330 } else { panic!(); }
4334 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4335 // Our algorithm should provide us with these 3 paths.
4336 let route = get_route(&our_id, &payment_params, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4337 assert_eq!(route.paths.len(), 3);
4338 let mut total_amount_paid_msat = 0;
4339 for path in &route.paths {
4340 assert_eq!(path.len(), 2);
4341 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4342 total_amount_paid_msat += path.last().unwrap().fee_msat;
4344 assert_eq!(total_amount_paid_msat, 125_000);
4348 // Attempt to route without the last small cheap channel
4349 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4350 assert_eq!(route.paths.len(), 2);
4351 let mut total_amount_paid_msat = 0;
4352 for path in &route.paths {
4353 assert_eq!(path.len(), 2);
4354 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4355 total_amount_paid_msat += path.last().unwrap().fee_msat;
4357 assert_eq!(total_amount_paid_msat, 90_000);
4362 fn min_criteria_consistency() {
4363 // Test that we don't use an inconsistent metric between updating and walking nodes during
4364 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4365 // was updated with a different criterion from the heap sorting, resulting in loops in
4366 // calculated paths. We test for that specific case here.
4368 // We construct a network that looks like this:
4370 // node2 -1(3)2- node3
4374 // node1 -1(5)2- node4 -1(1)2- node6
4380 // We create a loop on the side of our real path - our destination is node 6, with a
4381 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4382 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4383 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4384 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4385 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4386 // "previous hop" being set to node 3, creating a loop in the path.
4387 let secp_ctx = Secp256k1::new();
4388 let logger = Arc::new(test_utils::TestLogger::new());
4389 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4390 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4391 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4392 let scorer = test_utils::TestScorer::with_penalty(0);
4393 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4395 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4396 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4398 short_channel_id: 6,
4401 cltv_expiry_delta: (6 << 4) | 0,
4402 htlc_minimum_msat: 0,
4403 htlc_maximum_msat: OptionalField::Absent,
4405 fee_proportional_millionths: 0,
4406 excess_data: Vec::new()
4408 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4410 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4411 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4412 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4413 short_channel_id: 5,
4416 cltv_expiry_delta: (5 << 4) | 0,
4417 htlc_minimum_msat: 0,
4418 htlc_maximum_msat: OptionalField::Absent,
4420 fee_proportional_millionths: 0,
4421 excess_data: Vec::new()
4423 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4425 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4426 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4428 short_channel_id: 4,
4431 cltv_expiry_delta: (4 << 4) | 0,
4432 htlc_minimum_msat: 0,
4433 htlc_maximum_msat: OptionalField::Absent,
4435 fee_proportional_millionths: 0,
4436 excess_data: Vec::new()
4438 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4440 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4441 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4442 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4443 short_channel_id: 3,
4446 cltv_expiry_delta: (3 << 4) | 0,
4447 htlc_minimum_msat: 0,
4448 htlc_maximum_msat: OptionalField::Absent,
4450 fee_proportional_millionths: 0,
4451 excess_data: Vec::new()
4453 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4455 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4456 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4458 short_channel_id: 2,
4461 cltv_expiry_delta: (2 << 4) | 0,
4462 htlc_minimum_msat: 0,
4463 htlc_maximum_msat: OptionalField::Absent,
4465 fee_proportional_millionths: 0,
4466 excess_data: Vec::new()
4469 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4470 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4471 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4472 short_channel_id: 1,
4475 cltv_expiry_delta: (1 << 4) | 0,
4476 htlc_minimum_msat: 100,
4477 htlc_maximum_msat: OptionalField::Absent,
4479 fee_proportional_millionths: 0,
4480 excess_data: Vec::new()
4482 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4485 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4486 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4487 assert_eq!(route.paths.len(), 1);
4488 assert_eq!(route.paths[0].len(), 3);
4490 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4491 assert_eq!(route.paths[0][0].short_channel_id, 6);
4492 assert_eq!(route.paths[0][0].fee_msat, 100);
4493 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4494 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4495 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4497 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4498 assert_eq!(route.paths[0][1].short_channel_id, 5);
4499 assert_eq!(route.paths[0][1].fee_msat, 0);
4500 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4501 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4502 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4504 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4505 assert_eq!(route.paths[0][2].short_channel_id, 1);
4506 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4507 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4508 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4509 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4515 fn exact_fee_liquidity_limit() {
4516 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4517 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4518 // we calculated fees on a higher value, resulting in us ignoring such paths.
4519 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4520 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4521 let scorer = test_utils::TestScorer::with_penalty(0);
4522 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4524 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4526 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4528 short_channel_id: 2,
4531 cltv_expiry_delta: 0,
4532 htlc_minimum_msat: 0,
4533 htlc_maximum_msat: OptionalField::Present(85_000),
4535 fee_proportional_millionths: 0,
4536 excess_data: Vec::new()
4539 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4541 short_channel_id: 12,
4544 cltv_expiry_delta: (4 << 4) | 1,
4545 htlc_minimum_msat: 0,
4546 htlc_maximum_msat: OptionalField::Present(270_000),
4548 fee_proportional_millionths: 1000000,
4549 excess_data: Vec::new()
4553 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4554 // 200% fee charged channel 13 in the 1-to-2 direction.
4555 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4556 assert_eq!(route.paths.len(), 1);
4557 assert_eq!(route.paths[0].len(), 2);
4559 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4560 assert_eq!(route.paths[0][0].short_channel_id, 12);
4561 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4562 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4563 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4564 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4566 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4567 assert_eq!(route.paths[0][1].short_channel_id, 13);
4568 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4569 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4570 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4571 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4576 fn htlc_max_reduction_below_min() {
4577 // Test that if, while walking the graph, we reduce the value being sent to meet an
4578 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4579 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4580 // resulting in us thinking there is no possible path, even if other paths exist.
4581 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4582 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4583 let scorer = test_utils::TestScorer::with_penalty(0);
4584 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4586 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4587 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4588 // then try to send 90_000.
4589 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4591 short_channel_id: 2,
4594 cltv_expiry_delta: 0,
4595 htlc_minimum_msat: 0,
4596 htlc_maximum_msat: OptionalField::Present(80_000),
4598 fee_proportional_millionths: 0,
4599 excess_data: Vec::new()
4601 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4602 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4603 short_channel_id: 4,
4606 cltv_expiry_delta: (4 << 4) | 1,
4607 htlc_minimum_msat: 90_000,
4608 htlc_maximum_msat: OptionalField::Absent,
4610 fee_proportional_millionths: 0,
4611 excess_data: Vec::new()
4615 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4616 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4617 // expensive) channels 12-13 path.
4618 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4619 assert_eq!(route.paths.len(), 1);
4620 assert_eq!(route.paths[0].len(), 2);
4622 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4623 assert_eq!(route.paths[0][0].short_channel_id, 12);
4624 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4625 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4626 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4627 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4629 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4630 assert_eq!(route.paths[0][1].short_channel_id, 13);
4631 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4632 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4633 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4634 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4639 fn multiple_direct_first_hops() {
4640 // Previously we'd only ever considered one first hop path per counterparty.
4641 // However, as we don't restrict users to one channel per peer, we really need to support
4642 // looking at all first hop paths.
4643 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4644 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4645 // route over multiple channels with the same first hop.
4646 let secp_ctx = Secp256k1::new();
4647 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4648 let logger = Arc::new(test_utils::TestLogger::new());
4649 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4650 let scorer = test_utils::TestScorer::with_penalty(0);
4651 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4654 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4655 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4656 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4657 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4658 assert_eq!(route.paths.len(), 1);
4659 assert_eq!(route.paths[0].len(), 1);
4661 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4662 assert_eq!(route.paths[0][0].short_channel_id, 3);
4663 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4666 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4667 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4668 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4669 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4670 assert_eq!(route.paths.len(), 2);
4671 assert_eq!(route.paths[0].len(), 1);
4672 assert_eq!(route.paths[1].len(), 1);
4674 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4675 assert_eq!(route.paths[0][0].short_channel_id, 3);
4676 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4678 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4679 assert_eq!(route.paths[1][0].short_channel_id, 2);
4680 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4685 fn prefers_shorter_route_with_higher_fees() {
4686 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4687 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4688 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4690 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4691 let scorer = test_utils::TestScorer::with_penalty(0);
4692 let route = get_route(
4693 &our_id, &payment_params, &network_graph, None, 100, 42,
4694 Arc::clone(&logger), &scorer
4696 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4698 assert_eq!(route.get_total_fees(), 100);
4699 assert_eq!(route.get_total_amount(), 100);
4700 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4702 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4703 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4704 let scorer = test_utils::TestScorer::with_penalty(100);
4705 let route = get_route(
4706 &our_id, &payment_params, &network_graph, None, 100, 42,
4707 Arc::clone(&logger), &scorer
4709 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4711 assert_eq!(route.get_total_fees(), 300);
4712 assert_eq!(route.get_total_amount(), 100);
4713 assert_eq!(path, vec![2, 4, 7, 10]);
4716 struct BadChannelScorer {
4717 short_channel_id: u64,
4721 impl Writeable for BadChannelScorer {
4722 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4724 impl Score for BadChannelScorer {
4725 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4726 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4729 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4730 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4733 struct BadNodeScorer {
4738 impl Writeable for BadNodeScorer {
4739 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4742 impl Score for BadNodeScorer {
4743 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4744 if *target == self.node_id { u64::max_value() } else { 0 }
4747 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4748 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4752 fn avoids_routing_through_bad_channels_and_nodes() {
4753 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4754 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4755 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4757 // A path to nodes[6] exists when no penalties are applied to any channel.
4758 let scorer = test_utils::TestScorer::with_penalty(0);
4759 let route = get_route(
4760 &our_id, &payment_params, &network_graph, None, 100, 42,
4761 Arc::clone(&logger), &scorer
4763 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4765 assert_eq!(route.get_total_fees(), 100);
4766 assert_eq!(route.get_total_amount(), 100);
4767 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4769 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4770 let scorer = BadChannelScorer { short_channel_id: 6 };
4771 let route = get_route(
4772 &our_id, &payment_params, &network_graph, None, 100, 42,
4773 Arc::clone(&logger), &scorer
4775 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4777 assert_eq!(route.get_total_fees(), 300);
4778 assert_eq!(route.get_total_amount(), 100);
4779 assert_eq!(path, vec![2, 4, 7, 10]);
4781 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4782 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4784 &our_id, &payment_params, &network_graph, None, 100, 42,
4785 Arc::clone(&logger), &scorer
4787 Err(LightningError { err, .. } ) => {
4788 assert_eq!(err, "Failed to find a path to the given destination");
4790 Ok(_) => panic!("Expected error"),
4795 fn total_fees_single_path() {
4799 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4800 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4801 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4804 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4805 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4806 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4809 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4810 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4811 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4814 payment_params: None,
4817 assert_eq!(route.get_total_fees(), 250);
4818 assert_eq!(route.get_total_amount(), 225);
4822 fn total_fees_multi_path() {
4826 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4827 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4828 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4831 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4832 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4833 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4837 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4838 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4839 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4842 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4843 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4844 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4847 payment_params: None,
4850 assert_eq!(route.get_total_fees(), 200);
4851 assert_eq!(route.get_total_amount(), 300);
4855 fn total_empty_route_no_panic() {
4856 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4857 // would both panic if the route was completely empty. We test to ensure they return 0
4858 // here, even though its somewhat nonsensical as a route.
4859 let route = Route { paths: Vec::new(), payment_params: None };
4861 assert_eq!(route.get_total_fees(), 0);
4862 assert_eq!(route.get_total_amount(), 0);
4866 fn limits_total_cltv_delta() {
4867 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4868 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4870 let scorer = test_utils::TestScorer::with_penalty(0);
4872 // Make sure that generally there is at least one route available
4873 let feasible_max_total_cltv_delta = 1008;
4874 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4875 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
4876 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
4877 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4878 assert_ne!(path.len(), 0);
4880 // But not if we exclude all paths on the basis of their accumulated CLTV delta
4881 let fail_max_total_cltv_delta = 23;
4882 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4883 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
4884 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer)
4886 Err(LightningError { err, .. } ) => {
4887 assert_eq!(err, "Failed to find a path to the given destination");
4889 Ok(_) => panic!("Expected error"),
4893 #[cfg(not(feature = "no-std"))]
4894 pub(super) fn random_init_seed() -> u64 {
4895 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4896 use core::hash::{BuildHasher, Hasher};
4897 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4898 println!("Using seed of {}", seed);
4901 #[cfg(not(feature = "no-std"))]
4902 use util::ser::Readable;
4905 #[cfg(not(feature = "no-std"))]
4906 fn generate_routes() {
4907 let mut d = match super::test_utils::get_route_file() {
4914 let graph = NetworkGraph::read(&mut d).unwrap();
4916 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4917 let mut seed = random_init_seed() as usize;
4918 let nodes = graph.read_only().nodes().clone();
4919 'load_endpoints: for _ in 0..10 {
4921 seed = seed.overflowing_mul(0xdeadbeef).0;
4922 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4923 seed = seed.overflowing_mul(0xdeadbeef).0;
4924 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4925 let payment_params = PaymentParameters::from_node_id(dst);
4926 let amt = seed as u64 % 200_000_000;
4927 let params = ProbabilisticScoringParameters::default();
4928 let scorer = ProbabilisticScorer::new(params, &graph);
4929 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4930 continue 'load_endpoints;
4937 #[cfg(not(feature = "no-std"))]
4938 fn generate_routes_mpp() {
4939 let mut d = match super::test_utils::get_route_file() {
4946 let graph = NetworkGraph::read(&mut d).unwrap();
4948 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4949 let mut seed = random_init_seed() as usize;
4950 let nodes = graph.read_only().nodes().clone();
4951 'load_endpoints: for _ in 0..10 {
4953 seed = seed.overflowing_mul(0xdeadbeef).0;
4954 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4955 seed = seed.overflowing_mul(0xdeadbeef).0;
4956 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4957 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
4958 let amt = seed as u64 % 200_000_000;
4959 let params = ProbabilisticScoringParameters::default();
4960 let scorer = ProbabilisticScorer::new(params, &graph);
4961 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4962 continue 'load_endpoints;
4969 #[cfg(all(test, not(feature = "no-std")))]
4970 pub(crate) mod test_utils {
4972 /// Tries to open a network graph file, or panics with a URL to fetch it.
4973 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4974 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4975 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4976 .or_else(|_| { // Fall back to guessing based on the binary location
4977 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4978 let mut path = std::env::current_exe().unwrap();
4979 path.pop(); // lightning-...
4981 path.pop(); // debug
4982 path.pop(); // target
4983 path.push("lightning");
4984 path.push("net_graph-2021-05-31.bin");
4985 eprintln!("{}", path.to_str().unwrap());
4988 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.15-2021-05-31.bin and place it at lightning/net_graph-2021-05-31.bin");
4989 #[cfg(require_route_graph_test)]
4990 return Ok(res.unwrap());
4991 #[cfg(not(require_route_graph_test))]
4996 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
4999 use bitcoin::hashes::Hash;
5000 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5001 use chain::transaction::OutPoint;
5002 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5003 use ln::features::{InitFeatures, InvoiceFeatures};
5004 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5005 use util::logger::{Logger, Record};
5009 struct DummyLogger {}
5010 impl Logger for DummyLogger {
5011 fn log(&self, _record: &Record) {}
5014 fn read_network_graph() -> NetworkGraph {
5015 let mut d = test_utils::get_route_file().unwrap();
5016 NetworkGraph::read(&mut d).unwrap()
5019 fn payer_pubkey() -> PublicKey {
5020 let secp_ctx = Secp256k1::new();
5021 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5025 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5027 channel_id: [0; 32],
5028 counterparty: ChannelCounterparty {
5029 features: InitFeatures::known(),
5031 unspendable_punishment_reserve: 0,
5032 forwarding_info: None,
5034 funding_txo: Some(OutPoint {
5035 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5037 short_channel_id: Some(1),
5038 channel_value_satoshis: 10_000_000,
5040 balance_msat: 10_000_000,
5041 outbound_capacity_msat: 10_000_000,
5042 inbound_capacity_msat: 0,
5043 unspendable_punishment_reserve: None,
5044 confirmations_required: None,
5045 force_close_spend_delay: None,
5047 is_funding_locked: true,
5054 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5055 let network_graph = read_network_graph();
5056 let scorer = FixedPenaltyScorer::with_penalty(0);
5057 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5061 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5062 let network_graph = read_network_graph();
5063 let scorer = FixedPenaltyScorer::with_penalty(0);
5064 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5068 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5069 let network_graph = read_network_graph();
5070 let scorer = Scorer::default();
5071 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5075 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5076 let network_graph = read_network_graph();
5077 let scorer = Scorer::default();
5078 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5082 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5083 let network_graph = read_network_graph();
5084 let params = ProbabilisticScoringParameters::default();
5085 let scorer = ProbabilisticScorer::new(params, &network_graph);
5086 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5090 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5091 let network_graph = read_network_graph();
5092 let params = ProbabilisticScoringParameters::default();
5093 let scorer = ProbabilisticScorer::new(params, &network_graph);
5094 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5097 fn generate_routes<S: Score>(
5098 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5100 let nodes = graph.read_only().nodes().clone();
5101 let payer = payer_pubkey();
5103 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5104 let mut routes = Vec::new();
5105 let mut route_endpoints = Vec::new();
5106 let mut seed: usize = 0xdeadbeef;
5107 'load_endpoints: for _ in 0..100 {
5110 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5112 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5113 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5114 let first_hop = first_hop(src);
5115 let amt = seed as u64 % 1_000_000;
5116 if let Ok(route) = get_route(&payer, ¶ms, &graph, Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer) {
5118 route_endpoints.push((first_hop, params, amt));
5119 continue 'load_endpoints;
5124 // ...and seed the scorer with success and failure data...
5125 for route in routes {
5126 let amount = route.get_total_amount();
5127 if amount < 250_000 {
5128 for path in route.paths {
5129 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5131 } else if amount > 750_000 {
5132 for path in route.paths {
5133 let short_channel_id = path[path.len() / 2].short_channel_id;
5134 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5139 // ...then benchmark finding paths between the nodes we learned.
5142 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5143 assert!(get_route(&payer, params, &graph, Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer).is_ok());