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(any(test, feature = "fuzztarget"))]
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", our_node_pubkey,
739 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" });
742 // Prepare the data we'll use for payee-to-payer search by
743 // inserting first hops suggested by the caller as targets.
744 // Our search will then attempt to reach them while traversing from the payee node.
745 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
746 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
747 if let Some(hops) = first_hops {
749 if chan.short_channel_id.is_none() {
750 panic!("first_hops should be filled in with usable channels, not pending ones");
752 if chan.counterparty.node_id == *our_node_pubkey {
753 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
756 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
757 .or_insert(Vec::new())
760 if first_hop_targets.is_empty() {
761 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
765 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
766 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
767 // adding duplicate entries when we find a better path to a given node.
768 let mut targets = BinaryHeap::new();
770 // Map from node_id to information about the best current path to that node, including feerate
772 let mut dist = HashMap::with_capacity(network_nodes.len());
774 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
775 // indicating that we may wish to try again with a higher value, potentially paying to meet an
776 // htlc_minimum with extra fees while still finding a cheaper path.
777 let mut hit_minimum_limit;
779 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
780 // We start with a path_value of the exact amount we want, and if that generates a route we may
781 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
782 // amount we want in total across paths, selecting the best subset at the end.
783 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
784 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
785 let mut path_value_msat = final_value_msat;
787 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
788 // This map allows paths to be aware of the channel use by other paths in the same call.
789 // This would help to make a better path finding decisions and not "overbook" channels.
790 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
791 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
793 // Keeping track of how much value we already collected across other paths. Helps to decide:
794 // - how much a new path should be transferring (upper bound);
795 // - whether a channel should be disregarded because
796 // it's available liquidity is too small comparing to how much more we need to collect;
797 // - when we want to stop looking for new paths.
798 let mut already_collected_value_msat = 0;
800 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
802 macro_rules! add_entry {
803 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
804 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
805 // since that value has to be transferred over this channel.
806 // Returns whether this channel caused an update to `targets`.
807 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
808 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
809 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
810 // We "return" whether we updated the path at the end, via this:
811 let mut did_add_update_path_to_src_node = false;
812 // Channels to self should not be used. This is more of belt-and-suspenders, because in
813 // practice these cases should be caught earlier:
814 // - for regular channels at channel announcement (TODO)
815 // - for first and last hops early in get_route
816 if $src_node_id != $dest_node_id {
817 let short_channel_id = $candidate.short_channel_id();
818 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
819 .entry(short_channel_id)
820 .or_insert_with(|| $candidate.effective_capacity().as_msat());
822 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
823 // It may be misleading because we might later choose to reduce the value transferred
824 // over these channels, and the channel which was insufficient might become sufficient.
825 // Worst case: we drop a good channel here because it can't cover the high following
826 // fees caused by one expensive channel, but then this channel could have been used
827 // if the amount being transferred over this path is lower.
828 // We do this for now, but this is a subject for removal.
829 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
831 // Routing Fragmentation Mitigation heuristic:
833 // Routing fragmentation across many payment paths increases the overall routing
834 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
835 // Taking too many smaller paths also increases the chance of payment failure.
836 // Thus to avoid this effect, we require from our collected links to provide
837 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
839 // This requirement is currently 5% of the remaining-to-be-collected value.
840 // This means as we successfully advance in our collection,
841 // the absolute liquidity contribution is lowered,
842 // thus increasing the number of potential channels to be selected.
844 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
845 // or 100% if we're not allowed to do multipath payments.
846 let minimal_value_contribution_msat: u64 = if allow_mpp {
847 (recommended_value_msat - already_collected_value_msat + 19) / 20
851 // Verify the liquidity offered by this channel complies to the minimal contribution.
852 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
854 // Do not consider candidates that exceed the maximum total cltv expiry limit.
855 let max_total_cltv_expiry_delta = payment_params.max_total_cltv_expiry_delta;
856 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
857 .checked_add($candidate.cltv_expiry_delta())
858 .unwrap_or(u32::max_value());
859 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
861 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
862 // Includes paying fees for the use of the following channels.
863 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
864 Some(result) => result,
865 // Can't overflow due to how the values were computed right above.
866 None => unreachable!(),
868 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
869 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
870 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
872 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
873 // bother considering this channel.
874 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
875 // be only reduced later (not increased), so this channel should just be skipped
876 // as not sufficient.
877 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
878 hit_minimum_limit = true;
879 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
880 // Note that low contribution here (limited by available_liquidity_msat)
881 // might violate htlc_minimum_msat on the hops which are next along the
882 // payment path (upstream to the payee). To avoid that, we recompute
883 // path fees knowing the final path contribution after constructing it.
884 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
885 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
886 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
887 .unwrap_or_else(|| u64::max_value());
888 let hm_entry = dist.entry($src_node_id);
889 let old_entry = hm_entry.or_insert_with(|| {
890 // If there was previously no known way to access the source node
891 // (recall it goes payee-to-payer) of short_channel_id, first add a
892 // semi-dummy record just to compute the fees to reach the source node.
893 // This will affect our decision on selecting short_channel_id
894 // as a way to reach the $dest_node_id.
895 let mut fee_base_msat = u32::max_value();
896 let mut fee_proportional_millionths = u32::max_value();
897 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
898 fee_base_msat = fees.base_msat;
899 fee_proportional_millionths = fees.proportional_millionths;
902 node_id: $dest_node_id.clone(),
903 candidate: $candidate.clone(),
905 src_lowest_inbound_fees: RoutingFees {
906 base_msat: fee_base_msat,
907 proportional_millionths: fee_proportional_millionths,
909 next_hops_fee_msat: u64::max_value(),
910 hop_use_fee_msat: u64::max_value(),
911 total_fee_msat: u64::max_value(),
912 path_htlc_minimum_msat,
913 path_penalty_msat: u64::max_value(),
914 was_processed: false,
915 #[cfg(any(test, feature = "fuzztarget"))]
916 value_contribution_msat,
920 #[allow(unused_mut)] // We only use the mut in cfg(test)
921 let mut should_process = !old_entry.was_processed;
922 #[cfg(any(test, feature = "fuzztarget"))]
924 // In test/fuzzing builds, we do extra checks to make sure the skipping
925 // of already-seen nodes only happens in cases we expect (see below).
926 if !should_process { should_process = true; }
930 let mut hop_use_fee_msat = 0;
931 let mut total_fee_msat = $next_hops_fee_msat;
933 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
934 // will have the same effective-fee
935 if $src_node_id != our_node_id {
936 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
937 // max_value means we'll always fail
938 // the old_entry.total_fee_msat > total_fee_msat check
939 None => total_fee_msat = u64::max_value(),
941 hop_use_fee_msat = fee_msat;
942 total_fee_msat += hop_use_fee_msat;
943 // When calculating the lowest inbound fees to a node, we
944 // calculate fees here not based on the actual value we think
945 // will flow over this channel, but on the minimum value that
946 // we'll accept flowing over it. The minimum accepted value
947 // is a constant through each path collection run, ensuring
948 // consistent basis. Otherwise we may later find a
949 // different path to the source node that is more expensive,
950 // but which we consider to be cheaper because we are capacity
951 // constrained and the relative fee becomes lower.
952 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
953 .map(|a| a.checked_add(total_fee_msat)) {
958 total_fee_msat = u64::max_value();
965 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
966 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
967 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
968 let new_graph_node = RouteGraphNode {
969 node_id: $src_node_id,
970 lowest_fee_to_peer_through_node: total_fee_msat,
971 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
972 total_cltv_delta: hop_total_cltv_delta,
973 value_contribution_msat: value_contribution_msat,
974 path_htlc_minimum_msat,
978 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
979 // if this way is cheaper than the already known
980 // (considering the cost to "reach" this channel from the route destination,
981 // the cost of using this channel,
982 // and the cost of routing to the source node of this channel).
983 // Also, consider that htlc_minimum_msat_difference, because we might end up
984 // paying it. Consider the following exploit:
985 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
986 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
987 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
988 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
990 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
991 // but it may require additional tracking - we don't want to double-count
992 // the fees included in $next_hops_path_htlc_minimum_msat, but also
993 // can't use something that may decrease on future hops.
994 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
995 .checked_add(old_entry.path_penalty_msat)
996 .unwrap_or_else(|| u64::max_value());
997 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
998 .checked_add(path_penalty_msat)
999 .unwrap_or_else(|| u64::max_value());
1001 if !old_entry.was_processed && new_cost < old_cost {
1002 targets.push(new_graph_node);
1003 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1004 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1005 old_entry.total_fee_msat = total_fee_msat;
1006 old_entry.node_id = $dest_node_id.clone();
1007 old_entry.candidate = $candidate.clone();
1008 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1009 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1010 old_entry.path_penalty_msat = path_penalty_msat;
1011 #[cfg(any(test, feature = "fuzztarget"))]
1013 old_entry.value_contribution_msat = value_contribution_msat;
1015 did_add_update_path_to_src_node = true;
1016 } else if old_entry.was_processed && new_cost < old_cost {
1017 #[cfg(any(test, feature = "fuzztarget"))]
1019 // If we're skipping processing a node which was previously
1020 // processed even though we found another path to it with a
1021 // cheaper fee, check that it was because the second path we
1022 // found (which we are processing now) has a lower value
1023 // contribution due to an HTLC minimum limit.
1025 // e.g. take a graph with two paths from node 1 to node 2, one
1026 // through channel A, and one through channel B. Channel A and
1027 // B are both in the to-process heap, with their scores set by
1028 // a higher htlc_minimum than fee.
1029 // Channel A is processed first, and the channels onwards from
1030 // node 1 are added to the to-process heap. Thereafter, we pop
1031 // Channel B off of the heap, note that it has a much more
1032 // restrictive htlc_maximum_msat, and recalculate the fees for
1033 // all of node 1's channels using the new, reduced, amount.
1035 // This would be bogus - we'd be selecting a higher-fee path
1036 // with a lower htlc_maximum_msat instead of the one we'd
1037 // already decided to use.
1038 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1040 value_contribution_msat + path_penalty_msat <
1041 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1049 did_add_update_path_to_src_node
1053 let empty_node_features = NodeFeatures::empty();
1054 // Find ways (channels with destination) to reach a given node and store them
1055 // in the corresponding data structures (routing graph etc).
1056 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1057 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1058 // This data can later be helpful to optimize routing (pay lower fees).
1059 macro_rules! add_entries_to_cheapest_to_target_node {
1060 ( $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 ) => {
1061 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1062 let was_processed = elem.was_processed;
1063 elem.was_processed = true;
1066 // Entries are added to dist in add_entry!() when there is a channel from a node.
1067 // Because there are no channels from payee, it will not have a dist entry at this point.
1068 // If we're processing any other node, it is always be the result of a channel from it.
1069 assert_eq!($node_id, payee_node_id);
1074 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1075 for details in first_channels {
1076 let candidate = CandidateRouteHop::FirstHop { details };
1077 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);
1081 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1084 &empty_node_features
1087 if !features.requires_unknown_bits() {
1088 for chan_id in $node.channels.iter() {
1089 let chan = network_channels.get(chan_id).unwrap();
1090 if !chan.features.requires_unknown_bits() {
1091 let (directed_channel, source) =
1092 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1093 if first_hops.is_none() || *source != our_node_id {
1094 if let Some(direction) = directed_channel.direction() {
1095 if direction.enabled {
1096 let candidate = CandidateRouteHop::PublicHop {
1097 info: directed_channel.with_update().unwrap(),
1098 short_channel_id: *chan_id,
1100 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);
1111 let mut payment_paths = Vec::<PaymentPath>::new();
1113 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1114 'paths_collection: loop {
1115 // For every new path, start from scratch, except
1116 // bookkept_channels_liquidity_available_msat, which will improve
1117 // the further iterations of path finding. Also don't erase first_hop_targets.
1120 hit_minimum_limit = false;
1122 // If first hop is a private channel and the only way to reach the payee, this is the only
1123 // place where it could be added.
1124 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1125 for details in first_channels {
1126 let candidate = CandidateRouteHop::FirstHop { details };
1127 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1128 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1132 // Add the payee as a target, so that the payee-to-payer
1133 // search algorithm knows what to start with.
1134 match network_nodes.get(&payee_node_id) {
1135 // The payee is not in our network graph, so nothing to add here.
1136 // There is still a chance of reaching them via last_hops though,
1137 // so don't yet fail the payment here.
1138 // If not, targets.pop() will not even let us enter the loop in step 2.
1141 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1146 // If a caller provided us with last hops, add them to routing targets. Since this happens
1147 // earlier than general path finding, they will be somewhat prioritized, although currently
1148 // it matters only if the fees are exactly the same.
1149 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1150 let first_hop_in_route = &(route.0)[0];
1151 let have_hop_src_in_graph =
1152 // Only add the hops in this route to our candidate set if either
1153 // we have a direct channel to the first hop or the first hop is
1154 // in the regular network graph.
1155 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1156 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1157 if have_hop_src_in_graph {
1158 // We start building the path from reverse, i.e., from payee
1159 // to the first RouteHintHop in the path.
1160 let hop_iter = route.0.iter().rev();
1161 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1162 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1163 let mut hop_used = true;
1164 let mut aggregate_next_hops_fee_msat: u64 = 0;
1165 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1166 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1167 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1169 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1170 let source = NodeId::from_pubkey(&hop.src_node_id);
1171 let target = NodeId::from_pubkey(&prev_hop_id);
1172 let candidate = network_channels
1173 .get(&hop.short_channel_id)
1174 .and_then(|channel| channel.as_directed_to(&target))
1175 .and_then(|(channel, _)| channel.with_update())
1176 .map(|info| CandidateRouteHop::PublicHop {
1178 short_channel_id: hop.short_channel_id,
1180 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1181 let capacity_msat = candidate.effective_capacity().as_msat();
1182 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1183 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1184 .unwrap_or_else(|| u64::max_value());
1186 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1187 .checked_add(hop.cltv_expiry_delta as u32)
1188 .unwrap_or_else(|| u32::max_value());
1190 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) {
1191 // If this hop was not used then there is no use checking the preceding hops
1192 // in the RouteHint. We can break by just searching for a direct channel between
1193 // last checked hop and first_hop_targets
1197 // Searching for a direct channel between last checked hop and first_hop_targets
1198 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1199 for details in first_channels {
1200 let candidate = CandidateRouteHop::FirstHop { details };
1201 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);
1209 // In the next values of the iterator, the aggregate fees already reflects
1210 // the sum of value sent from payer (final_value_msat) and routing fees
1211 // for the last node in the RouteHint. We need to just add the fees to
1212 // route through the current node so that the preceeding node (next iteration)
1214 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1215 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1216 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1218 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1219 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1220 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1221 .checked_add(hop_htlc_minimum_msat_inc);
1222 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1224 if idx == route.0.len() - 1 {
1225 // The last hop in this iterator is the first hop in
1226 // overall RouteHint.
1227 // If this hop connects to a node with which we have a direct channel,
1228 // ignore the network graph and, if the last hop was added, add our
1229 // direct channel to the candidate set.
1231 // Note that we *must* check if the last hop was added as `add_entry`
1232 // always assumes that the third argument is a node to which we have a
1234 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1235 for details in first_channels {
1236 let candidate = CandidateRouteHop::FirstHop { details };
1237 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);
1245 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1247 // At this point, targets are filled with the data from first and
1248 // last hops communicated by the caller, and the payment receiver.
1249 let mut found_new_path = false;
1252 // If this loop terminates due the exhaustion of targets, two situations are possible:
1253 // - not enough outgoing liquidity:
1254 // 0 < already_collected_value_msat < final_value_msat
1255 // - enough outgoing liquidity:
1256 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1257 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1258 // paths_collection will be stopped because found_new_path==false.
1259 // This is not necessarily a routing failure.
1260 '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() {
1262 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1263 // traversing the graph and arrange the path out of what we found.
1264 if node_id == our_node_id {
1265 let mut new_entry = dist.remove(&our_node_id).unwrap();
1266 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1269 let mut features_set = false;
1270 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1271 for details in first_channels {
1272 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1273 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1274 features_set = true;
1280 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1281 if let Some(node_info) = node.announcement_info.as_ref() {
1282 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1284 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1287 // We should be able to fill in features for everything except the last
1288 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1289 // should be able to extend it further as BOLT 11 does have feature
1290 // flags for the last hop node itself).
1291 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1295 // Means we succesfully traversed from the payer to the payee, now
1296 // save this path for the payment route. Also, update the liquidity
1297 // remaining on the used hops, so that we take them into account
1298 // while looking for more paths.
1299 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1303 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1304 Some(payment_hop) => payment_hop,
1305 // We can't arrive at None because, if we ever add an entry to targets,
1306 // we also fill in the entry in dist (see add_entry!).
1307 None => unreachable!(),
1309 // We "propagate" the fees one hop backward (topologically) here,
1310 // so that fees paid for a HTLC forwarding on the current channel are
1311 // associated with the previous channel (where they will be subtracted).
1312 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1313 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1315 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1316 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1318 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
1319 ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
1321 let mut payment_path = PaymentPath {hops: ordered_hops};
1323 // We could have possibly constructed a slightly inconsistent path: since we reduce
1324 // value being transferred along the way, we could have violated htlc_minimum_msat
1325 // on some channels we already passed (assuming dest->source direction). Here, we
1326 // recompute the fees again, so that if that's the case, we match the currently
1327 // underpaid htlc_minimum_msat with fees.
1328 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1330 // Since a path allows to transfer as much value as
1331 // the smallest channel it has ("bottleneck"), we should recompute
1332 // the fees so sender HTLC don't overpay fees when traversing
1333 // larger channels than the bottleneck. This may happen because
1334 // when we were selecting those channels we were not aware how much value
1335 // this path will transfer, and the relative fee for them
1336 // might have been computed considering a larger value.
1337 // Remember that we used these channels so that we don't rely
1338 // on the same liquidity in future paths.
1339 let mut prevented_redundant_path_selection = false;
1340 for (payment_hop, _) in payment_path.hops.iter() {
1341 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1342 let mut spent_on_hop_msat = value_contribution_msat;
1343 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1344 spent_on_hop_msat += next_hops_fee_msat;
1345 if spent_on_hop_msat == *channel_liquidity_available_msat {
1346 // If this path used all of this channel's available liquidity, we know
1347 // this path will not be selected again in the next loop iteration.
1348 prevented_redundant_path_selection = true;
1350 *channel_liquidity_available_msat -= spent_on_hop_msat;
1352 if !prevented_redundant_path_selection {
1353 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1354 // we'll probably end up picking the same path again on the next iteration.
1355 // Decrease the available liquidity of a hop in the middle of the path.
1356 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1357 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1358 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1359 *victim_liquidity = 0;
1362 // Track the total amount all our collected paths allow to send so that we:
1363 // - know when to stop looking for more paths
1364 // - know which of the hops are useless considering how much more sats we need
1365 // (contributes_sufficient_value)
1366 already_collected_value_msat += value_contribution_msat;
1368 payment_paths.push(payment_path);
1369 found_new_path = true;
1370 break 'path_construction;
1373 // If we found a path back to the payee, we shouldn't try to process it again. This is
1374 // the equivalent of the `elem.was_processed` check in
1375 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1376 if node_id == payee_node_id { continue 'path_construction; }
1378 // Otherwise, since the current target node is not us,
1379 // keep "unrolling" the payment graph from payee to payer by
1380 // finding a way to reach the current target from the payer side.
1381 match network_nodes.get(&node_id) {
1384 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);
1390 // If we don't support MPP, no use trying to gather more value ever.
1391 break 'paths_collection;
1395 // Stop either when the recommended value is reached or if no new path was found in this
1397 // In the latter case, making another path finding attempt won't help,
1398 // because we deterministically terminated the search due to low liquidity.
1399 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1400 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1401 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1402 break 'paths_collection;
1403 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1404 // Further, if this was our first walk of the graph, and we weren't limited by an
1405 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1406 // limited by an htlc_minimum_msat value, find another path with a higher value,
1407 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1408 // still keeping a lower total fee than this path.
1409 if !hit_minimum_limit {
1410 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1411 break 'paths_collection;
1413 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1414 path_value_msat = recommended_value_msat;
1419 if payment_paths.len() == 0 {
1420 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1423 if already_collected_value_msat < final_value_msat {
1424 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1427 // Sort by total fees and take the best paths.
1428 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1429 if payment_paths.len() > 50 {
1430 payment_paths.truncate(50);
1433 // Draw multiple sufficient routes by randomly combining the selected paths.
1434 let mut drawn_routes = Vec::new();
1435 for i in 0..payment_paths.len() {
1436 let mut cur_route = Vec::<PaymentPath>::new();
1437 let mut aggregate_route_value_msat = 0;
1440 // TODO: real random shuffle
1441 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1442 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1445 for payment_path in cur_payment_paths {
1446 cur_route.push(payment_path.clone());
1447 aggregate_route_value_msat += payment_path.get_value_msat();
1448 if aggregate_route_value_msat > final_value_msat {
1449 // Last path likely overpaid. Substract it from the most expensive
1450 // (in terms of proportional fee) path in this route and recompute fees.
1451 // This might be not the most economically efficient way, but fewer paths
1452 // also makes routing more reliable.
1453 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1455 // First, drop some expensive low-value paths entirely if possible.
1456 // Sort by value so that we drop many really-low values first, since
1457 // fewer paths is better: the payment is less likely to fail.
1458 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1459 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1460 cur_route.sort_by_key(|path| path.get_value_msat());
1461 // We should make sure that at least 1 path left.
1462 let mut paths_left = cur_route.len();
1463 cur_route.retain(|path| {
1464 if paths_left == 1 {
1467 let mut keep = true;
1468 let path_value_msat = path.get_value_msat();
1469 if path_value_msat <= overpaid_value_msat {
1471 overpaid_value_msat -= path_value_msat;
1477 if overpaid_value_msat == 0 {
1481 assert!(cur_route.len() > 0);
1484 // Now, substract the overpaid value from the most-expensive path.
1485 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1486 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1487 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1488 let expensive_payment_path = cur_route.first_mut().unwrap();
1489 // We already dropped all the small channels above, meaning all the
1490 // remaining channels are larger than remaining overpaid_value_msat.
1491 // Thus, this can't be negative.
1492 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1493 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1497 drawn_routes.push(cur_route);
1501 // Select the best route by lowest total fee.
1502 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1503 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1504 for payment_path in drawn_routes.first().unwrap() {
1505 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1507 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)})?,
1508 node_features: node_features.clone(),
1509 short_channel_id: payment_hop.candidate.short_channel_id(),
1510 channel_features: payment_hop.candidate.features(),
1511 fee_msat: payment_hop.fee_msat,
1512 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1514 }).collect::<Vec<_>>();
1515 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1516 // applicable for the previous hop.
1517 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1518 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1520 selected_paths.push(path);
1523 if let Some(features) = &payment_params.features {
1524 for path in selected_paths.iter_mut() {
1525 if let Ok(route_hop) = path.last_mut().unwrap() {
1526 route_hop.node_features = features.to_context();
1532 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1533 payment_params: Some(payment_params.clone()),
1535 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1541 use routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters, Score};
1542 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1543 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1544 use chain::transaction::OutPoint;
1545 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1546 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1547 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1548 use ln::channelmanager;
1549 use util::test_utils;
1550 use util::ser::Writeable;
1552 use util::ser::Writer;
1554 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1555 use bitcoin::hashes::Hash;
1556 use bitcoin::network::constants::Network;
1557 use bitcoin::blockdata::constants::genesis_block;
1558 use bitcoin::blockdata::script::Builder;
1559 use bitcoin::blockdata::opcodes;
1560 use bitcoin::blockdata::transaction::TxOut;
1564 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1565 use bitcoin::secp256k1::{Secp256k1, All};
1568 use sync::{self, Arc};
1570 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1571 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1572 channelmanager::ChannelDetails {
1573 channel_id: [0; 32],
1574 counterparty: channelmanager::ChannelCounterparty {
1577 unspendable_punishment_reserve: 0,
1578 forwarding_info: None,
1580 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1582 channel_value_satoshis: 0,
1585 outbound_capacity_msat,
1586 inbound_capacity_msat: 42,
1587 unspendable_punishment_reserve: None,
1588 confirmations_required: None,
1589 force_close_spend_delay: None,
1590 is_outbound: true, is_funding_locked: true,
1591 is_usable: true, is_public: true,
1595 // Using the same keys for LN and BTC ids
1597 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1598 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1600 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1601 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1603 let unsigned_announcement = UnsignedChannelAnnouncement {
1605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1609 bitcoin_key_1: node_id_1,
1610 bitcoin_key_2: node_id_2,
1611 excess_data: Vec::new(),
1614 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1615 let valid_announcement = ChannelAnnouncement {
1616 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1617 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1618 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1619 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1620 contents: unsigned_announcement.clone(),
1622 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1623 Ok(res) => assert!(res),
1629 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1630 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1632 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1633 let valid_channel_update = ChannelUpdate {
1634 signature: secp_ctx.sign(&msghash, node_privkey),
1635 contents: update.clone()
1638 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1639 Ok(res) => assert!(res),
1644 fn add_or_update_node(
1645 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1646 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1648 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1649 let unsigned_announcement = UnsignedNodeAnnouncement {
1655 addresses: Vec::new(),
1656 excess_address_data: Vec::new(),
1657 excess_data: Vec::new(),
1659 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1660 let valid_announcement = NodeAnnouncement {
1661 signature: secp_ctx.sign(&msghash, node_privkey),
1662 contents: unsigned_announcement.clone()
1665 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1671 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1672 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1673 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1676 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1678 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1679 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1681 (our_privkey, our_id, privkeys, pubkeys)
1684 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1685 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1686 // test for it later.
1687 let idx = (id - 1) * 2 + 1;
1689 vec![1 << (idx - 8*3), 0, 0, 0]
1690 } else if idx > 8*2 {
1691 vec![1 << (idx - 8*2), 0, 0]
1692 } else if idx > 8*1 {
1693 vec![1 << (idx - 8*1), 0]
1699 fn build_graph() -> (
1701 sync::Arc<NetworkGraph>,
1702 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1703 sync::Arc<test_utils::TestChainSource>,
1704 sync::Arc<test_utils::TestLogger>,
1706 let secp_ctx = Secp256k1::new();
1707 let logger = Arc::new(test_utils::TestLogger::new());
1708 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1709 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1710 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1711 // Build network from our_id to node6:
1713 // -1(1)2- node0 -1(3)2-
1715 // our_id -1(12)2- node7 -1(13)2--- node2
1717 // -1(2)2- node1 -1(4)2-
1720 // chan1 1-to-2: disabled
1721 // chan1 2-to-1: enabled, 0 fee
1723 // chan2 1-to-2: enabled, ignored fee
1724 // chan2 2-to-1: enabled, 0 fee
1726 // chan3 1-to-2: enabled, 0 fee
1727 // chan3 2-to-1: enabled, 100 msat fee
1729 // chan4 1-to-2: enabled, 100% fee
1730 // chan4 2-to-1: enabled, 0 fee
1732 // chan12 1-to-2: enabled, ignored fee
1733 // chan12 2-to-1: enabled, 0 fee
1735 // chan13 1-to-2: enabled, 200% fee
1736 // chan13 2-to-1: enabled, 0 fee
1739 // -1(5)2- node3 -1(8)2--
1743 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1745 // -1(7)2- node5 -1(10)2-
1747 // Channels 5, 8, 9 and 10 are private channels.
1749 // chan5 1-to-2: enabled, 100 msat fee
1750 // chan5 2-to-1: enabled, 0 fee
1752 // chan6 1-to-2: enabled, 0 fee
1753 // chan6 2-to-1: enabled, 0 fee
1755 // chan7 1-to-2: enabled, 100% fee
1756 // chan7 2-to-1: enabled, 0 fee
1758 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1759 // chan8 2-to-1: enabled, 0 fee
1761 // chan9 1-to-2: enabled, 1001 msat fee
1762 // chan9 2-to-1: enabled, 0 fee
1764 // chan10 1-to-2: enabled, 0 fee
1765 // chan10 2-to-1: enabled, 0 fee
1767 // chan11 1-to-2: enabled, 0 fee
1768 // chan11 2-to-1: enabled, 0 fee
1770 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1772 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1773 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1775 short_channel_id: 1,
1778 cltv_expiry_delta: 0,
1779 htlc_minimum_msat: 0,
1780 htlc_maximum_msat: OptionalField::Absent,
1782 fee_proportional_millionths: 0,
1783 excess_data: Vec::new()
1786 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1788 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1789 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1790 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1791 short_channel_id: 2,
1794 cltv_expiry_delta: (5 << 4) | 3,
1795 htlc_minimum_msat: 0,
1796 htlc_maximum_msat: OptionalField::Absent,
1797 fee_base_msat: u32::max_value(),
1798 fee_proportional_millionths: u32::max_value(),
1799 excess_data: Vec::new()
1801 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1802 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1803 short_channel_id: 2,
1806 cltv_expiry_delta: 0,
1807 htlc_minimum_msat: 0,
1808 htlc_maximum_msat: OptionalField::Absent,
1810 fee_proportional_millionths: 0,
1811 excess_data: Vec::new()
1814 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1816 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1817 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1819 short_channel_id: 12,
1822 cltv_expiry_delta: (5 << 4) | 3,
1823 htlc_minimum_msat: 0,
1824 htlc_maximum_msat: OptionalField::Absent,
1825 fee_base_msat: u32::max_value(),
1826 fee_proportional_millionths: u32::max_value(),
1827 excess_data: Vec::new()
1829 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1831 short_channel_id: 12,
1834 cltv_expiry_delta: 0,
1835 htlc_minimum_msat: 0,
1836 htlc_maximum_msat: OptionalField::Absent,
1838 fee_proportional_millionths: 0,
1839 excess_data: Vec::new()
1842 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1844 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1845 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1846 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1847 short_channel_id: 3,
1850 cltv_expiry_delta: (3 << 4) | 1,
1851 htlc_minimum_msat: 0,
1852 htlc_maximum_msat: OptionalField::Absent,
1854 fee_proportional_millionths: 0,
1855 excess_data: Vec::new()
1857 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1859 short_channel_id: 3,
1862 cltv_expiry_delta: (3 << 4) | 2,
1863 htlc_minimum_msat: 0,
1864 htlc_maximum_msat: OptionalField::Absent,
1866 fee_proportional_millionths: 0,
1867 excess_data: Vec::new()
1870 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1871 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1872 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1873 short_channel_id: 4,
1876 cltv_expiry_delta: (4 << 4) | 1,
1877 htlc_minimum_msat: 0,
1878 htlc_maximum_msat: OptionalField::Absent,
1880 fee_proportional_millionths: 1000000,
1881 excess_data: Vec::new()
1883 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1885 short_channel_id: 4,
1888 cltv_expiry_delta: (4 << 4) | 2,
1889 htlc_minimum_msat: 0,
1890 htlc_maximum_msat: OptionalField::Absent,
1892 fee_proportional_millionths: 0,
1893 excess_data: Vec::new()
1896 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1897 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1898 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1899 short_channel_id: 13,
1902 cltv_expiry_delta: (13 << 4) | 1,
1903 htlc_minimum_msat: 0,
1904 htlc_maximum_msat: OptionalField::Absent,
1906 fee_proportional_millionths: 2000000,
1907 excess_data: Vec::new()
1909 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1911 short_channel_id: 13,
1914 cltv_expiry_delta: (13 << 4) | 2,
1915 htlc_minimum_msat: 0,
1916 htlc_maximum_msat: OptionalField::Absent,
1918 fee_proportional_millionths: 0,
1919 excess_data: Vec::new()
1922 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1924 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1925 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1927 short_channel_id: 6,
1930 cltv_expiry_delta: (6 << 4) | 1,
1931 htlc_minimum_msat: 0,
1932 htlc_maximum_msat: OptionalField::Absent,
1934 fee_proportional_millionths: 0,
1935 excess_data: Vec::new()
1937 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1938 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1939 short_channel_id: 6,
1942 cltv_expiry_delta: (6 << 4) | 2,
1943 htlc_minimum_msat: 0,
1944 htlc_maximum_msat: OptionalField::Absent,
1946 fee_proportional_millionths: 0,
1947 excess_data: Vec::new(),
1950 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1951 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1952 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1953 short_channel_id: 11,
1956 cltv_expiry_delta: (11 << 4) | 1,
1957 htlc_minimum_msat: 0,
1958 htlc_maximum_msat: OptionalField::Absent,
1960 fee_proportional_millionths: 0,
1961 excess_data: Vec::new()
1963 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1964 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1965 short_channel_id: 11,
1968 cltv_expiry_delta: (11 << 4) | 2,
1969 htlc_minimum_msat: 0,
1970 htlc_maximum_msat: OptionalField::Absent,
1972 fee_proportional_millionths: 0,
1973 excess_data: Vec::new()
1976 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1978 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1980 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1981 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1982 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1983 short_channel_id: 7,
1986 cltv_expiry_delta: (7 << 4) | 1,
1987 htlc_minimum_msat: 0,
1988 htlc_maximum_msat: OptionalField::Absent,
1990 fee_proportional_millionths: 1000000,
1991 excess_data: Vec::new()
1993 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1995 short_channel_id: 7,
1998 cltv_expiry_delta: (7 << 4) | 2,
1999 htlc_minimum_msat: 0,
2000 htlc_maximum_msat: OptionalField::Absent,
2002 fee_proportional_millionths: 0,
2003 excess_data: Vec::new()
2006 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2008 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2012 fn simple_route_test() {
2013 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2014 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2015 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2016 let scorer = test_utils::TestScorer::with_penalty(0);
2018 // Simple route to 2 via 1
2020 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
2021 assert_eq!(err, "Cannot send a payment of 0 msat");
2022 } else { panic!(); }
2024 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2025 assert_eq!(route.paths[0].len(), 2);
2027 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2028 assert_eq!(route.paths[0][0].short_channel_id, 2);
2029 assert_eq!(route.paths[0][0].fee_msat, 100);
2030 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2031 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2032 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2034 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2035 assert_eq!(route.paths[0][1].short_channel_id, 4);
2036 assert_eq!(route.paths[0][1].fee_msat, 100);
2037 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2038 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2039 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2043 fn invalid_first_hop_test() {
2044 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2045 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2046 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2047 let scorer = test_utils::TestScorer::with_penalty(0);
2049 // Simple route to 2 via 1
2051 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2053 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) {
2054 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2055 } else { panic!(); }
2057 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2058 assert_eq!(route.paths[0].len(), 2);
2062 fn htlc_minimum_test() {
2063 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2064 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2065 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2066 let scorer = test_utils::TestScorer::with_penalty(0);
2068 // Simple route to 2 via 1
2070 // Disable other paths
2071 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2073 short_channel_id: 12,
2075 flags: 2, // to disable
2076 cltv_expiry_delta: 0,
2077 htlc_minimum_msat: 0,
2078 htlc_maximum_msat: OptionalField::Absent,
2080 fee_proportional_millionths: 0,
2081 excess_data: Vec::new()
2083 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2084 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2085 short_channel_id: 3,
2087 flags: 2, // to disable
2088 cltv_expiry_delta: 0,
2089 htlc_minimum_msat: 0,
2090 htlc_maximum_msat: OptionalField::Absent,
2092 fee_proportional_millionths: 0,
2093 excess_data: Vec::new()
2095 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2096 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2097 short_channel_id: 13,
2099 flags: 2, // to disable
2100 cltv_expiry_delta: 0,
2101 htlc_minimum_msat: 0,
2102 htlc_maximum_msat: OptionalField::Absent,
2104 fee_proportional_millionths: 0,
2105 excess_data: Vec::new()
2107 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2108 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2109 short_channel_id: 6,
2111 flags: 2, // to disable
2112 cltv_expiry_delta: 0,
2113 htlc_minimum_msat: 0,
2114 htlc_maximum_msat: OptionalField::Absent,
2116 fee_proportional_millionths: 0,
2117 excess_data: Vec::new()
2119 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2120 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2121 short_channel_id: 7,
2123 flags: 2, // to disable
2124 cltv_expiry_delta: 0,
2125 htlc_minimum_msat: 0,
2126 htlc_maximum_msat: OptionalField::Absent,
2128 fee_proportional_millionths: 0,
2129 excess_data: Vec::new()
2132 // Check against amount_to_transfer_over_msat.
2133 // Set minimal HTLC of 200_000_000 msat.
2134 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2135 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2136 short_channel_id: 2,
2139 cltv_expiry_delta: 0,
2140 htlc_minimum_msat: 200_000_000,
2141 htlc_maximum_msat: OptionalField::Absent,
2143 fee_proportional_millionths: 0,
2144 excess_data: Vec::new()
2147 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2149 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2150 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2151 short_channel_id: 4,
2154 cltv_expiry_delta: 0,
2155 htlc_minimum_msat: 0,
2156 htlc_maximum_msat: OptionalField::Present(199_999_999),
2158 fee_proportional_millionths: 0,
2159 excess_data: Vec::new()
2162 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2163 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) {
2164 assert_eq!(err, "Failed to find a path to the given destination");
2165 } else { panic!(); }
2167 // Lift the restriction on the first hop.
2168 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2170 short_channel_id: 2,
2173 cltv_expiry_delta: 0,
2174 htlc_minimum_msat: 0,
2175 htlc_maximum_msat: OptionalField::Absent,
2177 fee_proportional_millionths: 0,
2178 excess_data: Vec::new()
2181 // A payment above the minimum should pass
2182 let route = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2183 assert_eq!(route.paths[0].len(), 2);
2187 fn htlc_minimum_overpay_test() {
2188 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2189 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2190 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2191 let scorer = test_utils::TestScorer::with_penalty(0);
2193 // A route to node#2 via two paths.
2194 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2195 // Thus, they can't send 60 without overpaying.
2196 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2198 short_channel_id: 2,
2201 cltv_expiry_delta: 0,
2202 htlc_minimum_msat: 35_000,
2203 htlc_maximum_msat: OptionalField::Present(40_000),
2205 fee_proportional_millionths: 0,
2206 excess_data: Vec::new()
2208 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210 short_channel_id: 12,
2213 cltv_expiry_delta: 0,
2214 htlc_minimum_msat: 35_000,
2215 htlc_maximum_msat: OptionalField::Present(40_000),
2217 fee_proportional_millionths: 0,
2218 excess_data: Vec::new()
2222 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2224 short_channel_id: 13,
2227 cltv_expiry_delta: 0,
2228 htlc_minimum_msat: 0,
2229 htlc_maximum_msat: OptionalField::Absent,
2231 fee_proportional_millionths: 0,
2232 excess_data: Vec::new()
2234 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2236 short_channel_id: 4,
2239 cltv_expiry_delta: 0,
2240 htlc_minimum_msat: 0,
2241 htlc_maximum_msat: OptionalField::Absent,
2243 fee_proportional_millionths: 0,
2244 excess_data: Vec::new()
2247 // Disable other paths
2248 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2250 short_channel_id: 1,
2252 flags: 2, // to disable
2253 cltv_expiry_delta: 0,
2254 htlc_minimum_msat: 0,
2255 htlc_maximum_msat: OptionalField::Absent,
2257 fee_proportional_millionths: 0,
2258 excess_data: Vec::new()
2261 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2262 // Overpay fees to hit htlc_minimum_msat.
2263 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2264 // TODO: this could be better balanced to overpay 10k and not 15k.
2265 assert_eq!(overpaid_fees, 15_000);
2267 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2268 // while taking even more fee to match htlc_minimum_msat.
2269 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2271 short_channel_id: 12,
2274 cltv_expiry_delta: 0,
2275 htlc_minimum_msat: 65_000,
2276 htlc_maximum_msat: OptionalField::Present(80_000),
2278 fee_proportional_millionths: 0,
2279 excess_data: Vec::new()
2281 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2283 short_channel_id: 2,
2286 cltv_expiry_delta: 0,
2287 htlc_minimum_msat: 0,
2288 htlc_maximum_msat: OptionalField::Absent,
2290 fee_proportional_millionths: 0,
2291 excess_data: Vec::new()
2293 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2294 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2295 short_channel_id: 4,
2298 cltv_expiry_delta: 0,
2299 htlc_minimum_msat: 0,
2300 htlc_maximum_msat: OptionalField::Absent,
2302 fee_proportional_millionths: 100_000,
2303 excess_data: Vec::new()
2306 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2307 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2308 assert_eq!(route.paths.len(), 1);
2309 assert_eq!(route.paths[0][0].short_channel_id, 12);
2310 let fees = route.paths[0][0].fee_msat;
2311 assert_eq!(fees, 5_000);
2313 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2314 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2315 // the other channel.
2316 assert_eq!(route.paths.len(), 1);
2317 assert_eq!(route.paths[0][0].short_channel_id, 2);
2318 let fees = route.paths[0][0].fee_msat;
2319 assert_eq!(fees, 5_000);
2323 fn disable_channels_test() {
2324 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2325 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2326 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2327 let scorer = test_utils::TestScorer::with_penalty(0);
2329 // // Disable channels 4 and 12 by flags=2
2330 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2331 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2332 short_channel_id: 4,
2334 flags: 2, // to disable
2335 cltv_expiry_delta: 0,
2336 htlc_minimum_msat: 0,
2337 htlc_maximum_msat: OptionalField::Absent,
2339 fee_proportional_millionths: 0,
2340 excess_data: Vec::new()
2342 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2343 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2344 short_channel_id: 12,
2346 flags: 2, // to disable
2347 cltv_expiry_delta: 0,
2348 htlc_minimum_msat: 0,
2349 htlc_maximum_msat: OptionalField::Absent,
2351 fee_proportional_millionths: 0,
2352 excess_data: Vec::new()
2355 // If all the channels require some features we don't understand, route should fail
2356 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2357 assert_eq!(err, "Failed to find a path to the given destination");
2358 } else { panic!(); }
2360 // If we specify a channel to node7, that overrides our local channel view and that gets used
2361 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2362 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2363 assert_eq!(route.paths[0].len(), 2);
2365 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2366 assert_eq!(route.paths[0][0].short_channel_id, 42);
2367 assert_eq!(route.paths[0][0].fee_msat, 200);
2368 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2369 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2370 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2372 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2373 assert_eq!(route.paths[0][1].short_channel_id, 13);
2374 assert_eq!(route.paths[0][1].fee_msat, 100);
2375 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2376 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2377 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2381 fn disable_node_test() {
2382 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2383 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2384 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2385 let scorer = test_utils::TestScorer::with_penalty(0);
2387 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2388 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2389 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2390 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2391 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2393 // If all nodes require some features we don't understand, route should fail
2394 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2395 assert_eq!(err, "Failed to find a path to the given destination");
2396 } else { panic!(); }
2398 // If we specify a channel to node7, that overrides our local channel view and that gets used
2399 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2400 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2401 assert_eq!(route.paths[0].len(), 2);
2403 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2404 assert_eq!(route.paths[0][0].short_channel_id, 42);
2405 assert_eq!(route.paths[0][0].fee_msat, 200);
2406 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2407 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2408 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2410 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2411 assert_eq!(route.paths[0][1].short_channel_id, 13);
2412 assert_eq!(route.paths[0][1].fee_msat, 100);
2413 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2414 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2415 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2417 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2418 // naively) assume that the user checked the feature bits on the invoice, which override
2419 // the node_announcement.
2423 fn our_chans_test() {
2424 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2425 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2426 let scorer = test_utils::TestScorer::with_penalty(0);
2428 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2429 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2430 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2431 assert_eq!(route.paths[0].len(), 3);
2433 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2434 assert_eq!(route.paths[0][0].short_channel_id, 2);
2435 assert_eq!(route.paths[0][0].fee_msat, 200);
2436 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2437 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2438 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2440 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2441 assert_eq!(route.paths[0][1].short_channel_id, 4);
2442 assert_eq!(route.paths[0][1].fee_msat, 100);
2443 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2444 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2445 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2447 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2448 assert_eq!(route.paths[0][2].short_channel_id, 3);
2449 assert_eq!(route.paths[0][2].fee_msat, 100);
2450 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2451 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2452 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2454 // If we specify a channel to node7, that overrides our local channel view and that gets used
2455 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2456 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2457 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2458 assert_eq!(route.paths[0].len(), 2);
2460 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2461 assert_eq!(route.paths[0][0].short_channel_id, 42);
2462 assert_eq!(route.paths[0][0].fee_msat, 200);
2463 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2464 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2465 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2467 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2468 assert_eq!(route.paths[0][1].short_channel_id, 13);
2469 assert_eq!(route.paths[0][1].fee_msat, 100);
2470 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2471 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2472 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2475 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2476 let zero_fees = RoutingFees {
2478 proportional_millionths: 0,
2480 vec![RouteHint(vec![RouteHintHop {
2481 src_node_id: nodes[3],
2482 short_channel_id: 8,
2484 cltv_expiry_delta: (8 << 4) | 1,
2485 htlc_minimum_msat: None,
2486 htlc_maximum_msat: None,
2488 ]), RouteHint(vec![RouteHintHop {
2489 src_node_id: nodes[4],
2490 short_channel_id: 9,
2493 proportional_millionths: 0,
2495 cltv_expiry_delta: (9 << 4) | 1,
2496 htlc_minimum_msat: None,
2497 htlc_maximum_msat: None,
2498 }]), RouteHint(vec![RouteHintHop {
2499 src_node_id: nodes[5],
2500 short_channel_id: 10,
2502 cltv_expiry_delta: (10 << 4) | 1,
2503 htlc_minimum_msat: None,
2504 htlc_maximum_msat: None,
2508 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2509 let zero_fees = RoutingFees {
2511 proportional_millionths: 0,
2513 vec![RouteHint(vec![RouteHintHop {
2514 src_node_id: nodes[2],
2515 short_channel_id: 5,
2518 proportional_millionths: 0,
2520 cltv_expiry_delta: (5 << 4) | 1,
2521 htlc_minimum_msat: None,
2522 htlc_maximum_msat: None,
2524 src_node_id: nodes[3],
2525 short_channel_id: 8,
2527 cltv_expiry_delta: (8 << 4) | 1,
2528 htlc_minimum_msat: None,
2529 htlc_maximum_msat: None,
2531 ]), RouteHint(vec![RouteHintHop {
2532 src_node_id: nodes[4],
2533 short_channel_id: 9,
2536 proportional_millionths: 0,
2538 cltv_expiry_delta: (9 << 4) | 1,
2539 htlc_minimum_msat: None,
2540 htlc_maximum_msat: None,
2541 }]), RouteHint(vec![RouteHintHop {
2542 src_node_id: nodes[5],
2543 short_channel_id: 10,
2545 cltv_expiry_delta: (10 << 4) | 1,
2546 htlc_minimum_msat: None,
2547 htlc_maximum_msat: None,
2552 fn partial_route_hint_test() {
2553 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2554 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2555 let scorer = test_utils::TestScorer::with_penalty(0);
2557 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2558 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2559 // RouteHint may be partially used by the algo to build the best path.
2561 // First check that last hop can't have its source as the payee.
2562 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2563 src_node_id: nodes[6],
2564 short_channel_id: 8,
2567 proportional_millionths: 0,
2569 cltv_expiry_delta: (8 << 4) | 1,
2570 htlc_minimum_msat: None,
2571 htlc_maximum_msat: None,
2574 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2575 invalid_last_hops.push(invalid_last_hop);
2577 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2578 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2579 assert_eq!(err, "Route hint cannot have the payee as the source.");
2580 } else { panic!(); }
2583 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2584 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2585 assert_eq!(route.paths[0].len(), 5);
2587 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2588 assert_eq!(route.paths[0][0].short_channel_id, 2);
2589 assert_eq!(route.paths[0][0].fee_msat, 100);
2590 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2591 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2592 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2594 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2595 assert_eq!(route.paths[0][1].short_channel_id, 4);
2596 assert_eq!(route.paths[0][1].fee_msat, 0);
2597 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2598 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2599 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2601 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2602 assert_eq!(route.paths[0][2].short_channel_id, 6);
2603 assert_eq!(route.paths[0][2].fee_msat, 0);
2604 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2605 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2606 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2608 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2609 assert_eq!(route.paths[0][3].short_channel_id, 11);
2610 assert_eq!(route.paths[0][3].fee_msat, 0);
2611 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2612 // If we have a peer in the node map, we'll use their features here since we don't have
2613 // a way of figuring out their features from the invoice:
2614 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2615 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2617 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2618 assert_eq!(route.paths[0][4].short_channel_id, 8);
2619 assert_eq!(route.paths[0][4].fee_msat, 100);
2620 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2621 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2622 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2625 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2626 let zero_fees = RoutingFees {
2628 proportional_millionths: 0,
2630 vec![RouteHint(vec![RouteHintHop {
2631 src_node_id: nodes[3],
2632 short_channel_id: 8,
2634 cltv_expiry_delta: (8 << 4) | 1,
2635 htlc_minimum_msat: None,
2636 htlc_maximum_msat: None,
2637 }]), RouteHint(vec![
2639 ]), RouteHint(vec![RouteHintHop {
2640 src_node_id: nodes[5],
2641 short_channel_id: 10,
2643 cltv_expiry_delta: (10 << 4) | 1,
2644 htlc_minimum_msat: None,
2645 htlc_maximum_msat: None,
2650 fn ignores_empty_last_hops_test() {
2651 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2652 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2653 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2654 let scorer = test_utils::TestScorer::with_penalty(0);
2656 // Test handling of an empty RouteHint passed in Invoice.
2658 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2659 assert_eq!(route.paths[0].len(), 5);
2661 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2662 assert_eq!(route.paths[0][0].short_channel_id, 2);
2663 assert_eq!(route.paths[0][0].fee_msat, 100);
2664 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2665 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2666 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2668 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2669 assert_eq!(route.paths[0][1].short_channel_id, 4);
2670 assert_eq!(route.paths[0][1].fee_msat, 0);
2671 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2672 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2673 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2675 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2676 assert_eq!(route.paths[0][2].short_channel_id, 6);
2677 assert_eq!(route.paths[0][2].fee_msat, 0);
2678 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2679 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2680 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2682 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2683 assert_eq!(route.paths[0][3].short_channel_id, 11);
2684 assert_eq!(route.paths[0][3].fee_msat, 0);
2685 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2686 // If we have a peer in the node map, we'll use their features here since we don't have
2687 // a way of figuring out their features from the invoice:
2688 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2689 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2691 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2692 assert_eq!(route.paths[0][4].short_channel_id, 8);
2693 assert_eq!(route.paths[0][4].fee_msat, 100);
2694 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2695 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2696 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2699 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2700 let zero_fees = RoutingFees {
2702 proportional_millionths: 0,
2704 vec![RouteHint(vec![RouteHintHop {
2705 src_node_id: nodes[2],
2706 short_channel_id: 5,
2709 proportional_millionths: 0,
2711 cltv_expiry_delta: (5 << 4) | 1,
2712 htlc_minimum_msat: None,
2713 htlc_maximum_msat: None,
2715 src_node_id: nodes[3],
2716 short_channel_id: 8,
2718 cltv_expiry_delta: (8 << 4) | 1,
2719 htlc_minimum_msat: None,
2720 htlc_maximum_msat: None,
2721 }]), RouteHint(vec![RouteHintHop {
2722 src_node_id: nodes[5],
2723 short_channel_id: 10,
2725 cltv_expiry_delta: (10 << 4) | 1,
2726 htlc_minimum_msat: None,
2727 htlc_maximum_msat: None,
2732 fn multi_hint_last_hops_test() {
2733 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2734 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2735 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2736 let scorer = test_utils::TestScorer::with_penalty(0);
2737 // Test through channels 2, 3, 5, 8.
2738 // Test shows that multiple hop hints are considered.
2740 // Disabling channels 6 & 7 by flags=2
2741 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2742 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2743 short_channel_id: 6,
2745 flags: 2, // to disable
2746 cltv_expiry_delta: 0,
2747 htlc_minimum_msat: 0,
2748 htlc_maximum_msat: OptionalField::Absent,
2750 fee_proportional_millionths: 0,
2751 excess_data: Vec::new()
2753 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2754 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2755 short_channel_id: 7,
2757 flags: 2, // to disable
2758 cltv_expiry_delta: 0,
2759 htlc_minimum_msat: 0,
2760 htlc_maximum_msat: OptionalField::Absent,
2762 fee_proportional_millionths: 0,
2763 excess_data: Vec::new()
2766 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2767 assert_eq!(route.paths[0].len(), 4);
2769 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2770 assert_eq!(route.paths[0][0].short_channel_id, 2);
2771 assert_eq!(route.paths[0][0].fee_msat, 200);
2772 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2773 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2774 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2776 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2777 assert_eq!(route.paths[0][1].short_channel_id, 4);
2778 assert_eq!(route.paths[0][1].fee_msat, 100);
2779 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2780 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2781 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2783 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2784 assert_eq!(route.paths[0][2].short_channel_id, 5);
2785 assert_eq!(route.paths[0][2].fee_msat, 0);
2786 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2787 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2788 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2790 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2791 assert_eq!(route.paths[0][3].short_channel_id, 8);
2792 assert_eq!(route.paths[0][3].fee_msat, 100);
2793 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2794 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2795 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2798 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2799 let zero_fees = RoutingFees {
2801 proportional_millionths: 0,
2803 vec![RouteHint(vec![RouteHintHop {
2804 src_node_id: nodes[4],
2805 short_channel_id: 11,
2807 cltv_expiry_delta: (11 << 4) | 1,
2808 htlc_minimum_msat: None,
2809 htlc_maximum_msat: None,
2811 src_node_id: nodes[3],
2812 short_channel_id: 8,
2814 cltv_expiry_delta: (8 << 4) | 1,
2815 htlc_minimum_msat: None,
2816 htlc_maximum_msat: None,
2817 }]), RouteHint(vec![RouteHintHop {
2818 src_node_id: nodes[4],
2819 short_channel_id: 9,
2822 proportional_millionths: 0,
2824 cltv_expiry_delta: (9 << 4) | 1,
2825 htlc_minimum_msat: None,
2826 htlc_maximum_msat: None,
2827 }]), RouteHint(vec![RouteHintHop {
2828 src_node_id: nodes[5],
2829 short_channel_id: 10,
2831 cltv_expiry_delta: (10 << 4) | 1,
2832 htlc_minimum_msat: None,
2833 htlc_maximum_msat: None,
2838 fn last_hops_with_public_channel_test() {
2839 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2840 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2841 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2842 let scorer = test_utils::TestScorer::with_penalty(0);
2843 // This test shows that public routes can be present in the invoice
2844 // which would be handled in the same manner.
2846 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2847 assert_eq!(route.paths[0].len(), 5);
2849 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2850 assert_eq!(route.paths[0][0].short_channel_id, 2);
2851 assert_eq!(route.paths[0][0].fee_msat, 100);
2852 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2853 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2854 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2856 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2857 assert_eq!(route.paths[0][1].short_channel_id, 4);
2858 assert_eq!(route.paths[0][1].fee_msat, 0);
2859 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2860 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2861 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2863 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2864 assert_eq!(route.paths[0][2].short_channel_id, 6);
2865 assert_eq!(route.paths[0][2].fee_msat, 0);
2866 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2867 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2868 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2870 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2871 assert_eq!(route.paths[0][3].short_channel_id, 11);
2872 assert_eq!(route.paths[0][3].fee_msat, 0);
2873 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2874 // If we have a peer in the node map, we'll use their features here since we don't have
2875 // a way of figuring out their features from the invoice:
2876 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2877 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2879 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2880 assert_eq!(route.paths[0][4].short_channel_id, 8);
2881 assert_eq!(route.paths[0][4].fee_msat, 100);
2882 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2883 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2884 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2888 fn our_chans_last_hop_connect_test() {
2889 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2890 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2891 let scorer = test_utils::TestScorer::with_penalty(0);
2893 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2894 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2895 let mut last_hops = last_hops(&nodes);
2896 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2897 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2898 assert_eq!(route.paths[0].len(), 2);
2900 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2901 assert_eq!(route.paths[0][0].short_channel_id, 42);
2902 assert_eq!(route.paths[0][0].fee_msat, 0);
2903 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2904 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2905 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2907 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2908 assert_eq!(route.paths[0][1].short_channel_id, 8);
2909 assert_eq!(route.paths[0][1].fee_msat, 100);
2910 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2911 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2912 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2914 last_hops[0].0[0].fees.base_msat = 1000;
2916 // Revert to via 6 as the fee on 8 goes up
2917 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
2918 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2919 assert_eq!(route.paths[0].len(), 4);
2921 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2922 assert_eq!(route.paths[0][0].short_channel_id, 2);
2923 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2924 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2925 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2926 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2928 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2929 assert_eq!(route.paths[0][1].short_channel_id, 4);
2930 assert_eq!(route.paths[0][1].fee_msat, 100);
2931 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
2932 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2933 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2935 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2936 assert_eq!(route.paths[0][2].short_channel_id, 7);
2937 assert_eq!(route.paths[0][2].fee_msat, 0);
2938 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
2939 // If we have a peer in the node map, we'll use their features here since we don't have
2940 // a way of figuring out their features from the invoice:
2941 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2942 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2944 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2945 assert_eq!(route.paths[0][3].short_channel_id, 10);
2946 assert_eq!(route.paths[0][3].fee_msat, 100);
2947 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2948 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2949 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2951 // ...but still use 8 for larger payments as 6 has a variable feerate
2952 let route = get_route(&our_id, &payment_params, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2953 assert_eq!(route.paths[0].len(), 5);
2955 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2956 assert_eq!(route.paths[0][0].short_channel_id, 2);
2957 assert_eq!(route.paths[0][0].fee_msat, 3000);
2958 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2959 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2960 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2962 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2963 assert_eq!(route.paths[0][1].short_channel_id, 4);
2964 assert_eq!(route.paths[0][1].fee_msat, 0);
2965 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2966 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2967 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2969 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2970 assert_eq!(route.paths[0][2].short_channel_id, 6);
2971 assert_eq!(route.paths[0][2].fee_msat, 0);
2972 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2973 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2974 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2976 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2977 assert_eq!(route.paths[0][3].short_channel_id, 11);
2978 assert_eq!(route.paths[0][3].fee_msat, 1000);
2979 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2980 // If we have a peer in the node map, we'll use their features here since we don't have
2981 // a way of figuring out their features from the invoice:
2982 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2983 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2985 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2986 assert_eq!(route.paths[0][4].short_channel_id, 8);
2987 assert_eq!(route.paths[0][4].fee_msat, 2000);
2988 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2989 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2990 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2993 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> {
2994 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2995 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2996 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2998 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2999 let last_hops = RouteHint(vec![RouteHintHop {
3000 src_node_id: middle_node_id,
3001 short_channel_id: 8,
3004 proportional_millionths: last_hop_fee_prop,
3006 cltv_expiry_delta: (8 << 4) | 1,
3007 htlc_minimum_msat: None,
3008 htlc_maximum_msat: last_hop_htlc_max,
3010 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3011 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3012 let scorer = test_utils::TestScorer::with_penalty(0);
3013 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)
3017 fn unannounced_path_test() {
3018 // We should be able to send a payment to a destination without any help of a routing graph
3019 // if we have a channel with a common counterparty that appears in the first and last hop
3021 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3023 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3024 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3025 assert_eq!(route.paths[0].len(), 2);
3027 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3028 assert_eq!(route.paths[0][0].short_channel_id, 42);
3029 assert_eq!(route.paths[0][0].fee_msat, 1001);
3030 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3031 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3032 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3034 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3035 assert_eq!(route.paths[0][1].short_channel_id, 8);
3036 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3037 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3038 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3039 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3043 fn overflow_unannounced_path_test_liquidity_underflow() {
3044 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3045 // the last-hop had a fee which overflowed a u64, we'd panic.
3046 // This was due to us adding the first-hop from us unconditionally, causing us to think
3047 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3048 // In this test, we previously hit a subtraction underflow due to having less available
3049 // liquidity at the last hop than 0.
3050 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());
3054 fn overflow_unannounced_path_test_feerate_overflow() {
3055 // This tests for the same case as above, except instead of hitting a subtraction
3056 // underflow, we hit a case where the fee charged at a hop overflowed.
3057 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());
3061 fn available_amount_while_routing_test() {
3062 // Tests whether we choose the correct available channel amount while routing.
3064 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3065 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3066 let scorer = test_utils::TestScorer::with_penalty(0);
3067 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3069 // We will use a simple single-path route from
3070 // our node to node2 via node0: channels {1, 3}.
3072 // First disable all other paths.
3073 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3075 short_channel_id: 2,
3078 cltv_expiry_delta: 0,
3079 htlc_minimum_msat: 0,
3080 htlc_maximum_msat: OptionalField::Present(100_000),
3082 fee_proportional_millionths: 0,
3083 excess_data: Vec::new()
3085 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3087 short_channel_id: 12,
3090 cltv_expiry_delta: 0,
3091 htlc_minimum_msat: 0,
3092 htlc_maximum_msat: OptionalField::Present(100_000),
3094 fee_proportional_millionths: 0,
3095 excess_data: Vec::new()
3098 // Make the first channel (#1) very permissive,
3099 // and we will be testing all limits on the second channel.
3100 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3101 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3102 short_channel_id: 1,
3105 cltv_expiry_delta: 0,
3106 htlc_minimum_msat: 0,
3107 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3109 fee_proportional_millionths: 0,
3110 excess_data: Vec::new()
3113 // First, let's see if routing works if we have absolutely no idea about the available amount.
3114 // In this case, it should be set to 250_000 sats.
3115 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3116 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3117 short_channel_id: 3,
3120 cltv_expiry_delta: 0,
3121 htlc_minimum_msat: 0,
3122 htlc_maximum_msat: OptionalField::Absent,
3124 fee_proportional_millionths: 0,
3125 excess_data: Vec::new()
3129 // Attempt to route more than available results in a failure.
3130 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3131 &our_id, &payment_params, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3132 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3133 } else { panic!(); }
3137 // Now, attempt to route an exact amount we have should be fine.
3138 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3139 assert_eq!(route.paths.len(), 1);
3140 let path = route.paths.last().unwrap();
3141 assert_eq!(path.len(), 2);
3142 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3143 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3146 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3147 // Disable channel #1 and use another first hop.
3148 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3150 short_channel_id: 1,
3153 cltv_expiry_delta: 0,
3154 htlc_minimum_msat: 0,
3155 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3157 fee_proportional_millionths: 0,
3158 excess_data: Vec::new()
3161 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3162 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3165 // Attempt to route more than available results in a failure.
3166 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3167 &our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3168 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3169 } else { panic!(); }
3173 // Now, attempt to route an exact amount we have should be fine.
3174 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();
3175 assert_eq!(route.paths.len(), 1);
3176 let path = route.paths.last().unwrap();
3177 assert_eq!(path.len(), 2);
3178 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3179 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3182 // Enable channel #1 back.
3183 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3185 short_channel_id: 1,
3188 cltv_expiry_delta: 0,
3189 htlc_minimum_msat: 0,
3190 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3192 fee_proportional_millionths: 0,
3193 excess_data: Vec::new()
3197 // Now let's see if routing works if we know only htlc_maximum_msat.
3198 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3200 short_channel_id: 3,
3203 cltv_expiry_delta: 0,
3204 htlc_minimum_msat: 0,
3205 htlc_maximum_msat: OptionalField::Present(15_000),
3207 fee_proportional_millionths: 0,
3208 excess_data: Vec::new()
3212 // Attempt to route more than available results in a failure.
3213 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3214 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3215 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3216 } else { panic!(); }
3220 // Now, attempt to route an exact amount we have should be fine.
3221 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3222 assert_eq!(route.paths.len(), 1);
3223 let path = route.paths.last().unwrap();
3224 assert_eq!(path.len(), 2);
3225 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3226 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3229 // Now let's see if routing works if we know only capacity from the UTXO.
3231 // We can't change UTXO capacity on the fly, so we'll disable
3232 // the existing channel and add another one with the capacity we need.
3233 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3235 short_channel_id: 3,
3238 cltv_expiry_delta: 0,
3239 htlc_minimum_msat: 0,
3240 htlc_maximum_msat: OptionalField::Absent,
3242 fee_proportional_millionths: 0,
3243 excess_data: Vec::new()
3246 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3247 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3248 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3249 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3250 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3252 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3253 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3255 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3256 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3257 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3258 short_channel_id: 333,
3261 cltv_expiry_delta: (3 << 4) | 1,
3262 htlc_minimum_msat: 0,
3263 htlc_maximum_msat: OptionalField::Absent,
3265 fee_proportional_millionths: 0,
3266 excess_data: Vec::new()
3268 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3269 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3270 short_channel_id: 333,
3273 cltv_expiry_delta: (3 << 4) | 2,
3274 htlc_minimum_msat: 0,
3275 htlc_maximum_msat: OptionalField::Absent,
3277 fee_proportional_millionths: 0,
3278 excess_data: Vec::new()
3282 // Attempt to route more than available results in a failure.
3283 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3284 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3285 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3286 } else { panic!(); }
3290 // Now, attempt to route an exact amount we have should be fine.
3291 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3292 assert_eq!(route.paths.len(), 1);
3293 let path = route.paths.last().unwrap();
3294 assert_eq!(path.len(), 2);
3295 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3296 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3299 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3300 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3302 short_channel_id: 333,
3305 cltv_expiry_delta: 0,
3306 htlc_minimum_msat: 0,
3307 htlc_maximum_msat: OptionalField::Present(10_000),
3309 fee_proportional_millionths: 0,
3310 excess_data: Vec::new()
3314 // Attempt to route more than available results in a failure.
3315 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3316 &our_id, &payment_params, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3317 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3318 } else { panic!(); }
3322 // Now, attempt to route an exact amount we have should be fine.
3323 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3324 assert_eq!(route.paths.len(), 1);
3325 let path = route.paths.last().unwrap();
3326 assert_eq!(path.len(), 2);
3327 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3328 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3333 fn available_liquidity_last_hop_test() {
3334 // Check that available liquidity properly limits the path even when only
3335 // one of the latter hops is limited.
3336 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3337 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3338 let scorer = test_utils::TestScorer::with_penalty(0);
3339 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3341 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3342 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3343 // Total capacity: 50 sats.
3345 // Disable other potential paths.
3346 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3348 short_channel_id: 2,
3351 cltv_expiry_delta: 0,
3352 htlc_minimum_msat: 0,
3353 htlc_maximum_msat: OptionalField::Present(100_000),
3355 fee_proportional_millionths: 0,
3356 excess_data: Vec::new()
3358 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3359 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3360 short_channel_id: 7,
3363 cltv_expiry_delta: 0,
3364 htlc_minimum_msat: 0,
3365 htlc_maximum_msat: OptionalField::Present(100_000),
3367 fee_proportional_millionths: 0,
3368 excess_data: Vec::new()
3373 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3374 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3375 short_channel_id: 12,
3378 cltv_expiry_delta: 0,
3379 htlc_minimum_msat: 0,
3380 htlc_maximum_msat: OptionalField::Present(100_000),
3382 fee_proportional_millionths: 0,
3383 excess_data: Vec::new()
3385 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3386 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3387 short_channel_id: 13,
3390 cltv_expiry_delta: 0,
3391 htlc_minimum_msat: 0,
3392 htlc_maximum_msat: OptionalField::Present(100_000),
3394 fee_proportional_millionths: 0,
3395 excess_data: Vec::new()
3398 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3400 short_channel_id: 6,
3403 cltv_expiry_delta: 0,
3404 htlc_minimum_msat: 0,
3405 htlc_maximum_msat: OptionalField::Present(50_000),
3407 fee_proportional_millionths: 0,
3408 excess_data: Vec::new()
3410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3412 short_channel_id: 11,
3415 cltv_expiry_delta: 0,
3416 htlc_minimum_msat: 0,
3417 htlc_maximum_msat: OptionalField::Present(100_000),
3419 fee_proportional_millionths: 0,
3420 excess_data: Vec::new()
3423 // Attempt to route more than available results in a failure.
3424 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3425 &our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3426 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3427 } else { panic!(); }
3431 // Now, attempt to route 49 sats (just a bit below the capacity).
3432 let route = get_route(&our_id, &payment_params, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3433 assert_eq!(route.paths.len(), 1);
3434 let mut total_amount_paid_msat = 0;
3435 for path in &route.paths {
3436 assert_eq!(path.len(), 4);
3437 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3438 total_amount_paid_msat += path.last().unwrap().fee_msat;
3440 assert_eq!(total_amount_paid_msat, 49_000);
3444 // Attempt to route an exact amount is also fine
3445 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3446 assert_eq!(route.paths.len(), 1);
3447 let mut total_amount_paid_msat = 0;
3448 for path in &route.paths {
3449 assert_eq!(path.len(), 4);
3450 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3451 total_amount_paid_msat += path.last().unwrap().fee_msat;
3453 assert_eq!(total_amount_paid_msat, 50_000);
3458 fn ignore_fee_first_hop_test() {
3459 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3460 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3461 let scorer = test_utils::TestScorer::with_penalty(0);
3462 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3464 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3465 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3466 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3467 short_channel_id: 1,
3470 cltv_expiry_delta: 0,
3471 htlc_minimum_msat: 0,
3472 htlc_maximum_msat: OptionalField::Present(100_000),
3473 fee_base_msat: 1_000_000,
3474 fee_proportional_millionths: 0,
3475 excess_data: Vec::new()
3477 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3479 short_channel_id: 3,
3482 cltv_expiry_delta: 0,
3483 htlc_minimum_msat: 0,
3484 htlc_maximum_msat: OptionalField::Present(50_000),
3486 fee_proportional_millionths: 0,
3487 excess_data: Vec::new()
3491 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3492 assert_eq!(route.paths.len(), 1);
3493 let mut total_amount_paid_msat = 0;
3494 for path in &route.paths {
3495 assert_eq!(path.len(), 2);
3496 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3497 total_amount_paid_msat += path.last().unwrap().fee_msat;
3499 assert_eq!(total_amount_paid_msat, 50_000);
3504 fn simple_mpp_route_test() {
3505 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3506 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3507 let scorer = test_utils::TestScorer::with_penalty(0);
3508 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3510 // We need a route consisting of 3 paths:
3511 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3512 // To achieve this, the amount being transferred should be around
3513 // the total capacity of these 3 paths.
3515 // First, we set limits on these (previously unlimited) channels.
3516 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3518 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3519 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3520 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3521 short_channel_id: 1,
3524 cltv_expiry_delta: 0,
3525 htlc_minimum_msat: 0,
3526 htlc_maximum_msat: OptionalField::Present(100_000),
3528 fee_proportional_millionths: 0,
3529 excess_data: Vec::new()
3531 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3532 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3533 short_channel_id: 3,
3536 cltv_expiry_delta: 0,
3537 htlc_minimum_msat: 0,
3538 htlc_maximum_msat: OptionalField::Present(50_000),
3540 fee_proportional_millionths: 0,
3541 excess_data: Vec::new()
3544 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3545 // (total limit 60).
3546 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3547 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3548 short_channel_id: 12,
3551 cltv_expiry_delta: 0,
3552 htlc_minimum_msat: 0,
3553 htlc_maximum_msat: OptionalField::Present(60_000),
3555 fee_proportional_millionths: 0,
3556 excess_data: Vec::new()
3558 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3560 short_channel_id: 13,
3563 cltv_expiry_delta: 0,
3564 htlc_minimum_msat: 0,
3565 htlc_maximum_msat: OptionalField::Present(60_000),
3567 fee_proportional_millionths: 0,
3568 excess_data: Vec::new()
3571 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3572 // (total capacity 180 sats).
3573 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3574 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3575 short_channel_id: 2,
3578 cltv_expiry_delta: 0,
3579 htlc_minimum_msat: 0,
3580 htlc_maximum_msat: OptionalField::Present(200_000),
3582 fee_proportional_millionths: 0,
3583 excess_data: Vec::new()
3585 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3587 short_channel_id: 4,
3590 cltv_expiry_delta: 0,
3591 htlc_minimum_msat: 0,
3592 htlc_maximum_msat: OptionalField::Present(180_000),
3594 fee_proportional_millionths: 0,
3595 excess_data: Vec::new()
3599 // Attempt to route more than available results in a failure.
3600 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3601 &our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3602 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3603 } else { panic!(); }
3607 // Now, attempt to route 250 sats (just a bit below the capacity).
3608 // Our algorithm should provide us with these 3 paths.
3609 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3610 assert_eq!(route.paths.len(), 3);
3611 let mut total_amount_paid_msat = 0;
3612 for path in &route.paths {
3613 assert_eq!(path.len(), 2);
3614 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3615 total_amount_paid_msat += path.last().unwrap().fee_msat;
3617 assert_eq!(total_amount_paid_msat, 250_000);
3621 // Attempt to route an exact amount is also fine
3622 let route = get_route(&our_id, &payment_params, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3623 assert_eq!(route.paths.len(), 3);
3624 let mut total_amount_paid_msat = 0;
3625 for path in &route.paths {
3626 assert_eq!(path.len(), 2);
3627 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3628 total_amount_paid_msat += path.last().unwrap().fee_msat;
3630 assert_eq!(total_amount_paid_msat, 290_000);
3635 fn long_mpp_route_test() {
3636 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3637 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3638 let scorer = test_utils::TestScorer::with_penalty(0);
3639 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3641 // We need a route consisting of 3 paths:
3642 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3643 // Note that these paths overlap (channels 5, 12, 13).
3644 // We will route 300 sats.
3645 // Each path will have 100 sats capacity, those channels which
3646 // are used twice will have 200 sats capacity.
3648 // Disable other potential paths.
3649 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3650 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3651 short_channel_id: 2,
3654 cltv_expiry_delta: 0,
3655 htlc_minimum_msat: 0,
3656 htlc_maximum_msat: OptionalField::Present(100_000),
3658 fee_proportional_millionths: 0,
3659 excess_data: Vec::new()
3661 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3662 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3663 short_channel_id: 7,
3666 cltv_expiry_delta: 0,
3667 htlc_minimum_msat: 0,
3668 htlc_maximum_msat: OptionalField::Present(100_000),
3670 fee_proportional_millionths: 0,
3671 excess_data: Vec::new()
3674 // Path via {node0, node2} is channels {1, 3, 5}.
3675 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3677 short_channel_id: 1,
3680 cltv_expiry_delta: 0,
3681 htlc_minimum_msat: 0,
3682 htlc_maximum_msat: OptionalField::Present(100_000),
3684 fee_proportional_millionths: 0,
3685 excess_data: Vec::new()
3687 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3689 short_channel_id: 3,
3692 cltv_expiry_delta: 0,
3693 htlc_minimum_msat: 0,
3694 htlc_maximum_msat: OptionalField::Present(100_000),
3696 fee_proportional_millionths: 0,
3697 excess_data: Vec::new()
3700 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3701 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3702 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3704 short_channel_id: 5,
3707 cltv_expiry_delta: 0,
3708 htlc_minimum_msat: 0,
3709 htlc_maximum_msat: OptionalField::Present(200_000),
3711 fee_proportional_millionths: 0,
3712 excess_data: Vec::new()
3715 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3716 // Add 100 sats to the capacities of {12, 13}, because these channels
3717 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3718 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3719 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3720 short_channel_id: 12,
3723 cltv_expiry_delta: 0,
3724 htlc_minimum_msat: 0,
3725 htlc_maximum_msat: OptionalField::Present(200_000),
3727 fee_proportional_millionths: 0,
3728 excess_data: Vec::new()
3730 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3731 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3732 short_channel_id: 13,
3735 cltv_expiry_delta: 0,
3736 htlc_minimum_msat: 0,
3737 htlc_maximum_msat: OptionalField::Present(200_000),
3739 fee_proportional_millionths: 0,
3740 excess_data: Vec::new()
3743 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3744 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3745 short_channel_id: 6,
3748 cltv_expiry_delta: 0,
3749 htlc_minimum_msat: 0,
3750 htlc_maximum_msat: OptionalField::Present(100_000),
3752 fee_proportional_millionths: 0,
3753 excess_data: Vec::new()
3755 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3756 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3757 short_channel_id: 11,
3760 cltv_expiry_delta: 0,
3761 htlc_minimum_msat: 0,
3762 htlc_maximum_msat: OptionalField::Present(100_000),
3764 fee_proportional_millionths: 0,
3765 excess_data: Vec::new()
3768 // Path via {node7, node2} is channels {12, 13, 5}.
3769 // We already limited them to 200 sats (they are used twice for 100 sats).
3770 // Nothing to do here.
3773 // Attempt to route more than available results in a failure.
3774 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3775 &our_id, &payment_params, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3776 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3777 } else { panic!(); }
3781 // Now, attempt to route 300 sats (exact amount we can route).
3782 // Our algorithm should provide us with these 3 paths, 100 sats each.
3783 let route = get_route(&our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3784 assert_eq!(route.paths.len(), 3);
3786 let mut total_amount_paid_msat = 0;
3787 for path in &route.paths {
3788 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3789 total_amount_paid_msat += path.last().unwrap().fee_msat;
3791 assert_eq!(total_amount_paid_msat, 300_000);
3797 fn mpp_cheaper_route_test() {
3798 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3799 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3800 let scorer = test_utils::TestScorer::with_penalty(0);
3801 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3803 // This test checks that if we have two cheaper paths and one more expensive path,
3804 // so that liquidity-wise any 2 of 3 combination is sufficient,
3805 // two cheaper paths will be taken.
3806 // These paths have equal available liquidity.
3808 // We need a combination of 3 paths:
3809 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3810 // Note that these paths overlap (channels 5, 12, 13).
3811 // Each path will have 100 sats capacity, those channels which
3812 // are used twice will have 200 sats capacity.
3814 // Disable other potential paths.
3815 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3816 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3817 short_channel_id: 2,
3820 cltv_expiry_delta: 0,
3821 htlc_minimum_msat: 0,
3822 htlc_maximum_msat: OptionalField::Present(100_000),
3824 fee_proportional_millionths: 0,
3825 excess_data: Vec::new()
3827 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3828 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3829 short_channel_id: 7,
3832 cltv_expiry_delta: 0,
3833 htlc_minimum_msat: 0,
3834 htlc_maximum_msat: OptionalField::Present(100_000),
3836 fee_proportional_millionths: 0,
3837 excess_data: Vec::new()
3840 // Path via {node0, node2} is channels {1, 3, 5}.
3841 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3843 short_channel_id: 1,
3846 cltv_expiry_delta: 0,
3847 htlc_minimum_msat: 0,
3848 htlc_maximum_msat: OptionalField::Present(100_000),
3850 fee_proportional_millionths: 0,
3851 excess_data: Vec::new()
3853 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3855 short_channel_id: 3,
3858 cltv_expiry_delta: 0,
3859 htlc_minimum_msat: 0,
3860 htlc_maximum_msat: OptionalField::Present(100_000),
3862 fee_proportional_millionths: 0,
3863 excess_data: Vec::new()
3866 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3867 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3868 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3870 short_channel_id: 5,
3873 cltv_expiry_delta: 0,
3874 htlc_minimum_msat: 0,
3875 htlc_maximum_msat: OptionalField::Present(200_000),
3877 fee_proportional_millionths: 0,
3878 excess_data: Vec::new()
3881 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3882 // Add 100 sats to the capacities of {12, 13}, because these channels
3883 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3884 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3885 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3886 short_channel_id: 12,
3889 cltv_expiry_delta: 0,
3890 htlc_minimum_msat: 0,
3891 htlc_maximum_msat: OptionalField::Present(200_000),
3893 fee_proportional_millionths: 0,
3894 excess_data: Vec::new()
3896 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3897 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3898 short_channel_id: 13,
3901 cltv_expiry_delta: 0,
3902 htlc_minimum_msat: 0,
3903 htlc_maximum_msat: OptionalField::Present(200_000),
3905 fee_proportional_millionths: 0,
3906 excess_data: Vec::new()
3909 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3911 short_channel_id: 6,
3914 cltv_expiry_delta: 0,
3915 htlc_minimum_msat: 0,
3916 htlc_maximum_msat: OptionalField::Present(100_000),
3917 fee_base_msat: 1_000,
3918 fee_proportional_millionths: 0,
3919 excess_data: Vec::new()
3921 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3923 short_channel_id: 11,
3926 cltv_expiry_delta: 0,
3927 htlc_minimum_msat: 0,
3928 htlc_maximum_msat: OptionalField::Present(100_000),
3930 fee_proportional_millionths: 0,
3931 excess_data: Vec::new()
3934 // Path via {node7, node2} is channels {12, 13, 5}.
3935 // We already limited them to 200 sats (they are used twice for 100 sats).
3936 // Nothing to do here.
3939 // Now, attempt to route 180 sats.
3940 // Our algorithm should provide us with these 2 paths.
3941 let route = get_route(&our_id, &payment_params, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3942 assert_eq!(route.paths.len(), 2);
3944 let mut total_value_transferred_msat = 0;
3945 let mut total_paid_msat = 0;
3946 for path in &route.paths {
3947 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3948 total_value_transferred_msat += path.last().unwrap().fee_msat;
3950 total_paid_msat += hop.fee_msat;
3953 // If we paid fee, this would be higher.
3954 assert_eq!(total_value_transferred_msat, 180_000);
3955 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3956 assert_eq!(total_fees_paid, 0);
3961 fn fees_on_mpp_route_test() {
3962 // This test makes sure that MPP algorithm properly takes into account
3963 // fees charged on the channels, by making the fees impactful:
3964 // if the fee is not properly accounted for, the behavior is different.
3965 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3966 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3967 let scorer = test_utils::TestScorer::with_penalty(0);
3968 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3970 // We need a route consisting of 2 paths:
3971 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3972 // We will route 200 sats, Each path will have 100 sats capacity.
3974 // This test is not particularly stable: e.g.,
3975 // there's a way to route via {node0, node2, node4}.
3976 // It works while pathfinding is deterministic, but can be broken otherwise.
3977 // It's fine to ignore this concern for now.
3979 // Disable other potential paths.
3980 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3981 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3982 short_channel_id: 2,
3985 cltv_expiry_delta: 0,
3986 htlc_minimum_msat: 0,
3987 htlc_maximum_msat: OptionalField::Present(100_000),
3989 fee_proportional_millionths: 0,
3990 excess_data: Vec::new()
3993 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3995 short_channel_id: 7,
3998 cltv_expiry_delta: 0,
3999 htlc_minimum_msat: 0,
4000 htlc_maximum_msat: OptionalField::Present(100_000),
4002 fee_proportional_millionths: 0,
4003 excess_data: Vec::new()
4006 // Path via {node0, node2} is channels {1, 3, 5}.
4007 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4009 short_channel_id: 1,
4012 cltv_expiry_delta: 0,
4013 htlc_minimum_msat: 0,
4014 htlc_maximum_msat: OptionalField::Present(100_000),
4016 fee_proportional_millionths: 0,
4017 excess_data: Vec::new()
4019 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4021 short_channel_id: 3,
4024 cltv_expiry_delta: 0,
4025 htlc_minimum_msat: 0,
4026 htlc_maximum_msat: OptionalField::Present(100_000),
4028 fee_proportional_millionths: 0,
4029 excess_data: Vec::new()
4032 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4033 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4034 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4035 short_channel_id: 5,
4038 cltv_expiry_delta: 0,
4039 htlc_minimum_msat: 0,
4040 htlc_maximum_msat: OptionalField::Present(100_000),
4042 fee_proportional_millionths: 0,
4043 excess_data: Vec::new()
4046 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4047 // All channels should be 100 sats capacity. But for the fee experiment,
4048 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4049 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4050 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4051 // so no matter how large are other channels,
4052 // the whole path will be limited by 100 sats with just these 2 conditions:
4053 // - channel 12 capacity is 250 sats
4054 // - fee for channel 6 is 150 sats
4055 // Let's test this by enforcing these 2 conditions and removing other limits.
4056 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4058 short_channel_id: 12,
4061 cltv_expiry_delta: 0,
4062 htlc_minimum_msat: 0,
4063 htlc_maximum_msat: OptionalField::Present(250_000),
4065 fee_proportional_millionths: 0,
4066 excess_data: Vec::new()
4068 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4070 short_channel_id: 13,
4073 cltv_expiry_delta: 0,
4074 htlc_minimum_msat: 0,
4075 htlc_maximum_msat: OptionalField::Absent,
4077 fee_proportional_millionths: 0,
4078 excess_data: Vec::new()
4081 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4082 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4083 short_channel_id: 6,
4086 cltv_expiry_delta: 0,
4087 htlc_minimum_msat: 0,
4088 htlc_maximum_msat: OptionalField::Absent,
4089 fee_base_msat: 150_000,
4090 fee_proportional_millionths: 0,
4091 excess_data: Vec::new()
4093 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4094 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4095 short_channel_id: 11,
4098 cltv_expiry_delta: 0,
4099 htlc_minimum_msat: 0,
4100 htlc_maximum_msat: OptionalField::Absent,
4102 fee_proportional_millionths: 0,
4103 excess_data: Vec::new()
4107 // Attempt to route more than available results in a failure.
4108 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4109 &our_id, &payment_params, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4110 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4111 } else { panic!(); }
4115 // Now, attempt to route 200 sats (exact amount we can route).
4116 let route = get_route(&our_id, &payment_params, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4117 assert_eq!(route.paths.len(), 2);
4119 let mut total_amount_paid_msat = 0;
4120 for path in &route.paths {
4121 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4122 total_amount_paid_msat += path.last().unwrap().fee_msat;
4124 assert_eq!(total_amount_paid_msat, 200_000);
4125 assert_eq!(route.get_total_fees(), 150_000);
4130 fn mpp_with_last_hops() {
4131 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4132 // via a single last-hop route hint, we'd fail to route if we first collected routes
4133 // totaling close but not quite enough to fund the full payment.
4135 // This was because we considered last-hop hints to have exactly the sought payment amount
4136 // instead of the amount we were trying to collect, needlessly limiting our path searching
4137 // at the very first hop.
4139 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4140 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4141 // to only have the remaining to-collect amount in available liquidity.
4143 // This bug appeared in production in some specific channel configurations.
4144 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4145 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4146 let scorer = test_utils::TestScorer::with_penalty(0);
4147 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4148 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4149 src_node_id: nodes[2],
4150 short_channel_id: 42,
4151 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4152 cltv_expiry_delta: 42,
4153 htlc_minimum_msat: None,
4154 htlc_maximum_msat: None,
4157 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4158 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4159 // would first use the no-fee route and then fail to find a path along the second route as
4160 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4161 // under 5% of our payment amount.
4162 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4163 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4164 short_channel_id: 1,
4167 cltv_expiry_delta: (5 << 4) | 5,
4168 htlc_minimum_msat: 0,
4169 htlc_maximum_msat: OptionalField::Present(99_000),
4170 fee_base_msat: u32::max_value(),
4171 fee_proportional_millionths: u32::max_value(),
4172 excess_data: Vec::new()
4174 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4175 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4176 short_channel_id: 2,
4179 cltv_expiry_delta: (5 << 4) | 3,
4180 htlc_minimum_msat: 0,
4181 htlc_maximum_msat: OptionalField::Present(99_000),
4182 fee_base_msat: u32::max_value(),
4183 fee_proportional_millionths: u32::max_value(),
4184 excess_data: Vec::new()
4186 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4188 short_channel_id: 4,
4191 cltv_expiry_delta: (4 << 4) | 1,
4192 htlc_minimum_msat: 0,
4193 htlc_maximum_msat: OptionalField::Absent,
4195 fee_proportional_millionths: 0,
4196 excess_data: Vec::new()
4198 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4200 short_channel_id: 13,
4202 flags: 0|2, // Channel disabled
4203 cltv_expiry_delta: (13 << 4) | 1,
4204 htlc_minimum_msat: 0,
4205 htlc_maximum_msat: OptionalField::Absent,
4207 fee_proportional_millionths: 2000000,
4208 excess_data: Vec::new()
4211 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4213 let route = get_route(&our_id, &payment_params, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4214 assert_eq!(route.paths.len(), 2);
4215 // Paths are somewhat randomly ordered, but:
4216 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4217 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4218 assert_eq!(route.paths[0][0].short_channel_id, 2);
4219 assert_eq!(route.paths[0][0].fee_msat, 1);
4220 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4221 assert_eq!(route.paths[1][0].short_channel_id, 1);
4222 assert_eq!(route.paths[1][0].fee_msat, 0);
4223 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4224 assert_eq!(route.get_total_fees(), 1);
4225 assert_eq!(route.get_total_amount(), 100_000);
4229 fn drop_lowest_channel_mpp_route_test() {
4230 // This test checks that low-capacity channel is dropped when after
4231 // path finding we realize that we found more capacity than we need.
4232 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4233 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4234 let scorer = test_utils::TestScorer::with_penalty(0);
4235 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4237 // We need a route consisting of 3 paths:
4238 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4240 // The first and the second paths should be sufficient, but the third should be
4241 // cheaper, so that we select it but drop later.
4243 // First, we set limits on these (previously unlimited) channels.
4244 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4246 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4247 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4248 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4249 short_channel_id: 1,
4252 cltv_expiry_delta: 0,
4253 htlc_minimum_msat: 0,
4254 htlc_maximum_msat: OptionalField::Present(100_000),
4256 fee_proportional_millionths: 0,
4257 excess_data: Vec::new()
4259 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4261 short_channel_id: 3,
4264 cltv_expiry_delta: 0,
4265 htlc_minimum_msat: 0,
4266 htlc_maximum_msat: OptionalField::Present(50_000),
4268 fee_proportional_millionths: 0,
4269 excess_data: Vec::new()
4272 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4273 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4275 short_channel_id: 12,
4278 cltv_expiry_delta: 0,
4279 htlc_minimum_msat: 0,
4280 htlc_maximum_msat: OptionalField::Present(60_000),
4282 fee_proportional_millionths: 0,
4283 excess_data: Vec::new()
4285 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4287 short_channel_id: 13,
4290 cltv_expiry_delta: 0,
4291 htlc_minimum_msat: 0,
4292 htlc_maximum_msat: OptionalField::Present(60_000),
4294 fee_proportional_millionths: 0,
4295 excess_data: Vec::new()
4298 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4299 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4301 short_channel_id: 2,
4304 cltv_expiry_delta: 0,
4305 htlc_minimum_msat: 0,
4306 htlc_maximum_msat: OptionalField::Present(20_000),
4308 fee_proportional_millionths: 0,
4309 excess_data: Vec::new()
4311 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4312 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4313 short_channel_id: 4,
4316 cltv_expiry_delta: 0,
4317 htlc_minimum_msat: 0,
4318 htlc_maximum_msat: OptionalField::Present(20_000),
4320 fee_proportional_millionths: 0,
4321 excess_data: Vec::new()
4325 // Attempt to route more than available results in a failure.
4326 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4327 &our_id, &payment_params, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4328 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4329 } else { panic!(); }
4333 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4334 // Our algorithm should provide us with these 3 paths.
4335 let route = get_route(&our_id, &payment_params, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4336 assert_eq!(route.paths.len(), 3);
4337 let mut total_amount_paid_msat = 0;
4338 for path in &route.paths {
4339 assert_eq!(path.len(), 2);
4340 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4341 total_amount_paid_msat += path.last().unwrap().fee_msat;
4343 assert_eq!(total_amount_paid_msat, 125_000);
4347 // Attempt to route without the last small cheap channel
4348 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4349 assert_eq!(route.paths.len(), 2);
4350 let mut total_amount_paid_msat = 0;
4351 for path in &route.paths {
4352 assert_eq!(path.len(), 2);
4353 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4354 total_amount_paid_msat += path.last().unwrap().fee_msat;
4356 assert_eq!(total_amount_paid_msat, 90_000);
4361 fn min_criteria_consistency() {
4362 // Test that we don't use an inconsistent metric between updating and walking nodes during
4363 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4364 // was updated with a different criterion from the heap sorting, resulting in loops in
4365 // calculated paths. We test for that specific case here.
4367 // We construct a network that looks like this:
4369 // node2 -1(3)2- node3
4373 // node1 -1(5)2- node4 -1(1)2- node6
4379 // We create a loop on the side of our real path - our destination is node 6, with a
4380 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4381 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4382 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4383 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4384 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4385 // "previous hop" being set to node 3, creating a loop in the path.
4386 let secp_ctx = Secp256k1::new();
4387 let logger = Arc::new(test_utils::TestLogger::new());
4388 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4389 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4390 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4391 let scorer = test_utils::TestScorer::with_penalty(0);
4392 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4394 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4395 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4397 short_channel_id: 6,
4400 cltv_expiry_delta: (6 << 4) | 0,
4401 htlc_minimum_msat: 0,
4402 htlc_maximum_msat: OptionalField::Absent,
4404 fee_proportional_millionths: 0,
4405 excess_data: Vec::new()
4407 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4409 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4412 short_channel_id: 5,
4415 cltv_expiry_delta: (5 << 4) | 0,
4416 htlc_minimum_msat: 0,
4417 htlc_maximum_msat: OptionalField::Absent,
4419 fee_proportional_millionths: 0,
4420 excess_data: Vec::new()
4422 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4424 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4425 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4427 short_channel_id: 4,
4430 cltv_expiry_delta: (4 << 4) | 0,
4431 htlc_minimum_msat: 0,
4432 htlc_maximum_msat: OptionalField::Absent,
4434 fee_proportional_millionths: 0,
4435 excess_data: Vec::new()
4437 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4439 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4440 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4442 short_channel_id: 3,
4445 cltv_expiry_delta: (3 << 4) | 0,
4446 htlc_minimum_msat: 0,
4447 htlc_maximum_msat: OptionalField::Absent,
4449 fee_proportional_millionths: 0,
4450 excess_data: Vec::new()
4452 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4454 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4455 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4457 short_channel_id: 2,
4460 cltv_expiry_delta: (2 << 4) | 0,
4461 htlc_minimum_msat: 0,
4462 htlc_maximum_msat: OptionalField::Absent,
4464 fee_proportional_millionths: 0,
4465 excess_data: Vec::new()
4468 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4469 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4470 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4471 short_channel_id: 1,
4474 cltv_expiry_delta: (1 << 4) | 0,
4475 htlc_minimum_msat: 100,
4476 htlc_maximum_msat: OptionalField::Absent,
4478 fee_proportional_millionths: 0,
4479 excess_data: Vec::new()
4481 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4484 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4485 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4486 assert_eq!(route.paths.len(), 1);
4487 assert_eq!(route.paths[0].len(), 3);
4489 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4490 assert_eq!(route.paths[0][0].short_channel_id, 6);
4491 assert_eq!(route.paths[0][0].fee_msat, 100);
4492 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4493 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4494 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4496 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4497 assert_eq!(route.paths[0][1].short_channel_id, 5);
4498 assert_eq!(route.paths[0][1].fee_msat, 0);
4499 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4500 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4501 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4503 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4504 assert_eq!(route.paths[0][2].short_channel_id, 1);
4505 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4506 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4507 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4508 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4514 fn exact_fee_liquidity_limit() {
4515 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4516 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4517 // we calculated fees on a higher value, resulting in us ignoring such paths.
4518 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4519 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4520 let scorer = test_utils::TestScorer::with_penalty(0);
4521 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4523 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4525 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4527 short_channel_id: 2,
4530 cltv_expiry_delta: 0,
4531 htlc_minimum_msat: 0,
4532 htlc_maximum_msat: OptionalField::Present(85_000),
4534 fee_proportional_millionths: 0,
4535 excess_data: Vec::new()
4538 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4539 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4540 short_channel_id: 12,
4543 cltv_expiry_delta: (4 << 4) | 1,
4544 htlc_minimum_msat: 0,
4545 htlc_maximum_msat: OptionalField::Present(270_000),
4547 fee_proportional_millionths: 1000000,
4548 excess_data: Vec::new()
4552 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4553 // 200% fee charged channel 13 in the 1-to-2 direction.
4554 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4555 assert_eq!(route.paths.len(), 1);
4556 assert_eq!(route.paths[0].len(), 2);
4558 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4559 assert_eq!(route.paths[0][0].short_channel_id, 12);
4560 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4561 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4562 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4563 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4565 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4566 assert_eq!(route.paths[0][1].short_channel_id, 13);
4567 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4568 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4569 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4570 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4575 fn htlc_max_reduction_below_min() {
4576 // Test that if, while walking the graph, we reduce the value being sent to meet an
4577 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4578 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4579 // resulting in us thinking there is no possible path, even if other paths exist.
4580 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4581 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4582 let scorer = test_utils::TestScorer::with_penalty(0);
4583 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4585 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4586 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4587 // then try to send 90_000.
4588 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4589 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4590 short_channel_id: 2,
4593 cltv_expiry_delta: 0,
4594 htlc_minimum_msat: 0,
4595 htlc_maximum_msat: OptionalField::Present(80_000),
4597 fee_proportional_millionths: 0,
4598 excess_data: Vec::new()
4600 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4601 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4602 short_channel_id: 4,
4605 cltv_expiry_delta: (4 << 4) | 1,
4606 htlc_minimum_msat: 90_000,
4607 htlc_maximum_msat: OptionalField::Absent,
4609 fee_proportional_millionths: 0,
4610 excess_data: Vec::new()
4614 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4615 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4616 // expensive) channels 12-13 path.
4617 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4618 assert_eq!(route.paths.len(), 1);
4619 assert_eq!(route.paths[0].len(), 2);
4621 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4622 assert_eq!(route.paths[0][0].short_channel_id, 12);
4623 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4624 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4625 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4626 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4628 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4629 assert_eq!(route.paths[0][1].short_channel_id, 13);
4630 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4631 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4632 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4633 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4638 fn multiple_direct_first_hops() {
4639 // Previously we'd only ever considered one first hop path per counterparty.
4640 // However, as we don't restrict users to one channel per peer, we really need to support
4641 // looking at all first hop paths.
4642 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4643 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4644 // route over multiple channels with the same first hop.
4645 let secp_ctx = Secp256k1::new();
4646 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4647 let logger = Arc::new(test_utils::TestLogger::new());
4648 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4649 let scorer = test_utils::TestScorer::with_penalty(0);
4650 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4653 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4654 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4655 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4656 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4657 assert_eq!(route.paths.len(), 1);
4658 assert_eq!(route.paths[0].len(), 1);
4660 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4661 assert_eq!(route.paths[0][0].short_channel_id, 3);
4662 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4665 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4666 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4667 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4668 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4669 assert_eq!(route.paths.len(), 2);
4670 assert_eq!(route.paths[0].len(), 1);
4671 assert_eq!(route.paths[1].len(), 1);
4673 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4674 assert_eq!(route.paths[0][0].short_channel_id, 3);
4675 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4677 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4678 assert_eq!(route.paths[1][0].short_channel_id, 2);
4679 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4684 fn prefers_shorter_route_with_higher_fees() {
4685 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4686 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4687 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4689 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4690 let scorer = test_utils::TestScorer::with_penalty(0);
4691 let route = get_route(
4692 &our_id, &payment_params, &network_graph, None, 100, 42,
4693 Arc::clone(&logger), &scorer
4695 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4697 assert_eq!(route.get_total_fees(), 100);
4698 assert_eq!(route.get_total_amount(), 100);
4699 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4701 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4702 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4703 let scorer = test_utils::TestScorer::with_penalty(100);
4704 let route = get_route(
4705 &our_id, &payment_params, &network_graph, None, 100, 42,
4706 Arc::clone(&logger), &scorer
4708 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4710 assert_eq!(route.get_total_fees(), 300);
4711 assert_eq!(route.get_total_amount(), 100);
4712 assert_eq!(path, vec![2, 4, 7, 10]);
4715 struct BadChannelScorer {
4716 short_channel_id: u64,
4720 impl Writeable for BadChannelScorer {
4721 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4723 impl Score for BadChannelScorer {
4724 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4725 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4728 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4729 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4732 struct BadNodeScorer {
4737 impl Writeable for BadNodeScorer {
4738 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4741 impl Score for BadNodeScorer {
4742 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4743 if *target == self.node_id { u64::max_value() } else { 0 }
4746 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4747 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4751 fn avoids_routing_through_bad_channels_and_nodes() {
4752 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4753 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4754 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4756 // A path to nodes[6] exists when no penalties are applied to any channel.
4757 let scorer = test_utils::TestScorer::with_penalty(0);
4758 let route = get_route(
4759 &our_id, &payment_params, &network_graph, None, 100, 42,
4760 Arc::clone(&logger), &scorer
4762 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4764 assert_eq!(route.get_total_fees(), 100);
4765 assert_eq!(route.get_total_amount(), 100);
4766 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4768 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4769 let scorer = BadChannelScorer { short_channel_id: 6 };
4770 let route = get_route(
4771 &our_id, &payment_params, &network_graph, None, 100, 42,
4772 Arc::clone(&logger), &scorer
4774 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4776 assert_eq!(route.get_total_fees(), 300);
4777 assert_eq!(route.get_total_amount(), 100);
4778 assert_eq!(path, vec![2, 4, 7, 10]);
4780 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4781 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4783 &our_id, &payment_params, &network_graph, None, 100, 42,
4784 Arc::clone(&logger), &scorer
4786 Err(LightningError { err, .. } ) => {
4787 assert_eq!(err, "Failed to find a path to the given destination");
4789 Ok(_) => panic!("Expected error"),
4794 fn total_fees_single_path() {
4798 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4799 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4800 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4803 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4804 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4805 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4808 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4809 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4810 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4813 payment_params: None,
4816 assert_eq!(route.get_total_fees(), 250);
4817 assert_eq!(route.get_total_amount(), 225);
4821 fn total_fees_multi_path() {
4825 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4826 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4827 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4830 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4831 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4832 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4836 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4837 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4838 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4841 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4842 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4843 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4846 payment_params: None,
4849 assert_eq!(route.get_total_fees(), 200);
4850 assert_eq!(route.get_total_amount(), 300);
4854 fn total_empty_route_no_panic() {
4855 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4856 // would both panic if the route was completely empty. We test to ensure they return 0
4857 // here, even though its somewhat nonsensical as a route.
4858 let route = Route { paths: Vec::new(), payment_params: None };
4860 assert_eq!(route.get_total_fees(), 0);
4861 assert_eq!(route.get_total_amount(), 0);
4865 fn limits_total_cltv_delta() {
4866 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4867 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4869 let scorer = test_utils::TestScorer::with_penalty(0);
4871 // Make sure that generally there is at least one route available
4872 let feasible_max_total_cltv_delta = 1008;
4873 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4874 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
4875 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
4876 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4877 assert_ne!(path.len(), 0);
4879 // But not if we exclude all paths on the basis of their accumulated CLTV delta
4880 let fail_max_total_cltv_delta = 23;
4881 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4882 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
4883 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer)
4885 Err(LightningError { err, .. } ) => {
4886 assert_eq!(err, "Failed to find a path to the given destination");
4888 Ok(_) => panic!("Expected error"),
4892 #[cfg(not(feature = "no-std"))]
4893 pub(super) fn random_init_seed() -> u64 {
4894 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4895 use core::hash::{BuildHasher, Hasher};
4896 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4897 println!("Using seed of {}", seed);
4900 #[cfg(not(feature = "no-std"))]
4901 use util::ser::Readable;
4904 #[cfg(not(feature = "no-std"))]
4905 fn generate_routes() {
4906 let mut d = match super::test_utils::get_route_file() {
4913 let graph = NetworkGraph::read(&mut d).unwrap();
4915 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4916 let mut seed = random_init_seed() as usize;
4917 let nodes = graph.read_only().nodes().clone();
4918 'load_endpoints: for _ in 0..10 {
4920 seed = seed.overflowing_mul(0xdeadbeef).0;
4921 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4922 seed = seed.overflowing_mul(0xdeadbeef).0;
4923 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4924 let payment_params = PaymentParameters::from_node_id(dst);
4925 let amt = seed as u64 % 200_000_000;
4926 let params = ProbabilisticScoringParameters::default();
4927 let scorer = ProbabilisticScorer::new(params, &graph);
4928 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4929 continue 'load_endpoints;
4936 #[cfg(not(feature = "no-std"))]
4937 fn generate_routes_mpp() {
4938 let mut d = match super::test_utils::get_route_file() {
4945 let graph = NetworkGraph::read(&mut d).unwrap();
4947 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4948 let mut seed = random_init_seed() as usize;
4949 let nodes = graph.read_only().nodes().clone();
4950 'load_endpoints: for _ in 0..10 {
4952 seed = seed.overflowing_mul(0xdeadbeef).0;
4953 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4954 seed = seed.overflowing_mul(0xdeadbeef).0;
4955 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4956 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
4957 let amt = seed as u64 % 200_000_000;
4958 let params = ProbabilisticScoringParameters::default();
4959 let scorer = ProbabilisticScorer::new(params, &graph);
4960 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4961 continue 'load_endpoints;
4968 #[cfg(all(test, not(feature = "no-std")))]
4969 pub(crate) mod test_utils {
4971 /// Tries to open a network graph file, or panics with a URL to fetch it.
4972 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4973 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4974 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4975 .or_else(|_| { // Fall back to guessing based on the binary location
4976 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4977 let mut path = std::env::current_exe().unwrap();
4978 path.pop(); // lightning-...
4980 path.pop(); // debug
4981 path.pop(); // target
4982 path.push("lightning");
4983 path.push("net_graph-2021-05-31.bin");
4984 eprintln!("{}", path.to_str().unwrap());
4987 .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");
4988 #[cfg(require_route_graph_test)]
4989 return Ok(res.unwrap());
4990 #[cfg(not(require_route_graph_test))]
4995 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4998 use bitcoin::hashes::Hash;
4999 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5000 use chain::transaction::OutPoint;
5001 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5002 use ln::features::{InitFeatures, InvoiceFeatures};
5003 use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5004 use util::logger::{Logger, Record};
5008 struct DummyLogger {}
5009 impl Logger for DummyLogger {
5010 fn log(&self, _record: &Record) {}
5013 fn read_network_graph() -> NetworkGraph {
5014 let mut d = test_utils::get_route_file().unwrap();
5015 NetworkGraph::read(&mut d).unwrap()
5018 fn payer_pubkey() -> PublicKey {
5019 let secp_ctx = Secp256k1::new();
5020 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5024 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5026 channel_id: [0; 32],
5027 counterparty: ChannelCounterparty {
5028 features: InitFeatures::known(),
5030 unspendable_punishment_reserve: 0,
5031 forwarding_info: None,
5033 funding_txo: Some(OutPoint {
5034 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5036 short_channel_id: Some(1),
5037 channel_value_satoshis: 10_000_000,
5039 balance_msat: 10_000_000,
5040 outbound_capacity_msat: 10_000_000,
5041 inbound_capacity_msat: 0,
5042 unspendable_punishment_reserve: None,
5043 confirmations_required: None,
5044 force_close_spend_delay: None,
5046 is_funding_locked: true,
5053 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5054 let network_graph = read_network_graph();
5055 let scorer = FixedPenaltyScorer::with_penalty(0);
5056 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5060 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5061 let network_graph = read_network_graph();
5062 let scorer = FixedPenaltyScorer::with_penalty(0);
5063 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5067 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5068 let network_graph = read_network_graph();
5069 let scorer = Scorer::default();
5070 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5074 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5075 let network_graph = read_network_graph();
5076 let scorer = Scorer::default();
5077 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5081 fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5082 let network_graph = read_network_graph();
5083 let params = ProbabilisticScoringParameters::default();
5084 let scorer = ProbabilisticScorer::new(params, &network_graph);
5085 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5089 fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5090 let network_graph = read_network_graph();
5091 let params = ProbabilisticScoringParameters::default();
5092 let scorer = ProbabilisticScorer::new(params, &network_graph);
5093 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5096 fn generate_routes<S: Score>(
5097 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5099 let nodes = graph.read_only().nodes().clone();
5100 let payer = payer_pubkey();
5102 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5103 let mut routes = Vec::new();
5104 let mut route_endpoints = Vec::new();
5105 let mut seed: usize = 0xdeadbeef;
5106 'load_endpoints: for _ in 0..100 {
5109 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5111 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5112 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5113 let first_hop = first_hop(src);
5114 let amt = seed as u64 % 1_000_000;
5115 if let Ok(route) = get_route(&payer, ¶ms, &graph, Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer) {
5117 route_endpoints.push((first_hop, params, amt));
5118 continue 'load_endpoints;
5123 // ...and seed the scorer with success and failure data...
5124 for route in routes {
5125 let amount = route.get_total_amount();
5126 if amount < 250_000 {
5127 for path in route.paths {
5128 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5130 } else if amount > 750_000 {
5131 for path in route.paths {
5132 let short_channel_id = path[path.len() / 2].short_channel_id;
5133 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5138 // ...then benchmark finding paths between the nodes we learned.
5141 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5142 assert!(get_route(&payer, params, &graph, Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer).is_ok());