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::{ChannelInfo, DirectedChannelInfo, DirectionalChannelInfo, 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 `payee` 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 payee: Option<Payee>,
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.payee, 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 payee = None;
145 read_tlv_fields!(reader, {
148 Ok(Route { paths, payee })
152 /// Parameters needed to find a [`Route`] for paying a [`Payee`].
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 recipient of the failed payment path.
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, payee, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// The recipient of a payment.
177 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
179 /// The node id of the payee.
180 pub pubkey: PublicKey,
182 /// Features supported by the payee.
184 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
185 /// does not contain any features.
187 /// [`for_keysend`]: Self::for_keysend
188 pub features: Option<InvoiceFeatures>,
190 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
191 pub route_hints: Vec<RouteHint>,
193 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
194 pub expiry_time: Option<u64>,
197 impl_writeable_tlv_based!(Payee, {
198 (0, pubkey, required),
199 (2, features, option),
200 (4, route_hints, vec_type),
201 (6, expiry_time, option),
205 /// Creates a payee with the node id of the given `pubkey`.
206 pub fn from_node_id(pubkey: PublicKey) -> Self {
215 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
216 pub fn for_keysend(pubkey: PublicKey) -> Self {
217 Self::from_node_id(pubkey).with_features(InvoiceFeatures::for_keysend())
220 /// Includes the payee's features.
222 /// (C-not exported) since bindings don't support move semantics
223 pub fn with_features(self, features: InvoiceFeatures) -> Self {
224 Self { features: Some(features), ..self }
227 /// Includes hints for routing to the payee.
229 /// (C-not exported) since bindings don't support move semantics
230 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
231 Self { route_hints, ..self }
234 /// Includes a payment expiration in seconds relative to the UNIX epoch.
236 /// (C-not exported) since bindings don't support move semantics
237 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
238 Self { expiry_time: Some(expiry_time), ..self }
242 /// A list of hops along a payment path terminating with a channel to the recipient.
243 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
244 pub struct RouteHint(pub Vec<RouteHintHop>);
247 impl Writeable for RouteHint {
248 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
249 (self.0.len() as u64).write(writer)?;
250 for hop in self.0.iter() {
257 impl Readable for RouteHint {
258 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
259 let hop_count: u64 = Readable::read(reader)?;
260 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
261 for _ in 0..hop_count {
262 hops.push(Readable::read(reader)?);
268 /// A channel descriptor for a hop along a payment path.
269 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
270 pub struct RouteHintHop {
271 /// The node_id of the non-target end of the route
272 pub src_node_id: PublicKey,
273 /// The short_channel_id of this channel
274 pub short_channel_id: u64,
275 /// The fees which must be paid to use this channel
276 pub fees: RoutingFees,
277 /// The difference in CLTV values between this node and the next node.
278 pub cltv_expiry_delta: u16,
279 /// The minimum value, in msat, which must be relayed to the next hop.
280 pub htlc_minimum_msat: Option<u64>,
281 /// The maximum value in msat available for routing with a single HTLC.
282 pub htlc_maximum_msat: Option<u64>,
285 impl_writeable_tlv_based!(RouteHintHop, {
286 (0, src_node_id, required),
287 (1, htlc_minimum_msat, option),
288 (2, short_channel_id, required),
289 (3, htlc_maximum_msat, option),
291 (6, cltv_expiry_delta, required),
294 #[derive(Eq, PartialEq)]
295 struct RouteGraphNode {
297 lowest_fee_to_peer_through_node: u64,
298 lowest_fee_to_node: u64,
299 // The maximum value a yet-to-be-constructed payment path might flow through this node.
300 // This value is upper-bounded by us by:
301 // - how much is needed for a path being constructed
302 // - how much value can channels following this node (up to the destination) can contribute,
303 // considering their capacity and fees
304 value_contribution_msat: u64,
305 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
306 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
307 path_htlc_minimum_msat: u64,
308 /// All penalties incurred from this hop on the way to the destination, as calculated using
310 path_penalty_msat: u64,
313 impl cmp::Ord for RouteGraphNode {
314 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
315 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
316 .checked_add(other.path_penalty_msat)
317 .unwrap_or_else(|| u64::max_value());
318 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
319 .checked_add(self.path_penalty_msat)
320 .unwrap_or_else(|| u64::max_value());
321 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
325 impl cmp::PartialOrd for RouteGraphNode {
326 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
327 Some(self.cmp(other))
331 /// A wrapper around the various hop representations.
333 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
334 enum CandidateRouteHop<'a> {
335 /// A hop from the payer to the next hop to the payee, where the outbound liquidity is known.
337 details: &'a ChannelDetails,
339 /// A hop found in the [`NetworkGraph`], where the channel capacity may or may not be known.
341 short_channel_id: u64,
342 channel: &'a ChannelInfo,
343 direction: &'a DirectionalChannelInfo,
345 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
347 hint: &'a RouteHintHop,
351 impl<'a> CandidateRouteHop<'a> {
352 fn short_channel_id(&self) -> u64 {
354 CandidateRouteHop::FirstHop { details } => details.short_channel_id.unwrap(),
355 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
356 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
360 fn features(&self) -> ChannelFeatures {
362 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
363 CandidateRouteHop::PublicHop { channel, .. } => channel.features.clone(),
364 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
368 fn cltv_expiry_delta(&self) -> u32 {
370 CandidateRouteHop::FirstHop { .. } => 0,
371 CandidateRouteHop::PublicHop { direction, .. } => direction.cltv_expiry_delta as u32,
372 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
376 fn htlc_minimum_msat(&self) -> u64 {
378 CandidateRouteHop::FirstHop { .. } => 0,
379 CandidateRouteHop::PublicHop { direction, .. } => direction.htlc_minimum_msat,
380 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
384 fn fees(&self) -> RoutingFees {
386 CandidateRouteHop::FirstHop { .. } => RoutingFees {
387 base_msat: 0, proportional_millionths: 0,
389 CandidateRouteHop::PublicHop { direction, .. } => direction.fees,
390 CandidateRouteHop::PrivateHop { hint } => hint.fees,
394 fn effective_capacity(&self) -> EffectiveCapacity {
396 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
397 liquidity_msast: details.outbound_capacity_msat,
399 CandidateRouteHop::PublicHop { channel, direction, .. } => {
400 DirectedChannelInfo::effective_capacity_from_parts(channel, Some(direction))
402 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
407 /// It's useful to keep track of the hops associated with the fees required to use them,
408 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
409 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
410 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
411 #[derive(Clone, Debug)]
412 struct PathBuildingHop {
413 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
414 // Note that node_features is calculated separately after our initial graph walk.
416 short_channel_id: u64,
417 channel_features: ChannelFeatures,
419 cltv_expiry_delta: u32,
421 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
422 src_lowest_inbound_fees: RoutingFees,
423 /// Fees of the channel used in this hop.
424 channel_fees: RoutingFees,
425 /// All the fees paid *after* this channel on the way to the destination
426 next_hops_fee_msat: u64,
427 /// Fee paid for the use of the current channel (see channel_fees).
428 /// The value will be actually deducted from the counterparty balance on the previous link.
429 hop_use_fee_msat: u64,
430 /// Used to compare channels when choosing the for routing.
431 /// Includes paying for the use of a hop and the following hops, as well as
432 /// an estimated cost of reaching this hop.
433 /// Might get stale when fees are recomputed. Primarily for internal use.
435 /// This is useful for update_value_and_recompute_fees to make sure
436 /// we don't fall below the minimum. Should not be updated manually and
437 /// generally should not be accessed.
438 htlc_minimum_msat: u64,
439 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
440 /// walk and may be invalid thereafter.
441 path_htlc_minimum_msat: u64,
442 /// All penalties incurred from this channel on the way to the destination, as calculated using
444 path_penalty_msat: u64,
445 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
446 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
447 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
448 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
449 /// avoid processing them again.
451 #[cfg(any(test, feature = "fuzztarget"))]
452 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
453 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
454 // value_contribution_msat, which requires tracking it here. See comments below where it is
455 // used for more info.
456 value_contribution_msat: u64,
459 // Instantiated with a list of hops with correct data in them collected during path finding,
460 // an instance of this struct should be further modified only via given methods.
463 hops: Vec<(PathBuildingHop, NodeFeatures)>,
467 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
468 fn get_value_msat(&self) -> u64 {
469 self.hops.last().unwrap().0.fee_msat
472 fn get_total_fee_paid_msat(&self) -> u64 {
473 if self.hops.len() < 1 {
477 // Can't use next_hops_fee_msat because it gets outdated.
478 for (i, (hop, _)) in self.hops.iter().enumerate() {
479 if i != self.hops.len() - 1 {
480 result += hop.fee_msat;
486 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
487 // to change fees may result in an inconsistency.
489 // Sometimes we call this function right after constructing a path which is inconsistent in
490 // that it the value being transferred has decreased while we were doing path finding, leading
491 // to the fees being paid not lining up with the actual limits.
493 // Note that this function is not aware of the available_liquidity limit, and thus does not
494 // support increasing the value being transferred.
495 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
496 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
498 let mut total_fee_paid_msat = 0 as u64;
499 for i in (0..self.hops.len()).rev() {
500 let last_hop = i == self.hops.len() - 1;
502 // For non-last-hop, this value will represent the fees paid on the current hop. It
503 // will consist of the fees for the use of the next hop, and extra fees to match
504 // htlc_minimum_msat of the current channel. Last hop is handled separately.
505 let mut cur_hop_fees_msat = 0;
507 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
510 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
511 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
512 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
513 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
514 // set it too high just to maliciously take more fees by exploiting this
515 // match htlc_minimum_msat logic.
516 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
517 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
518 // Note that there is a risk that *previous hops* (those closer to us, as we go
519 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
521 // This might make us end up with a broken route, although this should be super-rare
522 // in practice, both because of how healthy channels look like, and how we pick
523 // channels in add_entry.
524 // Also, this can't be exploited more heavily than *announce a free path and fail
526 cur_hop_transferred_amount_msat += extra_fees_msat;
527 total_fee_paid_msat += extra_fees_msat;
528 cur_hop_fees_msat += extra_fees_msat;
532 // Final hop is a special case: it usually has just value_msat (by design), but also
533 // it still could overpay for the htlc_minimum_msat.
534 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
536 // Propagate updated fees for the use of the channels to one hop back, where they
537 // will be actually paid (fee_msat). The last hop is handled above separately.
538 cur_hop.fee_msat = cur_hop_fees_msat;
541 // Fee for the use of the current hop which will be deducted on the previous hop.
542 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
543 // this channel is free for us.
545 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
546 cur_hop.hop_use_fee_msat = new_fee;
547 total_fee_paid_msat += new_fee;
549 // It should not be possible because this function is called only to reduce the
550 // value. In that case, compute_fee was already called with the same fees for
551 // larger amount and there was no overflow.
559 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
560 let proportional_fee_millions =
561 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
562 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
563 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
567 // This function may be (indirectly) called without any verification,
568 // with channel_fees provided by a caller. We should handle it gracefully.
573 /// Finds a route from us (payer) to the given target node (payee).
575 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
576 /// Without this, MPP will only be used if the payee's features are available in the network graph.
578 /// Private routing paths between a public node and the target may be included in `params.payee`.
580 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
581 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
582 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
584 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
585 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
586 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
590 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
591 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
596 /// Panics if first_hops contains channels without short_channel_ids;
597 /// [`ChannelManager::list_usable_channels`] will never include such channels.
599 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
600 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
601 pub fn find_route<L: Deref, S: Score>(
602 our_node_pubkey: &PublicKey, params: &RouteParameters, network: &NetworkGraph,
603 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
604 ) -> Result<Route, LightningError>
605 where L::Target: Logger {
607 our_node_pubkey, ¶ms.payee, network, first_hops, params.final_value_msat,
608 params.final_cltv_expiry_delta, logger, scorer
612 pub(crate) fn get_route<L: Deref, S: Score>(
613 our_node_pubkey: &PublicKey, payee: &Payee, network: &NetworkGraph,
614 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
615 logger: L, scorer: &S
616 ) -> Result<Route, LightningError>
617 where L::Target: Logger {
618 let payee_node_id = NodeId::from_pubkey(&payee.pubkey);
619 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
621 if payee_node_id == our_node_id {
622 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
625 if final_value_msat > MAX_VALUE_MSAT {
626 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
629 if final_value_msat == 0 {
630 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
633 for route in payee.route_hints.iter() {
634 for hop in &route.0 {
635 if hop.src_node_id == payee.pubkey {
636 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
641 // The general routing idea is the following:
642 // 1. Fill first/last hops communicated by the caller.
643 // 2. Attempt to construct a path from payer to payee for transferring
644 // any ~sufficient (described later) value.
645 // If succeed, remember which channels were used and how much liquidity they have available,
646 // so that future paths don't rely on the same liquidity.
647 // 3. Prooceed to the next step if:
648 // - we hit the recommended target value;
649 // - OR if we could not construct a new path. Any next attempt will fail too.
650 // Otherwise, repeat step 2.
651 // 4. See if we managed to collect paths which aggregately are able to transfer target value
652 // (not recommended value). If yes, proceed. If not, fail routing.
653 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
654 // 6. Of all the found paths, select only those with the lowest total fee.
655 // 7. The last path in every selected route is likely to be more than we need.
656 // Reduce its value-to-transfer and recompute fees.
657 // 8. Choose the best route by the lowest total fee.
659 // As for the actual search algorithm,
660 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
661 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
663 // We are not a faithful Dijkstra's implementation because we can change values which impact
664 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
665 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
666 // the value we are currently attempting to send over a path, we simply reduce the value being
667 // sent along the path for any hops after that channel. This may imply that later fees (which
668 // we've already tabulated) are lower because a smaller value is passing through the channels
669 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
670 // channels which were selected earlier (and which may still be used for other paths without a
671 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
674 // One potentially problematic case for this algorithm would be if there are many
675 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
676 // graph walking), we may never find a path which is not liquidity-limited and has lower
677 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
678 // Because we only consider paths with at least 5% of the total value being sent, the damage
679 // from such a case should be limited, however this could be further reduced in the future by
680 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
681 // limits for the purposes of fee calculation.
683 // Alternatively, we could store more detailed path information in the heap (targets, below)
684 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
685 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
686 // and practically (as we would need to store dynamically-allocated path information in heap
687 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
688 // results of such an algorithm would likely be biased towards lower-value paths.
690 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
691 // outside of our current search value, running a path search more times to gather candidate
692 // paths at different values. While this may be acceptable, further path searches may increase
693 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
694 // graph for candidate paths, calculating the maximum value which can realistically be sent at
695 // the same time, remaining generic across different payment values.
697 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
698 // to use as the A* heuristic beyond just the cost to get one node further than the current
701 let network_graph = network.read_only();
702 let network_channels = network_graph.channels();
703 let network_nodes = network_graph.nodes();
705 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
706 // it. If the payee supports it they're supposed to include it in the invoice, so that should
708 let allow_mpp = if let Some(features) = &payee.features {
709 features.supports_basic_mpp()
710 } else if let Some(node) = network_nodes.get(&payee_node_id) {
711 if let Some(node_info) = node.announcement_info.as_ref() {
712 node_info.features.supports_basic_mpp()
715 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
716 payee.pubkey, if allow_mpp { "with" } else { "without" });
719 // Prepare the data we'll use for payee-to-payer search by
720 // inserting first hops suggested by the caller as targets.
721 // Our search will then attempt to reach them while traversing from the payee node.
722 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
723 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
724 if let Some(hops) = first_hops {
726 if chan.short_channel_id.is_none() {
727 panic!("first_hops should be filled in with usable channels, not pending ones");
729 if chan.counterparty.node_id == *our_node_pubkey {
730 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
733 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
734 .or_insert(Vec::new())
737 if first_hop_targets.is_empty() {
738 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
742 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
743 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
744 // adding duplicate entries when we find a better path to a given node.
745 let mut targets = BinaryHeap::new();
747 // Map from node_id to information about the best current path to that node, including feerate
749 let mut dist = HashMap::with_capacity(network_nodes.len());
751 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
752 // indicating that we may wish to try again with a higher value, potentially paying to meet an
753 // htlc_minimum with extra fees while still finding a cheaper path.
754 let mut hit_minimum_limit;
756 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
757 // We start with a path_value of the exact amount we want, and if that generates a route we may
758 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
759 // amount we want in total across paths, selecting the best subset at the end.
760 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
761 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
762 let mut path_value_msat = final_value_msat;
764 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
765 // This map allows paths to be aware of the channel use by other paths in the same call.
766 // This would help to make a better path finding decisions and not "overbook" channels.
767 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
768 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
770 // Keeping track of how much value we already collected across other paths. Helps to decide:
771 // - how much a new path should be transferring (upper bound);
772 // - whether a channel should be disregarded because
773 // it's available liquidity is too small comparing to how much more we need to collect;
774 // - when we want to stop looking for new paths.
775 let mut already_collected_value_msat = 0;
777 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee.pubkey, our_node_pubkey, final_value_msat);
779 macro_rules! add_entry {
780 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
781 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
782 // since that value has to be transferred over this channel.
783 // Returns whether this channel caused an update to `targets`.
784 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
785 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => { {
786 // We "return" whether we updated the path at the end, via this:
787 let mut did_add_update_path_to_src_node = false;
788 // Channels to self should not be used. This is more of belt-and-suspenders, because in
789 // practice these cases should be caught earlier:
790 // - for regular channels at channel announcement (TODO)
791 // - for first and last hops early in get_route
792 if $src_node_id != $dest_node_id {
793 let short_channel_id = $candidate.short_channel_id();
794 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat
795 .entry(short_channel_id)
796 .or_insert_with(|| $candidate.effective_capacity().as_msat());
798 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
799 // It may be misleading because we might later choose to reduce the value transferred
800 // over these channels, and the channel which was insufficient might become sufficient.
801 // Worst case: we drop a good channel here because it can't cover the high following
802 // fees caused by one expensive channel, but then this channel could have been used
803 // if the amount being transferred over this path is lower.
804 // We do this for now, but this is a subject for removal.
805 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
807 // Routing Fragmentation Mitigation heuristic:
809 // Routing fragmentation across many payment paths increases the overall routing
810 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
811 // Taking too many smaller paths also increases the chance of payment failure.
812 // Thus to avoid this effect, we require from our collected links to provide
813 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
815 // This requirement is currently 5% of the remaining-to-be-collected value.
816 // This means as we successfully advance in our collection,
817 // the absolute liquidity contribution is lowered,
818 // thus increasing the number of potential channels to be selected.
820 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
821 // or 100% if we're not allowed to do multipath payments.
822 let minimal_value_contribution_msat: u64 = if allow_mpp {
823 (recommended_value_msat - already_collected_value_msat + 19) / 20
827 // Verify the liquidity offered by this channel complies to the minimal contribution.
828 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
830 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
831 // Includes paying fees for the use of the following channels.
832 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
833 Some(result) => result,
834 // Can't overflow due to how the values were computed right above.
835 None => unreachable!(),
837 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
838 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
839 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
841 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
842 // bother considering this channel.
843 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
844 // be only reduced later (not increased), so this channel should just be skipped
845 // as not sufficient.
846 if !over_path_minimum_msat {
847 hit_minimum_limit = true;
848 } else if contributes_sufficient_value {
849 // Note that low contribution here (limited by available_liquidity_msat)
850 // might violate htlc_minimum_msat on the hops which are next along the
851 // payment path (upstream to the payee). To avoid that, we recompute path
852 // path fees knowing the final path contribution after constructing it.
853 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
854 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
855 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
856 .unwrap_or_else(|| u64::max_value());
857 let hm_entry = dist.entry($src_node_id);
858 let old_entry = hm_entry.or_insert_with(|| {
859 // If there was previously no known way to access the source node
860 // (recall it goes payee-to-payer) of short_channel_id, first add a
861 // semi-dummy record just to compute the fees to reach the source node.
862 // This will affect our decision on selecting short_channel_id
863 // as a way to reach the $dest_node_id.
864 let mut fee_base_msat = u32::max_value();
865 let mut fee_proportional_millionths = u32::max_value();
866 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
867 fee_base_msat = fees.base_msat;
868 fee_proportional_millionths = fees.proportional_millionths;
871 node_id: $dest_node_id.clone(),
873 channel_features: $candidate.features(),
875 cltv_expiry_delta: 0,
876 src_lowest_inbound_fees: RoutingFees {
877 base_msat: fee_base_msat,
878 proportional_millionths: fee_proportional_millionths,
880 channel_fees: $candidate.fees(),
881 next_hops_fee_msat: u64::max_value(),
882 hop_use_fee_msat: u64::max_value(),
883 total_fee_msat: u64::max_value(),
884 htlc_minimum_msat: $candidate.htlc_minimum_msat(),
885 path_htlc_minimum_msat,
886 path_penalty_msat: u64::max_value(),
887 was_processed: false,
888 #[cfg(any(test, feature = "fuzztarget"))]
889 value_contribution_msat,
893 #[allow(unused_mut)] // We only use the mut in cfg(test)
894 let mut should_process = !old_entry.was_processed;
895 #[cfg(any(test, feature = "fuzztarget"))]
897 // In test/fuzzing builds, we do extra checks to make sure the skipping
898 // of already-seen nodes only happens in cases we expect (see below).
899 if !should_process { should_process = true; }
903 let mut hop_use_fee_msat = 0;
904 let mut total_fee_msat = $next_hops_fee_msat;
906 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
907 // will have the same effective-fee
908 if $src_node_id != our_node_id {
909 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
910 // max_value means we'll always fail
911 // the old_entry.total_fee_msat > total_fee_msat check
912 None => total_fee_msat = u64::max_value(),
914 hop_use_fee_msat = fee_msat;
915 total_fee_msat += hop_use_fee_msat;
916 // When calculating the lowest inbound fees to a node, we
917 // calculate fees here not based on the actual value we think
918 // will flow over this channel, but on the minimum value that
919 // we'll accept flowing over it. The minimum accepted value
920 // is a constant through each path collection run, ensuring
921 // consistent basis. Otherwise we may later find a
922 // different path to the source node that is more expensive,
923 // but which we consider to be cheaper because we are capacity
924 // constrained and the relative fee becomes lower.
925 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
926 .map(|a| a.checked_add(total_fee_msat)) {
931 total_fee_msat = u64::max_value();
938 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
939 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
940 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
941 let new_graph_node = RouteGraphNode {
942 node_id: $src_node_id,
943 lowest_fee_to_peer_through_node: total_fee_msat,
944 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
945 value_contribution_msat: value_contribution_msat,
946 path_htlc_minimum_msat,
950 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
951 // if this way is cheaper than the already known
952 // (considering the cost to "reach" this channel from the route destination,
953 // the cost of using this channel,
954 // and the cost of routing to the source node of this channel).
955 // Also, consider that htlc_minimum_msat_difference, because we might end up
956 // paying it. Consider the following exploit:
957 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
958 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
959 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
960 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
962 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
963 // but it may require additional tracking - we don't want to double-count
964 // the fees included in $next_hops_path_htlc_minimum_msat, but also
965 // can't use something that may decrease on future hops.
966 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
967 .checked_add(old_entry.path_penalty_msat)
968 .unwrap_or_else(|| u64::max_value());
969 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
970 .checked_add(path_penalty_msat)
971 .unwrap_or_else(|| u64::max_value());
973 if !old_entry.was_processed && new_cost < old_cost {
974 targets.push(new_graph_node);
975 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
976 old_entry.hop_use_fee_msat = hop_use_fee_msat;
977 old_entry.total_fee_msat = total_fee_msat;
978 old_entry.node_id = $dest_node_id.clone();
979 old_entry.short_channel_id = short_channel_id;
980 old_entry.channel_features = $candidate.features();
981 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
982 old_entry.cltv_expiry_delta = $candidate.cltv_expiry_delta();
983 old_entry.channel_fees = $candidate.fees();
984 old_entry.htlc_minimum_msat = $candidate.htlc_minimum_msat();
985 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
986 old_entry.path_penalty_msat = path_penalty_msat;
987 #[cfg(any(test, feature = "fuzztarget"))]
989 old_entry.value_contribution_msat = value_contribution_msat;
991 did_add_update_path_to_src_node = true;
992 } else if old_entry.was_processed && new_cost < old_cost {
993 #[cfg(any(test, feature = "fuzztarget"))]
995 // If we're skipping processing a node which was previously
996 // processed even though we found another path to it with a
997 // cheaper fee, check that it was because the second path we
998 // found (which we are processing now) has a lower value
999 // contribution due to an HTLC minimum limit.
1001 // e.g. take a graph with two paths from node 1 to node 2, one
1002 // through channel A, and one through channel B. Channel A and
1003 // B are both in the to-process heap, with their scores set by
1004 // a higher htlc_minimum than fee.
1005 // Channel A is processed first, and the channels onwards from
1006 // node 1 are added to the to-process heap. Thereafter, we pop
1007 // Channel B off of the heap, note that it has a much more
1008 // restrictive htlc_maximum_msat, and recalculate the fees for
1009 // all of node 1's channels using the new, reduced, amount.
1011 // This would be bogus - we'd be selecting a higher-fee path
1012 // with a lower htlc_maximum_msat instead of the one we'd
1013 // already decided to use.
1014 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1016 value_contribution_msat + path_penalty_msat <
1017 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1025 did_add_update_path_to_src_node
1029 let empty_node_features = NodeFeatures::empty();
1030 // Find ways (channels with destination) to reach a given node and store them
1031 // in the corresponding data structures (routing graph etc).
1032 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1033 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1034 // This data can later be helpful to optimize routing (pay lower fees).
1035 macro_rules! add_entries_to_cheapest_to_target_node {
1036 ( $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 ) => {
1037 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1038 let was_processed = elem.was_processed;
1039 elem.was_processed = true;
1042 // Entries are added to dist in add_entry!() when there is a channel from a node.
1043 // Because there are no channels from payee, it will not have a dist entry at this point.
1044 // If we're processing any other node, it is always be the result of a channel from it.
1045 assert_eq!($node_id, payee_node_id);
1050 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1051 for details in first_channels {
1052 let candidate = CandidateRouteHop::FirstHop { details };
1053 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);
1057 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1060 &empty_node_features
1063 if !features.requires_unknown_bits() {
1064 for chan_id in $node.channels.iter() {
1065 let chan = network_channels.get(chan_id).unwrap();
1066 if !chan.features.requires_unknown_bits() {
1067 let directed_channel = chan.directed_to(&$node_id);
1068 let source = directed_channel.source();
1069 let target = directed_channel.target();
1070 if first_hops.is_none() || *source != our_node_id {
1071 let (channel, direction) = directed_channel.into_parts();
1072 if let Some(direction) = direction {
1073 if direction.enabled {
1074 let candidate = CandidateRouteHop::PublicHop {
1075 short_channel_id: *chan_id,
1079 add_entry!(candidate, *source, *target, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat);
1090 let mut payment_paths = Vec::<PaymentPath>::new();
1092 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1093 'paths_collection: loop {
1094 // For every new path, start from scratch, except
1095 // bookkeeped_channels_liquidity_available_msat, which will improve
1096 // the further iterations of path finding. Also don't erase first_hop_targets.
1099 hit_minimum_limit = false;
1101 // If first hop is a private channel and the only way to reach the payee, this is the only
1102 // place where it could be added.
1103 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1104 for details in first_channels {
1105 let candidate = CandidateRouteHop::FirstHop { details };
1106 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64);
1107 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1111 // Add the payee as a target, so that the payee-to-payer
1112 // search algorithm knows what to start with.
1113 match network_nodes.get(&payee_node_id) {
1114 // The payee is not in our network graph, so nothing to add here.
1115 // There is still a chance of reaching them via last_hops though,
1116 // so don't yet fail the payment here.
1117 // If not, targets.pop() will not even let us enter the loop in step 2.
1120 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64);
1125 // If a caller provided us with last hops, add them to routing targets. Since this happens
1126 // earlier than general path finding, they will be somewhat prioritized, although currently
1127 // it matters only if the fees are exactly the same.
1128 for route in payee.route_hints.iter().filter(|route| !route.0.is_empty()) {
1129 let first_hop_in_route = &(route.0)[0];
1130 let have_hop_src_in_graph =
1131 // Only add the hops in this route to our candidate set if either
1132 // we have a direct channel to the first hop or the first hop is
1133 // in the regular network graph.
1134 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1135 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1136 if have_hop_src_in_graph {
1137 // We start building the path from reverse, i.e., from payee
1138 // to the first RouteHintHop in the path.
1139 let hop_iter = route.0.iter().rev();
1140 let prev_hop_iter = core::iter::once(&payee.pubkey).chain(
1141 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1142 let mut hop_used = true;
1143 let mut aggregate_next_hops_fee_msat: u64 = 0;
1144 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1145 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1147 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1148 let source = NodeId::from_pubkey(&hop.src_node_id);
1149 let target = NodeId::from_pubkey(&prev_hop_id);
1150 let candidate = network_channels
1151 .get(&hop.short_channel_id)
1152 .map(|channel| channel.as_directed(&source, &target).into_parts())
1153 .and_then(|(channel, direction)| {
1154 direction.map(|direction|
1155 CandidateRouteHop::PublicHop {
1156 short_channel_id: hop.short_channel_id,
1161 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1162 let capacity_msat = candidate.effective_capacity().as_msat();
1163 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1164 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1165 .unwrap_or_else(|| u64::max_value());
1167 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) {
1168 // If this hop was not used then there is no use checking the preceding hops
1169 // in the RouteHint. We can break by just searching for a direct channel between
1170 // last checked hop and first_hop_targets
1174 // Searching for a direct channel between last checked hop and first_hop_targets
1175 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1176 for details in first_channels {
1177 let candidate = CandidateRouteHop::FirstHop { details };
1178 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);
1186 // In the next values of the iterator, the aggregate fees already reflects
1187 // the sum of value sent from payer (final_value_msat) and routing fees
1188 // for the last node in the RouteHint. We need to just add the fees to
1189 // route through the current node so that the preceeding node (next iteration)
1191 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1192 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1193 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1195 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1196 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1197 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1198 .checked_add(hop_htlc_minimum_msat_inc);
1199 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1201 if idx == route.0.len() - 1 {
1202 // The last hop in this iterator is the first hop in
1203 // overall RouteHint.
1204 // If this hop connects to a node with which we have a direct channel,
1205 // ignore the network graph and, if the last hop was added, add our
1206 // direct channel to the candidate set.
1208 // Note that we *must* check if the last hop was added as `add_entry`
1209 // always assumes that the third argument is a node to which we have a
1211 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1212 for details in first_channels {
1213 let candidate = CandidateRouteHop::FirstHop { details };
1214 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);
1222 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1224 // At this point, targets are filled with the data from first and
1225 // last hops communicated by the caller, and the payment receiver.
1226 let mut found_new_path = false;
1229 // If this loop terminates due the exhaustion of targets, two situations are possible:
1230 // - not enough outgoing liquidity:
1231 // 0 < already_collected_value_msat < final_value_msat
1232 // - enough outgoing liquidity:
1233 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1234 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1235 // paths_collection will be stopped because found_new_path==false.
1236 // This is not necessarily a routing failure.
1237 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1239 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1240 // traversing the graph and arrange the path out of what we found.
1241 if node_id == our_node_id {
1242 let mut new_entry = dist.remove(&our_node_id).unwrap();
1243 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1246 let mut features_set = false;
1247 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1248 for details in first_channels {
1249 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.short_channel_id {
1250 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1251 features_set = true;
1257 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1258 if let Some(node_info) = node.announcement_info.as_ref() {
1259 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1261 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1264 // We should be able to fill in features for everything except the last
1265 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1266 // should be able to extend it further as BOLT 11 does have feature
1267 // flags for the last hop node itself).
1268 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1272 // Means we succesfully traversed from the payer to the payee, now
1273 // save this path for the payment route. Also, update the liquidity
1274 // remaining on the used hops, so that we take them into account
1275 // while looking for more paths.
1276 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1280 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1281 Some(payment_hop) => payment_hop,
1282 // We can't arrive at None because, if we ever add an entry to targets,
1283 // we also fill in the entry in dist (see add_entry!).
1284 None => unreachable!(),
1286 // We "propagate" the fees one hop backward (topologically) here,
1287 // so that fees paid for a HTLC forwarding on the current channel are
1288 // associated with the previous channel (where they will be subtracted).
1289 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1290 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1291 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1293 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1294 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1295 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv_expiry_delta;
1297 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1298 ordered_hops.len(), value_contribution_msat, ordered_hops);
1300 let mut payment_path = PaymentPath {hops: ordered_hops};
1302 // We could have possibly constructed a slightly inconsistent path: since we reduce
1303 // value being transferred along the way, we could have violated htlc_minimum_msat
1304 // on some channels we already passed (assuming dest->source direction). Here, we
1305 // recompute the fees again, so that if that's the case, we match the currently
1306 // underpaid htlc_minimum_msat with fees.
1307 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1309 // Since a path allows to transfer as much value as
1310 // the smallest channel it has ("bottleneck"), we should recompute
1311 // the fees so sender HTLC don't overpay fees when traversing
1312 // larger channels than the bottleneck. This may happen because
1313 // when we were selecting those channels we were not aware how much value
1314 // this path will transfer, and the relative fee for them
1315 // might have been computed considering a larger value.
1316 // Remember that we used these channels so that we don't rely
1317 // on the same liquidity in future paths.
1318 let mut prevented_redundant_path_selection = false;
1319 for (payment_hop, _) in payment_path.hops.iter() {
1320 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1321 let mut spent_on_hop_msat = value_contribution_msat;
1322 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1323 spent_on_hop_msat += next_hops_fee_msat;
1324 if spent_on_hop_msat == *channel_liquidity_available_msat {
1325 // If this path used all of this channel's available liquidity, we know
1326 // this path will not be selected again in the next loop iteration.
1327 prevented_redundant_path_selection = true;
1329 *channel_liquidity_available_msat -= spent_on_hop_msat;
1331 if !prevented_redundant_path_selection {
1332 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1333 // we'll probably end up picking the same path again on the next iteration.
1334 // Decrease the available liquidity of a hop in the middle of the path.
1335 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1336 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1337 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1338 *victim_liquidity = 0;
1341 // Track the total amount all our collected paths allow to send so that we:
1342 // - know when to stop looking for more paths
1343 // - know which of the hops are useless considering how much more sats we need
1344 // (contributes_sufficient_value)
1345 already_collected_value_msat += value_contribution_msat;
1347 payment_paths.push(payment_path);
1348 found_new_path = true;
1349 break 'path_construction;
1352 // If we found a path back to the payee, we shouldn't try to process it again. This is
1353 // the equivalent of the `elem.was_processed` check in
1354 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1355 if node_id == payee_node_id { continue 'path_construction; }
1357 // Otherwise, since the current target node is not us,
1358 // keep "unrolling" the payment graph from payee to payer by
1359 // finding a way to reach the current target from the payer side.
1360 match network_nodes.get(&node_id) {
1363 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1369 // If we don't support MPP, no use trying to gather more value ever.
1370 break 'paths_collection;
1374 // Stop either when the recommended value is reached or if no new path was found in this
1376 // In the latter case, making another path finding attempt won't help,
1377 // because we deterministically terminated the search due to low liquidity.
1378 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1379 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1380 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1381 break 'paths_collection;
1382 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1383 // Further, if this was our first walk of the graph, and we weren't limited by an
1384 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1385 // limited by an htlc_minimum_msat value, find another path with a higher value,
1386 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1387 // still keeping a lower total fee than this path.
1388 if !hit_minimum_limit {
1389 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1390 break 'paths_collection;
1392 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1393 path_value_msat = recommended_value_msat;
1398 if payment_paths.len() == 0 {
1399 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1402 if already_collected_value_msat < final_value_msat {
1403 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1406 // Sort by total fees and take the best paths.
1407 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1408 if payment_paths.len() > 50 {
1409 payment_paths.truncate(50);
1412 // Draw multiple sufficient routes by randomly combining the selected paths.
1413 let mut drawn_routes = Vec::new();
1414 for i in 0..payment_paths.len() {
1415 let mut cur_route = Vec::<PaymentPath>::new();
1416 let mut aggregate_route_value_msat = 0;
1419 // TODO: real random shuffle
1420 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1421 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1424 for payment_path in cur_payment_paths {
1425 cur_route.push(payment_path.clone());
1426 aggregate_route_value_msat += payment_path.get_value_msat();
1427 if aggregate_route_value_msat > final_value_msat {
1428 // Last path likely overpaid. Substract it from the most expensive
1429 // (in terms of proportional fee) path in this route and recompute fees.
1430 // This might be not the most economically efficient way, but fewer paths
1431 // also makes routing more reliable.
1432 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1434 // First, drop some expensive low-value paths entirely if possible.
1435 // Sort by value so that we drop many really-low values first, since
1436 // fewer paths is better: the payment is less likely to fail.
1437 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1438 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1439 cur_route.sort_by_key(|path| path.get_value_msat());
1440 // We should make sure that at least 1 path left.
1441 let mut paths_left = cur_route.len();
1442 cur_route.retain(|path| {
1443 if paths_left == 1 {
1446 let mut keep = true;
1447 let path_value_msat = path.get_value_msat();
1448 if path_value_msat <= overpaid_value_msat {
1450 overpaid_value_msat -= path_value_msat;
1456 if overpaid_value_msat == 0 {
1460 assert!(cur_route.len() > 0);
1463 // Now, substract the overpaid value from the most-expensive path.
1464 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1465 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1466 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1467 let expensive_payment_path = cur_route.first_mut().unwrap();
1468 // We already dropped all the small channels above, meaning all the
1469 // remaining channels are larger than remaining overpaid_value_msat.
1470 // Thus, this can't be negative.
1471 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1472 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1476 drawn_routes.push(cur_route);
1480 // Select the best route by lowest total fee.
1481 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1482 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1483 for payment_path in drawn_routes.first().unwrap() {
1484 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1486 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)})?,
1487 node_features: node_features.clone(),
1488 short_channel_id: payment_hop.short_channel_id,
1489 channel_features: payment_hop.channel_features.clone(),
1490 fee_msat: payment_hop.fee_msat,
1491 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1496 if let Some(features) = &payee.features {
1497 for path in selected_paths.iter_mut() {
1498 if let Ok(route_hop) = path.last_mut().unwrap() {
1499 route_hop.node_features = features.to_context();
1505 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1506 payee: Some(payee.clone()),
1508 log_info!(logger, "Got route to {}: {}", payee.pubkey, log_route!(route));
1514 use routing::scoring::Score;
1515 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1516 use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1517 use chain::transaction::OutPoint;
1518 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1519 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1520 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1521 use ln::channelmanager;
1522 use util::test_utils;
1523 use util::ser::Writeable;
1525 use util::ser::Writer;
1527 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1528 use bitcoin::hashes::Hash;
1529 use bitcoin::network::constants::Network;
1530 use bitcoin::blockdata::constants::genesis_block;
1531 use bitcoin::blockdata::script::Builder;
1532 use bitcoin::blockdata::opcodes;
1533 use bitcoin::blockdata::transaction::TxOut;
1537 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1538 use bitcoin::secp256k1::{Secp256k1, All};
1541 use sync::{self, Arc};
1543 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1544 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1545 channelmanager::ChannelDetails {
1546 channel_id: [0; 32],
1547 counterparty: channelmanager::ChannelCounterparty {
1550 unspendable_punishment_reserve: 0,
1551 forwarding_info: None,
1553 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1555 channel_value_satoshis: 0,
1558 outbound_capacity_msat,
1559 inbound_capacity_msat: 42,
1560 unspendable_punishment_reserve: None,
1561 confirmations_required: None,
1562 force_close_spend_delay: None,
1563 is_outbound: true, is_funding_locked: true,
1564 is_usable: true, is_public: true,
1568 // Using the same keys for LN and BTC ids
1570 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1571 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1573 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1574 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1576 let unsigned_announcement = UnsignedChannelAnnouncement {
1578 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1582 bitcoin_key_1: node_id_1,
1583 bitcoin_key_2: node_id_2,
1584 excess_data: Vec::new(),
1587 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1588 let valid_announcement = ChannelAnnouncement {
1589 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1590 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1591 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1592 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1593 contents: unsigned_announcement.clone(),
1595 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1596 Ok(res) => assert!(res),
1602 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1603 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1605 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1606 let valid_channel_update = ChannelUpdate {
1607 signature: secp_ctx.sign(&msghash, node_privkey),
1608 contents: update.clone()
1611 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1612 Ok(res) => assert!(res),
1617 fn add_or_update_node(
1618 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1619 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1621 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1622 let unsigned_announcement = UnsignedNodeAnnouncement {
1628 addresses: Vec::new(),
1629 excess_address_data: Vec::new(),
1630 excess_data: Vec::new(),
1632 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1633 let valid_announcement = NodeAnnouncement {
1634 signature: secp_ctx.sign(&msghash, node_privkey),
1635 contents: unsigned_announcement.clone()
1638 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1644 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1645 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1646 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1649 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1651 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1652 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1654 (our_privkey, our_id, privkeys, pubkeys)
1657 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1658 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1659 // test for it later.
1660 let idx = (id - 1) * 2 + 1;
1662 vec![1 << (idx - 8*3), 0, 0, 0]
1663 } else if idx > 8*2 {
1664 vec![1 << (idx - 8*2), 0, 0]
1665 } else if idx > 8*1 {
1666 vec![1 << (idx - 8*1), 0]
1672 fn build_graph() -> (
1674 sync::Arc<NetworkGraph>,
1675 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1676 sync::Arc<test_utils::TestChainSource>,
1677 sync::Arc<test_utils::TestLogger>,
1679 let secp_ctx = Secp256k1::new();
1680 let logger = Arc::new(test_utils::TestLogger::new());
1681 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1682 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1683 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1684 // Build network from our_id to node6:
1686 // -1(1)2- node0 -1(3)2-
1688 // our_id -1(12)2- node7 -1(13)2--- node2
1690 // -1(2)2- node1 -1(4)2-
1693 // chan1 1-to-2: disabled
1694 // chan1 2-to-1: enabled, 0 fee
1696 // chan2 1-to-2: enabled, ignored fee
1697 // chan2 2-to-1: enabled, 0 fee
1699 // chan3 1-to-2: enabled, 0 fee
1700 // chan3 2-to-1: enabled, 100 msat fee
1702 // chan4 1-to-2: enabled, 100% fee
1703 // chan4 2-to-1: enabled, 0 fee
1705 // chan12 1-to-2: enabled, ignored fee
1706 // chan12 2-to-1: enabled, 0 fee
1708 // chan13 1-to-2: enabled, 200% fee
1709 // chan13 2-to-1: enabled, 0 fee
1712 // -1(5)2- node3 -1(8)2--
1716 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1718 // -1(7)2- node5 -1(10)2-
1720 // Channels 5, 8, 9 and 10 are private channels.
1722 // chan5 1-to-2: enabled, 100 msat fee
1723 // chan5 2-to-1: enabled, 0 fee
1725 // chan6 1-to-2: enabled, 0 fee
1726 // chan6 2-to-1: enabled, 0 fee
1728 // chan7 1-to-2: enabled, 100% fee
1729 // chan7 2-to-1: enabled, 0 fee
1731 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1732 // chan8 2-to-1: enabled, 0 fee
1734 // chan9 1-to-2: enabled, 1001 msat fee
1735 // chan9 2-to-1: enabled, 0 fee
1737 // chan10 1-to-2: enabled, 0 fee
1738 // chan10 2-to-1: enabled, 0 fee
1740 // chan11 1-to-2: enabled, 0 fee
1741 // chan11 2-to-1: enabled, 0 fee
1743 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1745 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1746 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1748 short_channel_id: 1,
1751 cltv_expiry_delta: 0,
1752 htlc_minimum_msat: 0,
1753 htlc_maximum_msat: OptionalField::Absent,
1755 fee_proportional_millionths: 0,
1756 excess_data: Vec::new()
1759 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1761 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1762 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1764 short_channel_id: 2,
1767 cltv_expiry_delta: u16::max_value(),
1768 htlc_minimum_msat: 0,
1769 htlc_maximum_msat: OptionalField::Absent,
1770 fee_base_msat: u32::max_value(),
1771 fee_proportional_millionths: u32::max_value(),
1772 excess_data: Vec::new()
1774 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1776 short_channel_id: 2,
1779 cltv_expiry_delta: 0,
1780 htlc_minimum_msat: 0,
1781 htlc_maximum_msat: OptionalField::Absent,
1783 fee_proportional_millionths: 0,
1784 excess_data: Vec::new()
1787 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1789 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1790 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1792 short_channel_id: 12,
1795 cltv_expiry_delta: u16::max_value(),
1796 htlc_minimum_msat: 0,
1797 htlc_maximum_msat: OptionalField::Absent,
1798 fee_base_msat: u32::max_value(),
1799 fee_proportional_millionths: u32::max_value(),
1800 excess_data: Vec::new()
1802 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1804 short_channel_id: 12,
1807 cltv_expiry_delta: 0,
1808 htlc_minimum_msat: 0,
1809 htlc_maximum_msat: OptionalField::Absent,
1811 fee_proportional_millionths: 0,
1812 excess_data: Vec::new()
1815 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1817 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1818 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1820 short_channel_id: 3,
1823 cltv_expiry_delta: (3 << 8) | 1,
1824 htlc_minimum_msat: 0,
1825 htlc_maximum_msat: OptionalField::Absent,
1827 fee_proportional_millionths: 0,
1828 excess_data: Vec::new()
1830 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1832 short_channel_id: 3,
1835 cltv_expiry_delta: (3 << 8) | 2,
1836 htlc_minimum_msat: 0,
1837 htlc_maximum_msat: OptionalField::Absent,
1839 fee_proportional_millionths: 0,
1840 excess_data: Vec::new()
1843 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1844 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1845 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1846 short_channel_id: 4,
1849 cltv_expiry_delta: (4 << 8) | 1,
1850 htlc_minimum_msat: 0,
1851 htlc_maximum_msat: OptionalField::Absent,
1853 fee_proportional_millionths: 1000000,
1854 excess_data: Vec::new()
1856 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1858 short_channel_id: 4,
1861 cltv_expiry_delta: (4 << 8) | 2,
1862 htlc_minimum_msat: 0,
1863 htlc_maximum_msat: OptionalField::Absent,
1865 fee_proportional_millionths: 0,
1866 excess_data: Vec::new()
1869 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1870 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1872 short_channel_id: 13,
1875 cltv_expiry_delta: (13 << 8) | 1,
1876 htlc_minimum_msat: 0,
1877 htlc_maximum_msat: OptionalField::Absent,
1879 fee_proportional_millionths: 2000000,
1880 excess_data: Vec::new()
1882 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1884 short_channel_id: 13,
1887 cltv_expiry_delta: (13 << 8) | 2,
1888 htlc_minimum_msat: 0,
1889 htlc_maximum_msat: OptionalField::Absent,
1891 fee_proportional_millionths: 0,
1892 excess_data: Vec::new()
1895 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1897 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1900 short_channel_id: 6,
1903 cltv_expiry_delta: (6 << 8) | 1,
1904 htlc_minimum_msat: 0,
1905 htlc_maximum_msat: OptionalField::Absent,
1907 fee_proportional_millionths: 0,
1908 excess_data: Vec::new()
1910 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1912 short_channel_id: 6,
1915 cltv_expiry_delta: (6 << 8) | 2,
1916 htlc_minimum_msat: 0,
1917 htlc_maximum_msat: OptionalField::Absent,
1919 fee_proportional_millionths: 0,
1920 excess_data: Vec::new(),
1923 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1924 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1925 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1926 short_channel_id: 11,
1929 cltv_expiry_delta: (11 << 8) | 1,
1930 htlc_minimum_msat: 0,
1931 htlc_maximum_msat: OptionalField::Absent,
1933 fee_proportional_millionths: 0,
1934 excess_data: Vec::new()
1936 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1938 short_channel_id: 11,
1941 cltv_expiry_delta: (11 << 8) | 2,
1942 htlc_minimum_msat: 0,
1943 htlc_maximum_msat: OptionalField::Absent,
1945 fee_proportional_millionths: 0,
1946 excess_data: Vec::new()
1949 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1951 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1953 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1954 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1955 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1956 short_channel_id: 7,
1959 cltv_expiry_delta: (7 << 8) | 1,
1960 htlc_minimum_msat: 0,
1961 htlc_maximum_msat: OptionalField::Absent,
1963 fee_proportional_millionths: 1000000,
1964 excess_data: Vec::new()
1966 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1968 short_channel_id: 7,
1971 cltv_expiry_delta: (7 << 8) | 2,
1972 htlc_minimum_msat: 0,
1973 htlc_maximum_msat: OptionalField::Absent,
1975 fee_proportional_millionths: 0,
1976 excess_data: Vec::new()
1979 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1981 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1985 fn simple_route_test() {
1986 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1987 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1988 let payee = Payee::from_node_id(nodes[2]);
1989 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1991 // Simple route to 2 via 1
1993 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
1994 assert_eq!(err, "Cannot send a payment of 0 msat");
1995 } else { panic!(); }
1997 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1998 assert_eq!(route.paths[0].len(), 2);
2000 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2001 assert_eq!(route.paths[0][0].short_channel_id, 2);
2002 assert_eq!(route.paths[0][0].fee_msat, 100);
2003 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2004 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2005 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2007 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2008 assert_eq!(route.paths[0][1].short_channel_id, 4);
2009 assert_eq!(route.paths[0][1].fee_msat, 100);
2010 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2011 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2012 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2016 fn invalid_first_hop_test() {
2017 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2018 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2019 let payee = Payee::from_node_id(nodes[2]);
2020 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2022 // Simple route to 2 via 1
2024 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2026 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
2027 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2028 } else { panic!(); }
2030 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2031 assert_eq!(route.paths[0].len(), 2);
2035 fn htlc_minimum_test() {
2036 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2037 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2038 let payee = Payee::from_node_id(nodes[2]);
2039 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2041 // Simple route to 2 via 1
2043 // Disable other paths
2044 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2046 short_channel_id: 12,
2048 flags: 2, // to disable
2049 cltv_expiry_delta: 0,
2050 htlc_minimum_msat: 0,
2051 htlc_maximum_msat: OptionalField::Absent,
2053 fee_proportional_millionths: 0,
2054 excess_data: Vec::new()
2056 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2058 short_channel_id: 3,
2060 flags: 2, // to disable
2061 cltv_expiry_delta: 0,
2062 htlc_minimum_msat: 0,
2063 htlc_maximum_msat: OptionalField::Absent,
2065 fee_proportional_millionths: 0,
2066 excess_data: Vec::new()
2068 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2070 short_channel_id: 13,
2072 flags: 2, // to disable
2073 cltv_expiry_delta: 0,
2074 htlc_minimum_msat: 0,
2075 htlc_maximum_msat: OptionalField::Absent,
2077 fee_proportional_millionths: 0,
2078 excess_data: Vec::new()
2080 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2082 short_channel_id: 6,
2084 flags: 2, // to disable
2085 cltv_expiry_delta: 0,
2086 htlc_minimum_msat: 0,
2087 htlc_maximum_msat: OptionalField::Absent,
2089 fee_proportional_millionths: 0,
2090 excess_data: Vec::new()
2092 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2094 short_channel_id: 7,
2096 flags: 2, // to disable
2097 cltv_expiry_delta: 0,
2098 htlc_minimum_msat: 0,
2099 htlc_maximum_msat: OptionalField::Absent,
2101 fee_proportional_millionths: 0,
2102 excess_data: Vec::new()
2105 // Check against amount_to_transfer_over_msat.
2106 // Set minimal HTLC of 200_000_000 msat.
2107 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2108 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2109 short_channel_id: 2,
2112 cltv_expiry_delta: 0,
2113 htlc_minimum_msat: 200_000_000,
2114 htlc_maximum_msat: OptionalField::Absent,
2116 fee_proportional_millionths: 0,
2117 excess_data: Vec::new()
2120 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2122 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2123 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2124 short_channel_id: 4,
2127 cltv_expiry_delta: 0,
2128 htlc_minimum_msat: 0,
2129 htlc_maximum_msat: OptionalField::Present(199_999_999),
2131 fee_proportional_millionths: 0,
2132 excess_data: Vec::new()
2135 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2136 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2137 assert_eq!(err, "Failed to find a path to the given destination");
2138 } else { panic!(); }
2140 // Lift the restriction on the first hop.
2141 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2142 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2143 short_channel_id: 2,
2146 cltv_expiry_delta: 0,
2147 htlc_minimum_msat: 0,
2148 htlc_maximum_msat: OptionalField::Absent,
2150 fee_proportional_millionths: 0,
2151 excess_data: Vec::new()
2154 // A payment above the minimum should pass
2155 let route = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2156 assert_eq!(route.paths[0].len(), 2);
2160 fn htlc_minimum_overpay_test() {
2161 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2162 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2163 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2164 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2166 // A route to node#2 via two paths.
2167 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2168 // Thus, they can't send 60 without overpaying.
2169 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2170 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2171 short_channel_id: 2,
2174 cltv_expiry_delta: 0,
2175 htlc_minimum_msat: 35_000,
2176 htlc_maximum_msat: OptionalField::Present(40_000),
2178 fee_proportional_millionths: 0,
2179 excess_data: Vec::new()
2181 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2183 short_channel_id: 12,
2186 cltv_expiry_delta: 0,
2187 htlc_minimum_msat: 35_000,
2188 htlc_maximum_msat: OptionalField::Present(40_000),
2190 fee_proportional_millionths: 0,
2191 excess_data: Vec::new()
2195 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2196 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2197 short_channel_id: 13,
2200 cltv_expiry_delta: 0,
2201 htlc_minimum_msat: 0,
2202 htlc_maximum_msat: OptionalField::Absent,
2204 fee_proportional_millionths: 0,
2205 excess_data: Vec::new()
2207 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2209 short_channel_id: 4,
2212 cltv_expiry_delta: 0,
2213 htlc_minimum_msat: 0,
2214 htlc_maximum_msat: OptionalField::Absent,
2216 fee_proportional_millionths: 0,
2217 excess_data: Vec::new()
2220 // Disable other paths
2221 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2222 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2223 short_channel_id: 1,
2225 flags: 2, // to disable
2226 cltv_expiry_delta: 0,
2227 htlc_minimum_msat: 0,
2228 htlc_maximum_msat: OptionalField::Absent,
2230 fee_proportional_millionths: 0,
2231 excess_data: Vec::new()
2234 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2235 // Overpay fees to hit htlc_minimum_msat.
2236 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2237 // TODO: this could be better balanced to overpay 10k and not 15k.
2238 assert_eq!(overpaid_fees, 15_000);
2240 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2241 // while taking even more fee to match htlc_minimum_msat.
2242 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2244 short_channel_id: 12,
2247 cltv_expiry_delta: 0,
2248 htlc_minimum_msat: 65_000,
2249 htlc_maximum_msat: OptionalField::Present(80_000),
2251 fee_proportional_millionths: 0,
2252 excess_data: Vec::new()
2254 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2256 short_channel_id: 2,
2259 cltv_expiry_delta: 0,
2260 htlc_minimum_msat: 0,
2261 htlc_maximum_msat: OptionalField::Absent,
2263 fee_proportional_millionths: 0,
2264 excess_data: Vec::new()
2266 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2268 short_channel_id: 4,
2271 cltv_expiry_delta: 0,
2272 htlc_minimum_msat: 0,
2273 htlc_maximum_msat: OptionalField::Absent,
2275 fee_proportional_millionths: 100_000,
2276 excess_data: Vec::new()
2279 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2280 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2281 assert_eq!(route.paths.len(), 1);
2282 assert_eq!(route.paths[0][0].short_channel_id, 12);
2283 let fees = route.paths[0][0].fee_msat;
2284 assert_eq!(fees, 5_000);
2286 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2287 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2288 // the other channel.
2289 assert_eq!(route.paths.len(), 1);
2290 assert_eq!(route.paths[0][0].short_channel_id, 2);
2291 let fees = route.paths[0][0].fee_msat;
2292 assert_eq!(fees, 5_000);
2296 fn disable_channels_test() {
2297 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2298 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2299 let payee = Payee::from_node_id(nodes[2]);
2300 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2302 // // Disable channels 4 and 12 by flags=2
2303 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2304 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2305 short_channel_id: 4,
2307 flags: 2, // to disable
2308 cltv_expiry_delta: 0,
2309 htlc_minimum_msat: 0,
2310 htlc_maximum_msat: OptionalField::Absent,
2312 fee_proportional_millionths: 0,
2313 excess_data: Vec::new()
2315 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2316 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2317 short_channel_id: 12,
2319 flags: 2, // to disable
2320 cltv_expiry_delta: 0,
2321 htlc_minimum_msat: 0,
2322 htlc_maximum_msat: OptionalField::Absent,
2324 fee_proportional_millionths: 0,
2325 excess_data: Vec::new()
2328 // If all the channels require some features we don't understand, route should fail
2329 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2330 assert_eq!(err, "Failed to find a path to the given destination");
2331 } else { panic!(); }
2333 // If we specify a channel to node7, that overrides our local channel view and that gets used
2334 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2335 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2336 assert_eq!(route.paths[0].len(), 2);
2338 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2339 assert_eq!(route.paths[0][0].short_channel_id, 42);
2340 assert_eq!(route.paths[0][0].fee_msat, 200);
2341 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2342 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2343 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2345 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2346 assert_eq!(route.paths[0][1].short_channel_id, 13);
2347 assert_eq!(route.paths[0][1].fee_msat, 100);
2348 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2349 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2350 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2354 fn disable_node_test() {
2355 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2356 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2357 let payee = Payee::from_node_id(nodes[2]);
2358 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2360 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2361 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2362 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2363 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2364 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2366 // If all nodes require some features we don't understand, route should fail
2367 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2368 assert_eq!(err, "Failed to find a path to the given destination");
2369 } else { panic!(); }
2371 // If we specify a channel to node7, that overrides our local channel view and that gets used
2372 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2373 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2374 assert_eq!(route.paths[0].len(), 2);
2376 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2377 assert_eq!(route.paths[0][0].short_channel_id, 42);
2378 assert_eq!(route.paths[0][0].fee_msat, 200);
2379 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2380 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2381 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2383 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2384 assert_eq!(route.paths[0][1].short_channel_id, 13);
2385 assert_eq!(route.paths[0][1].fee_msat, 100);
2386 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2387 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2388 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2390 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2391 // naively) assume that the user checked the feature bits on the invoice, which override
2392 // the node_announcement.
2396 fn our_chans_test() {
2397 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2398 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2399 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2401 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2402 let payee = Payee::from_node_id(nodes[0]);
2403 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2404 assert_eq!(route.paths[0].len(), 3);
2406 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2407 assert_eq!(route.paths[0][0].short_channel_id, 2);
2408 assert_eq!(route.paths[0][0].fee_msat, 200);
2409 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2410 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2411 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2413 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2414 assert_eq!(route.paths[0][1].short_channel_id, 4);
2415 assert_eq!(route.paths[0][1].fee_msat, 100);
2416 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2417 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2418 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2420 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2421 assert_eq!(route.paths[0][2].short_channel_id, 3);
2422 assert_eq!(route.paths[0][2].fee_msat, 100);
2423 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2424 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2425 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2427 // If we specify a channel to node7, that overrides our local channel view and that gets used
2428 let payee = Payee::from_node_id(nodes[2]);
2429 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2430 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2431 assert_eq!(route.paths[0].len(), 2);
2433 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2434 assert_eq!(route.paths[0][0].short_channel_id, 42);
2435 assert_eq!(route.paths[0][0].fee_msat, 200);
2436 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2437 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2438 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2440 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2441 assert_eq!(route.paths[0][1].short_channel_id, 13);
2442 assert_eq!(route.paths[0][1].fee_msat, 100);
2443 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
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(13));
2448 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2449 let zero_fees = RoutingFees {
2451 proportional_millionths: 0,
2453 vec![RouteHint(vec![RouteHintHop {
2454 src_node_id: nodes[3],
2455 short_channel_id: 8,
2457 cltv_expiry_delta: (8 << 8) | 1,
2458 htlc_minimum_msat: None,
2459 htlc_maximum_msat: None,
2461 ]), RouteHint(vec![RouteHintHop {
2462 src_node_id: nodes[4],
2463 short_channel_id: 9,
2466 proportional_millionths: 0,
2468 cltv_expiry_delta: (9 << 8) | 1,
2469 htlc_minimum_msat: None,
2470 htlc_maximum_msat: None,
2471 }]), RouteHint(vec![RouteHintHop {
2472 src_node_id: nodes[5],
2473 short_channel_id: 10,
2475 cltv_expiry_delta: (10 << 8) | 1,
2476 htlc_minimum_msat: None,
2477 htlc_maximum_msat: None,
2481 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2482 let zero_fees = RoutingFees {
2484 proportional_millionths: 0,
2486 vec![RouteHint(vec![RouteHintHop {
2487 src_node_id: nodes[2],
2488 short_channel_id: 5,
2491 proportional_millionths: 0,
2493 cltv_expiry_delta: (5 << 8) | 1,
2494 htlc_minimum_msat: None,
2495 htlc_maximum_msat: None,
2497 src_node_id: nodes[3],
2498 short_channel_id: 8,
2500 cltv_expiry_delta: (8 << 8) | 1,
2501 htlc_minimum_msat: None,
2502 htlc_maximum_msat: None,
2504 ]), RouteHint(vec![RouteHintHop {
2505 src_node_id: nodes[4],
2506 short_channel_id: 9,
2509 proportional_millionths: 0,
2511 cltv_expiry_delta: (9 << 8) | 1,
2512 htlc_minimum_msat: None,
2513 htlc_maximum_msat: None,
2514 }]), RouteHint(vec![RouteHintHop {
2515 src_node_id: nodes[5],
2516 short_channel_id: 10,
2518 cltv_expiry_delta: (10 << 8) | 1,
2519 htlc_minimum_msat: None,
2520 htlc_maximum_msat: None,
2525 fn partial_route_hint_test() {
2526 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2527 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2528 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2530 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2531 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2532 // RouteHint may be partially used by the algo to build the best path.
2534 // First check that last hop can't have its source as the payee.
2535 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2536 src_node_id: nodes[6],
2537 short_channel_id: 8,
2540 proportional_millionths: 0,
2542 cltv_expiry_delta: (8 << 8) | 1,
2543 htlc_minimum_msat: None,
2544 htlc_maximum_msat: None,
2547 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2548 invalid_last_hops.push(invalid_last_hop);
2550 let payee = Payee::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2551 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2552 assert_eq!(err, "Route hint cannot have the payee as the source.");
2553 } else { panic!(); }
2556 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2557 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2558 assert_eq!(route.paths[0].len(), 5);
2560 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2561 assert_eq!(route.paths[0][0].short_channel_id, 2);
2562 assert_eq!(route.paths[0][0].fee_msat, 100);
2563 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2564 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2565 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2567 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2568 assert_eq!(route.paths[0][1].short_channel_id, 4);
2569 assert_eq!(route.paths[0][1].fee_msat, 0);
2570 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2571 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2572 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2574 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2575 assert_eq!(route.paths[0][2].short_channel_id, 6);
2576 assert_eq!(route.paths[0][2].fee_msat, 0);
2577 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2578 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2579 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2581 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2582 assert_eq!(route.paths[0][3].short_channel_id, 11);
2583 assert_eq!(route.paths[0][3].fee_msat, 0);
2584 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2585 // If we have a peer in the node map, we'll use their features here since we don't have
2586 // a way of figuring out their features from the invoice:
2587 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2588 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2590 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2591 assert_eq!(route.paths[0][4].short_channel_id, 8);
2592 assert_eq!(route.paths[0][4].fee_msat, 100);
2593 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2594 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2595 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2598 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2599 let zero_fees = RoutingFees {
2601 proportional_millionths: 0,
2603 vec![RouteHint(vec![RouteHintHop {
2604 src_node_id: nodes[3],
2605 short_channel_id: 8,
2607 cltv_expiry_delta: (8 << 8) | 1,
2608 htlc_minimum_msat: None,
2609 htlc_maximum_msat: None,
2610 }]), RouteHint(vec![
2612 ]), RouteHint(vec![RouteHintHop {
2613 src_node_id: nodes[5],
2614 short_channel_id: 10,
2616 cltv_expiry_delta: (10 << 8) | 1,
2617 htlc_minimum_msat: None,
2618 htlc_maximum_msat: None,
2623 fn ignores_empty_last_hops_test() {
2624 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2625 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2626 let payee = Payee::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2627 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2629 // Test handling of an empty RouteHint passed in Invoice.
2631 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2632 assert_eq!(route.paths[0].len(), 5);
2634 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2635 assert_eq!(route.paths[0][0].short_channel_id, 2);
2636 assert_eq!(route.paths[0][0].fee_msat, 100);
2637 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2638 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2639 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2641 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2642 assert_eq!(route.paths[0][1].short_channel_id, 4);
2643 assert_eq!(route.paths[0][1].fee_msat, 0);
2644 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2645 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2646 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2648 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2649 assert_eq!(route.paths[0][2].short_channel_id, 6);
2650 assert_eq!(route.paths[0][2].fee_msat, 0);
2651 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2652 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2653 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2655 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2656 assert_eq!(route.paths[0][3].short_channel_id, 11);
2657 assert_eq!(route.paths[0][3].fee_msat, 0);
2658 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2659 // If we have a peer in the node map, we'll use their features here since we don't have
2660 // a way of figuring out their features from the invoice:
2661 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2662 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2664 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2665 assert_eq!(route.paths[0][4].short_channel_id, 8);
2666 assert_eq!(route.paths[0][4].fee_msat, 100);
2667 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2668 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2669 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2672 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2673 let zero_fees = RoutingFees {
2675 proportional_millionths: 0,
2677 vec![RouteHint(vec![RouteHintHop {
2678 src_node_id: nodes[2],
2679 short_channel_id: 5,
2682 proportional_millionths: 0,
2684 cltv_expiry_delta: (5 << 8) | 1,
2685 htlc_minimum_msat: None,
2686 htlc_maximum_msat: None,
2688 src_node_id: nodes[3],
2689 short_channel_id: 8,
2691 cltv_expiry_delta: (8 << 8) | 1,
2692 htlc_minimum_msat: None,
2693 htlc_maximum_msat: None,
2694 }]), RouteHint(vec![RouteHintHop {
2695 src_node_id: nodes[5],
2696 short_channel_id: 10,
2698 cltv_expiry_delta: (10 << 8) | 1,
2699 htlc_minimum_msat: None,
2700 htlc_maximum_msat: None,
2705 fn multi_hint_last_hops_test() {
2706 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2707 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2708 let payee = Payee::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2709 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2710 // Test through channels 2, 3, 5, 8.
2711 // Test shows that multiple hop hints are considered.
2713 // Disabling channels 6 & 7 by flags=2
2714 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2715 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2716 short_channel_id: 6,
2718 flags: 2, // to disable
2719 cltv_expiry_delta: 0,
2720 htlc_minimum_msat: 0,
2721 htlc_maximum_msat: OptionalField::Absent,
2723 fee_proportional_millionths: 0,
2724 excess_data: Vec::new()
2726 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2727 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2728 short_channel_id: 7,
2730 flags: 2, // to disable
2731 cltv_expiry_delta: 0,
2732 htlc_minimum_msat: 0,
2733 htlc_maximum_msat: OptionalField::Absent,
2735 fee_proportional_millionths: 0,
2736 excess_data: Vec::new()
2739 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2740 assert_eq!(route.paths[0].len(), 4);
2742 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2743 assert_eq!(route.paths[0][0].short_channel_id, 2);
2744 assert_eq!(route.paths[0][0].fee_msat, 200);
2745 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2746 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2747 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2749 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2750 assert_eq!(route.paths[0][1].short_channel_id, 4);
2751 assert_eq!(route.paths[0][1].fee_msat, 100);
2752 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2753 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2754 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2756 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2757 assert_eq!(route.paths[0][2].short_channel_id, 5);
2758 assert_eq!(route.paths[0][2].fee_msat, 0);
2759 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2760 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2761 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2763 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2764 assert_eq!(route.paths[0][3].short_channel_id, 8);
2765 assert_eq!(route.paths[0][3].fee_msat, 100);
2766 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2767 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2768 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2771 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2772 let zero_fees = RoutingFees {
2774 proportional_millionths: 0,
2776 vec![RouteHint(vec![RouteHintHop {
2777 src_node_id: nodes[4],
2778 short_channel_id: 11,
2780 cltv_expiry_delta: (11 << 8) | 1,
2781 htlc_minimum_msat: None,
2782 htlc_maximum_msat: None,
2784 src_node_id: nodes[3],
2785 short_channel_id: 8,
2787 cltv_expiry_delta: (8 << 8) | 1,
2788 htlc_minimum_msat: None,
2789 htlc_maximum_msat: None,
2790 }]), RouteHint(vec![RouteHintHop {
2791 src_node_id: nodes[4],
2792 short_channel_id: 9,
2795 proportional_millionths: 0,
2797 cltv_expiry_delta: (9 << 8) | 1,
2798 htlc_minimum_msat: None,
2799 htlc_maximum_msat: None,
2800 }]), RouteHint(vec![RouteHintHop {
2801 src_node_id: nodes[5],
2802 short_channel_id: 10,
2804 cltv_expiry_delta: (10 << 8) | 1,
2805 htlc_minimum_msat: None,
2806 htlc_maximum_msat: None,
2811 fn last_hops_with_public_channel_test() {
2812 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2813 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2814 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2815 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2816 // This test shows that public routes can be present in the invoice
2817 // which would be handled in the same manner.
2819 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2820 assert_eq!(route.paths[0].len(), 5);
2822 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2823 assert_eq!(route.paths[0][0].short_channel_id, 2);
2824 assert_eq!(route.paths[0][0].fee_msat, 100);
2825 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2826 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2827 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2829 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2830 assert_eq!(route.paths[0][1].short_channel_id, 4);
2831 assert_eq!(route.paths[0][1].fee_msat, 0);
2832 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2833 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2834 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2836 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2837 assert_eq!(route.paths[0][2].short_channel_id, 6);
2838 assert_eq!(route.paths[0][2].fee_msat, 0);
2839 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2840 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2841 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2843 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2844 assert_eq!(route.paths[0][3].short_channel_id, 11);
2845 assert_eq!(route.paths[0][3].fee_msat, 0);
2846 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2847 // If we have a peer in the node map, we'll use their features here since we don't have
2848 // a way of figuring out their features from the invoice:
2849 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2850 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2852 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2853 assert_eq!(route.paths[0][4].short_channel_id, 8);
2854 assert_eq!(route.paths[0][4].fee_msat, 100);
2855 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2856 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2857 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2861 fn our_chans_last_hop_connect_test() {
2862 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2863 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2864 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2866 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2867 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2868 let mut last_hops = last_hops(&nodes);
2869 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2870 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2871 assert_eq!(route.paths[0].len(), 2);
2873 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2874 assert_eq!(route.paths[0][0].short_channel_id, 42);
2875 assert_eq!(route.paths[0][0].fee_msat, 0);
2876 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2877 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2878 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2880 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2881 assert_eq!(route.paths[0][1].short_channel_id, 8);
2882 assert_eq!(route.paths[0][1].fee_msat, 100);
2883 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2884 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2885 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2887 last_hops[0].0[0].fees.base_msat = 1000;
2889 // Revert to via 6 as the fee on 8 goes up
2890 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops);
2891 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2892 assert_eq!(route.paths[0].len(), 4);
2894 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2895 assert_eq!(route.paths[0][0].short_channel_id, 2);
2896 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2897 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2898 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2899 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2901 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2902 assert_eq!(route.paths[0][1].short_channel_id, 4);
2903 assert_eq!(route.paths[0][1].fee_msat, 100);
2904 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2905 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2906 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2908 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2909 assert_eq!(route.paths[0][2].short_channel_id, 7);
2910 assert_eq!(route.paths[0][2].fee_msat, 0);
2911 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2912 // If we have a peer in the node map, we'll use their features here since we don't have
2913 // a way of figuring out their features from the invoice:
2914 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2915 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2917 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2918 assert_eq!(route.paths[0][3].short_channel_id, 10);
2919 assert_eq!(route.paths[0][3].fee_msat, 100);
2920 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2921 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2922 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2924 // ...but still use 8 for larger payments as 6 has a variable feerate
2925 let route = get_route(&our_id, &payee, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2926 assert_eq!(route.paths[0].len(), 5);
2928 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2929 assert_eq!(route.paths[0][0].short_channel_id, 2);
2930 assert_eq!(route.paths[0][0].fee_msat, 3000);
2931 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2932 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2933 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2935 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2936 assert_eq!(route.paths[0][1].short_channel_id, 4);
2937 assert_eq!(route.paths[0][1].fee_msat, 0);
2938 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2939 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2940 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2942 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2943 assert_eq!(route.paths[0][2].short_channel_id, 6);
2944 assert_eq!(route.paths[0][2].fee_msat, 0);
2945 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2946 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2947 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2949 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2950 assert_eq!(route.paths[0][3].short_channel_id, 11);
2951 assert_eq!(route.paths[0][3].fee_msat, 1000);
2952 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2953 // If we have a peer in the node map, we'll use their features here since we don't have
2954 // a way of figuring out their features from the invoice:
2955 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2956 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2958 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2959 assert_eq!(route.paths[0][4].short_channel_id, 8);
2960 assert_eq!(route.paths[0][4].fee_msat, 2000);
2961 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2962 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2963 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2966 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> {
2967 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2968 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2969 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2971 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2972 let last_hops = RouteHint(vec![RouteHintHop {
2973 src_node_id: middle_node_id,
2974 short_channel_id: 8,
2977 proportional_millionths: last_hop_fee_prop,
2979 cltv_expiry_delta: (8 << 8) | 1,
2980 htlc_minimum_msat: None,
2981 htlc_maximum_msat: last_hop_htlc_max,
2983 let payee = Payee::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
2984 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2985 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2986 get_route(&source_node_id, &payee, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer)
2990 fn unannounced_path_test() {
2991 // We should be able to send a payment to a destination without any help of a routing graph
2992 // if we have a channel with a common counterparty that appears in the first and last hop
2994 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2996 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2997 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2998 assert_eq!(route.paths[0].len(), 2);
3000 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3001 assert_eq!(route.paths[0][0].short_channel_id, 42);
3002 assert_eq!(route.paths[0][0].fee_msat, 1001);
3003 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
3004 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3005 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3007 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3008 assert_eq!(route.paths[0][1].short_channel_id, 8);
3009 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3010 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3011 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3012 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3016 fn overflow_unannounced_path_test_liquidity_underflow() {
3017 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3018 // the last-hop had a fee which overflowed a u64, we'd panic.
3019 // This was due to us adding the first-hop from us unconditionally, causing us to think
3020 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3021 // In this test, we previously hit a subtraction underflow due to having less available
3022 // liquidity at the last hop than 0.
3023 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());
3027 fn overflow_unannounced_path_test_feerate_overflow() {
3028 // This tests for the same case as above, except instead of hitting a subtraction
3029 // underflow, we hit a case where the fee charged at a hop overflowed.
3030 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());
3034 fn available_amount_while_routing_test() {
3035 // Tests whether we choose the correct available channel amount while routing.
3037 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3038 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3039 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3040 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3042 // We will use a simple single-path route from
3043 // our node to node2 via node0: channels {1, 3}.
3045 // First disable all other paths.
3046 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3048 short_channel_id: 2,
3051 cltv_expiry_delta: 0,
3052 htlc_minimum_msat: 0,
3053 htlc_maximum_msat: OptionalField::Present(100_000),
3055 fee_proportional_millionths: 0,
3056 excess_data: Vec::new()
3058 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3060 short_channel_id: 12,
3063 cltv_expiry_delta: 0,
3064 htlc_minimum_msat: 0,
3065 htlc_maximum_msat: OptionalField::Present(100_000),
3067 fee_proportional_millionths: 0,
3068 excess_data: Vec::new()
3071 // Make the first channel (#1) very permissive,
3072 // and we will be testing all limits on the second channel.
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: 1,
3078 cltv_expiry_delta: 0,
3079 htlc_minimum_msat: 0,
3080 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3082 fee_proportional_millionths: 0,
3083 excess_data: Vec::new()
3086 // First, let's see if routing works if we have absolutely no idea about the available amount.
3087 // In this case, it should be set to 250_000 sats.
3088 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3089 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3090 short_channel_id: 3,
3093 cltv_expiry_delta: 0,
3094 htlc_minimum_msat: 0,
3095 htlc_maximum_msat: OptionalField::Absent,
3097 fee_proportional_millionths: 0,
3098 excess_data: Vec::new()
3102 // Attempt to route more than available results in a failure.
3103 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3104 &our_id, &payee, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3105 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3106 } else { panic!(); }
3110 // Now, attempt to route an exact amount we have should be fine.
3111 let route = get_route(&our_id, &payee, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3112 assert_eq!(route.paths.len(), 1);
3113 let path = route.paths.last().unwrap();
3114 assert_eq!(path.len(), 2);
3115 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3116 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3119 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3120 // Disable channel #1 and use another first hop.
3121 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3122 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3123 short_channel_id: 1,
3126 cltv_expiry_delta: 0,
3127 htlc_minimum_msat: 0,
3128 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3130 fee_proportional_millionths: 0,
3131 excess_data: Vec::new()
3134 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3135 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3138 // Attempt to route more than available results in a failure.
3139 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3140 &our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3141 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3142 } else { panic!(); }
3146 // Now, attempt to route an exact amount we have should be fine.
3147 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3148 assert_eq!(route.paths.len(), 1);
3149 let path = route.paths.last().unwrap();
3150 assert_eq!(path.len(), 2);
3151 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3152 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3155 // Enable channel #1 back.
3156 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3158 short_channel_id: 1,
3161 cltv_expiry_delta: 0,
3162 htlc_minimum_msat: 0,
3163 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3165 fee_proportional_millionths: 0,
3166 excess_data: Vec::new()
3170 // Now let's see if routing works if we know only htlc_maximum_msat.
3171 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3173 short_channel_id: 3,
3176 cltv_expiry_delta: 0,
3177 htlc_minimum_msat: 0,
3178 htlc_maximum_msat: OptionalField::Present(15_000),
3180 fee_proportional_millionths: 0,
3181 excess_data: Vec::new()
3185 // Attempt to route more than available results in a failure.
3186 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3187 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3188 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3189 } else { panic!(); }
3193 // Now, attempt to route an exact amount we have should be fine.
3194 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3195 assert_eq!(route.paths.len(), 1);
3196 let path = route.paths.last().unwrap();
3197 assert_eq!(path.len(), 2);
3198 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3199 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3202 // Now let's see if routing works if we know only capacity from the UTXO.
3204 // We can't change UTXO capacity on the fly, so we'll disable
3205 // the existing channel and add another one with the capacity we need.
3206 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3208 short_channel_id: 3,
3211 cltv_expiry_delta: 0,
3212 htlc_minimum_msat: 0,
3213 htlc_maximum_msat: OptionalField::Absent,
3215 fee_proportional_millionths: 0,
3216 excess_data: Vec::new()
3219 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3220 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3221 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3222 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3223 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3225 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3226 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3228 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3229 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3231 short_channel_id: 333,
3234 cltv_expiry_delta: (3 << 8) | 1,
3235 htlc_minimum_msat: 0,
3236 htlc_maximum_msat: OptionalField::Absent,
3238 fee_proportional_millionths: 0,
3239 excess_data: Vec::new()
3241 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3242 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3243 short_channel_id: 333,
3246 cltv_expiry_delta: (3 << 8) | 2,
3247 htlc_minimum_msat: 0,
3248 htlc_maximum_msat: OptionalField::Absent,
3250 fee_proportional_millionths: 0,
3251 excess_data: Vec::new()
3255 // Attempt to route more than available results in a failure.
3256 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3257 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3258 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3259 } else { panic!(); }
3263 // Now, attempt to route an exact amount we have should be fine.
3264 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3265 assert_eq!(route.paths.len(), 1);
3266 let path = route.paths.last().unwrap();
3267 assert_eq!(path.len(), 2);
3268 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3269 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3272 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3273 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3275 short_channel_id: 333,
3278 cltv_expiry_delta: 0,
3279 htlc_minimum_msat: 0,
3280 htlc_maximum_msat: OptionalField::Present(10_000),
3282 fee_proportional_millionths: 0,
3283 excess_data: Vec::new()
3287 // Attempt to route more than available results in a failure.
3288 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3289 &our_id, &payee, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3290 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3291 } else { panic!(); }
3295 // Now, attempt to route an exact amount we have should be fine.
3296 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3297 assert_eq!(route.paths.len(), 1);
3298 let path = route.paths.last().unwrap();
3299 assert_eq!(path.len(), 2);
3300 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3301 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3306 fn available_liquidity_last_hop_test() {
3307 // Check that available liquidity properly limits the path even when only
3308 // one of the latter hops is limited.
3309 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3310 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3311 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3312 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3314 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3315 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3316 // Total capacity: 50 sats.
3318 // Disable other potential paths.
3319 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3321 short_channel_id: 2,
3324 cltv_expiry_delta: 0,
3325 htlc_minimum_msat: 0,
3326 htlc_maximum_msat: OptionalField::Present(100_000),
3328 fee_proportional_millionths: 0,
3329 excess_data: Vec::new()
3331 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3333 short_channel_id: 7,
3336 cltv_expiry_delta: 0,
3337 htlc_minimum_msat: 0,
3338 htlc_maximum_msat: OptionalField::Present(100_000),
3340 fee_proportional_millionths: 0,
3341 excess_data: Vec::new()
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: 12,
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[7], UnsignedChannelUpdate {
3359 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3360 short_channel_id: 13,
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()
3371 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3372 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3373 short_channel_id: 6,
3376 cltv_expiry_delta: 0,
3377 htlc_minimum_msat: 0,
3378 htlc_maximum_msat: OptionalField::Present(50_000),
3380 fee_proportional_millionths: 0,
3381 excess_data: Vec::new()
3383 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3384 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3385 short_channel_id: 11,
3388 cltv_expiry_delta: 0,
3389 htlc_minimum_msat: 0,
3390 htlc_maximum_msat: OptionalField::Present(100_000),
3392 fee_proportional_millionths: 0,
3393 excess_data: Vec::new()
3396 // Attempt to route more than available results in a failure.
3397 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3398 &our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3399 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3400 } else { panic!(); }
3404 // Now, attempt to route 49 sats (just a bit below the capacity).
3405 let route = get_route(&our_id, &payee, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3406 assert_eq!(route.paths.len(), 1);
3407 let mut total_amount_paid_msat = 0;
3408 for path in &route.paths {
3409 assert_eq!(path.len(), 4);
3410 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3411 total_amount_paid_msat += path.last().unwrap().fee_msat;
3413 assert_eq!(total_amount_paid_msat, 49_000);
3417 // Attempt to route an exact amount is also fine
3418 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3419 assert_eq!(route.paths.len(), 1);
3420 let mut total_amount_paid_msat = 0;
3421 for path in &route.paths {
3422 assert_eq!(path.len(), 4);
3423 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3424 total_amount_paid_msat += path.last().unwrap().fee_msat;
3426 assert_eq!(total_amount_paid_msat, 50_000);
3431 fn ignore_fee_first_hop_test() {
3432 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3433 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3434 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3435 let payee = Payee::from_node_id(nodes[2]);
3437 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3438 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3439 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3440 short_channel_id: 1,
3443 cltv_expiry_delta: 0,
3444 htlc_minimum_msat: 0,
3445 htlc_maximum_msat: OptionalField::Present(100_000),
3446 fee_base_msat: 1_000_000,
3447 fee_proportional_millionths: 0,
3448 excess_data: Vec::new()
3450 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3451 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3452 short_channel_id: 3,
3455 cltv_expiry_delta: 0,
3456 htlc_minimum_msat: 0,
3457 htlc_maximum_msat: OptionalField::Present(50_000),
3459 fee_proportional_millionths: 0,
3460 excess_data: Vec::new()
3464 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3465 assert_eq!(route.paths.len(), 1);
3466 let mut total_amount_paid_msat = 0;
3467 for path in &route.paths {
3468 assert_eq!(path.len(), 2);
3469 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3470 total_amount_paid_msat += path.last().unwrap().fee_msat;
3472 assert_eq!(total_amount_paid_msat, 50_000);
3477 fn simple_mpp_route_test() {
3478 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3479 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3480 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3481 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3483 // We need a route consisting of 3 paths:
3484 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3485 // To achieve this, the amount being transferred should be around
3486 // the total capacity of these 3 paths.
3488 // First, we set limits on these (previously unlimited) channels.
3489 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3491 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3492 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3493 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3494 short_channel_id: 1,
3497 cltv_expiry_delta: 0,
3498 htlc_minimum_msat: 0,
3499 htlc_maximum_msat: OptionalField::Present(100_000),
3501 fee_proportional_millionths: 0,
3502 excess_data: Vec::new()
3504 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3505 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3506 short_channel_id: 3,
3509 cltv_expiry_delta: 0,
3510 htlc_minimum_msat: 0,
3511 htlc_maximum_msat: OptionalField::Present(50_000),
3513 fee_proportional_millionths: 0,
3514 excess_data: Vec::new()
3517 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3518 // (total limit 60).
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: 12,
3524 cltv_expiry_delta: 0,
3525 htlc_minimum_msat: 0,
3526 htlc_maximum_msat: OptionalField::Present(60_000),
3528 fee_proportional_millionths: 0,
3529 excess_data: Vec::new()
3531 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3532 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3533 short_channel_id: 13,
3536 cltv_expiry_delta: 0,
3537 htlc_minimum_msat: 0,
3538 htlc_maximum_msat: OptionalField::Present(60_000),
3540 fee_proportional_millionths: 0,
3541 excess_data: Vec::new()
3544 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3545 // (total capacity 180 sats).
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: 2,
3551 cltv_expiry_delta: 0,
3552 htlc_minimum_msat: 0,
3553 htlc_maximum_msat: OptionalField::Present(200_000),
3555 fee_proportional_millionths: 0,
3556 excess_data: Vec::new()
3558 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3560 short_channel_id: 4,
3563 cltv_expiry_delta: 0,
3564 htlc_minimum_msat: 0,
3565 htlc_maximum_msat: OptionalField::Present(180_000),
3567 fee_proportional_millionths: 0,
3568 excess_data: Vec::new()
3572 // Attempt to route more than available results in a failure.
3573 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3574 &our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3575 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3576 } else { panic!(); }
3580 // Now, attempt to route 250 sats (just a bit below the capacity).
3581 // Our algorithm should provide us with these 3 paths.
3582 let route = get_route(&our_id, &payee, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3583 assert_eq!(route.paths.len(), 3);
3584 let mut total_amount_paid_msat = 0;
3585 for path in &route.paths {
3586 assert_eq!(path.len(), 2);
3587 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3588 total_amount_paid_msat += path.last().unwrap().fee_msat;
3590 assert_eq!(total_amount_paid_msat, 250_000);
3594 // Attempt to route an exact amount is also fine
3595 let route = get_route(&our_id, &payee, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3596 assert_eq!(route.paths.len(), 3);
3597 let mut total_amount_paid_msat = 0;
3598 for path in &route.paths {
3599 assert_eq!(path.len(), 2);
3600 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3601 total_amount_paid_msat += path.last().unwrap().fee_msat;
3603 assert_eq!(total_amount_paid_msat, 290_000);
3608 fn long_mpp_route_test() {
3609 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3610 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3611 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3612 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3614 // We need a route consisting of 3 paths:
3615 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3616 // Note that these paths overlap (channels 5, 12, 13).
3617 // We will route 300 sats.
3618 // Each path will have 100 sats capacity, those channels which
3619 // are used twice will have 200 sats capacity.
3621 // Disable other potential paths.
3622 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3624 short_channel_id: 2,
3627 cltv_expiry_delta: 0,
3628 htlc_minimum_msat: 0,
3629 htlc_maximum_msat: OptionalField::Present(100_000),
3631 fee_proportional_millionths: 0,
3632 excess_data: Vec::new()
3634 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3636 short_channel_id: 7,
3639 cltv_expiry_delta: 0,
3640 htlc_minimum_msat: 0,
3641 htlc_maximum_msat: OptionalField::Present(100_000),
3643 fee_proportional_millionths: 0,
3644 excess_data: Vec::new()
3647 // Path via {node0, node2} is channels {1, 3, 5}.
3648 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3649 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3650 short_channel_id: 1,
3653 cltv_expiry_delta: 0,
3654 htlc_minimum_msat: 0,
3655 htlc_maximum_msat: OptionalField::Present(100_000),
3657 fee_proportional_millionths: 0,
3658 excess_data: Vec::new()
3660 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3662 short_channel_id: 3,
3665 cltv_expiry_delta: 0,
3666 htlc_minimum_msat: 0,
3667 htlc_maximum_msat: OptionalField::Present(100_000),
3669 fee_proportional_millionths: 0,
3670 excess_data: Vec::new()
3673 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3674 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3675 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3676 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3677 short_channel_id: 5,
3680 cltv_expiry_delta: 0,
3681 htlc_minimum_msat: 0,
3682 htlc_maximum_msat: OptionalField::Present(200_000),
3684 fee_proportional_millionths: 0,
3685 excess_data: Vec::new()
3688 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3689 // Add 100 sats to the capacities of {12, 13}, because these channels
3690 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3691 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3693 short_channel_id: 12,
3696 cltv_expiry_delta: 0,
3697 htlc_minimum_msat: 0,
3698 htlc_maximum_msat: OptionalField::Present(200_000),
3700 fee_proportional_millionths: 0,
3701 excess_data: Vec::new()
3703 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3705 short_channel_id: 13,
3708 cltv_expiry_delta: 0,
3709 htlc_minimum_msat: 0,
3710 htlc_maximum_msat: OptionalField::Present(200_000),
3712 fee_proportional_millionths: 0,
3713 excess_data: Vec::new()
3716 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3718 short_channel_id: 6,
3721 cltv_expiry_delta: 0,
3722 htlc_minimum_msat: 0,
3723 htlc_maximum_msat: OptionalField::Present(100_000),
3725 fee_proportional_millionths: 0,
3726 excess_data: Vec::new()
3728 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3729 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3730 short_channel_id: 11,
3733 cltv_expiry_delta: 0,
3734 htlc_minimum_msat: 0,
3735 htlc_maximum_msat: OptionalField::Present(100_000),
3737 fee_proportional_millionths: 0,
3738 excess_data: Vec::new()
3741 // Path via {node7, node2} is channels {12, 13, 5}.
3742 // We already limited them to 200 sats (they are used twice for 100 sats).
3743 // Nothing to do here.
3746 // Attempt to route more than available results in a failure.
3747 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3748 &our_id, &payee, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3749 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3750 } else { panic!(); }
3754 // Now, attempt to route 300 sats (exact amount we can route).
3755 // Our algorithm should provide us with these 3 paths, 100 sats each.
3756 let route = get_route(&our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3757 assert_eq!(route.paths.len(), 3);
3759 let mut total_amount_paid_msat = 0;
3760 for path in &route.paths {
3761 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3762 total_amount_paid_msat += path.last().unwrap().fee_msat;
3764 assert_eq!(total_amount_paid_msat, 300_000);
3770 fn mpp_cheaper_route_test() {
3771 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3772 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3773 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3774 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3776 // This test checks that if we have two cheaper paths and one more expensive path,
3777 // so that liquidity-wise any 2 of 3 combination is sufficient,
3778 // two cheaper paths will be taken.
3779 // These paths have equal available liquidity.
3781 // We need a combination of 3 paths:
3782 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3783 // Note that these paths overlap (channels 5, 12, 13).
3784 // Each path will have 100 sats capacity, those channels which
3785 // are used twice will have 200 sats capacity.
3787 // Disable other potential paths.
3788 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3789 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3790 short_channel_id: 2,
3793 cltv_expiry_delta: 0,
3794 htlc_minimum_msat: 0,
3795 htlc_maximum_msat: OptionalField::Present(100_000),
3797 fee_proportional_millionths: 0,
3798 excess_data: Vec::new()
3800 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3802 short_channel_id: 7,
3805 cltv_expiry_delta: 0,
3806 htlc_minimum_msat: 0,
3807 htlc_maximum_msat: OptionalField::Present(100_000),
3809 fee_proportional_millionths: 0,
3810 excess_data: Vec::new()
3813 // Path via {node0, node2} is channels {1, 3, 5}.
3814 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3816 short_channel_id: 1,
3819 cltv_expiry_delta: 0,
3820 htlc_minimum_msat: 0,
3821 htlc_maximum_msat: OptionalField::Present(100_000),
3823 fee_proportional_millionths: 0,
3824 excess_data: Vec::new()
3826 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3828 short_channel_id: 3,
3831 cltv_expiry_delta: 0,
3832 htlc_minimum_msat: 0,
3833 htlc_maximum_msat: OptionalField::Present(100_000),
3835 fee_proportional_millionths: 0,
3836 excess_data: Vec::new()
3839 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3840 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3841 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3843 short_channel_id: 5,
3846 cltv_expiry_delta: 0,
3847 htlc_minimum_msat: 0,
3848 htlc_maximum_msat: OptionalField::Present(200_000),
3850 fee_proportional_millionths: 0,
3851 excess_data: Vec::new()
3854 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3855 // Add 100 sats to the capacities of {12, 13}, because these channels
3856 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3857 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3859 short_channel_id: 12,
3862 cltv_expiry_delta: 0,
3863 htlc_minimum_msat: 0,
3864 htlc_maximum_msat: OptionalField::Present(200_000),
3866 fee_proportional_millionths: 0,
3867 excess_data: Vec::new()
3869 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3870 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3871 short_channel_id: 13,
3874 cltv_expiry_delta: 0,
3875 htlc_minimum_msat: 0,
3876 htlc_maximum_msat: OptionalField::Present(200_000),
3878 fee_proportional_millionths: 0,
3879 excess_data: Vec::new()
3882 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3884 short_channel_id: 6,
3887 cltv_expiry_delta: 0,
3888 htlc_minimum_msat: 0,
3889 htlc_maximum_msat: OptionalField::Present(100_000),
3890 fee_base_msat: 1_000,
3891 fee_proportional_millionths: 0,
3892 excess_data: Vec::new()
3894 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3896 short_channel_id: 11,
3899 cltv_expiry_delta: 0,
3900 htlc_minimum_msat: 0,
3901 htlc_maximum_msat: OptionalField::Present(100_000),
3903 fee_proportional_millionths: 0,
3904 excess_data: Vec::new()
3907 // Path via {node7, node2} is channels {12, 13, 5}.
3908 // We already limited them to 200 sats (they are used twice for 100 sats).
3909 // Nothing to do here.
3912 // Now, attempt to route 180 sats.
3913 // Our algorithm should provide us with these 2 paths.
3914 let route = get_route(&our_id, &payee, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3915 assert_eq!(route.paths.len(), 2);
3917 let mut total_value_transferred_msat = 0;
3918 let mut total_paid_msat = 0;
3919 for path in &route.paths {
3920 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3921 total_value_transferred_msat += path.last().unwrap().fee_msat;
3923 total_paid_msat += hop.fee_msat;
3926 // If we paid fee, this would be higher.
3927 assert_eq!(total_value_transferred_msat, 180_000);
3928 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3929 assert_eq!(total_fees_paid, 0);
3934 fn fees_on_mpp_route_test() {
3935 // This test makes sure that MPP algorithm properly takes into account
3936 // fees charged on the channels, by making the fees impactful:
3937 // if the fee is not properly accounted for, the behavior is different.
3938 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3939 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3940 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3941 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3943 // We need a route consisting of 2 paths:
3944 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3945 // We will route 200 sats, Each path will have 100 sats capacity.
3947 // This test is not particularly stable: e.g.,
3948 // there's a way to route via {node0, node2, node4}.
3949 // It works while pathfinding is deterministic, but can be broken otherwise.
3950 // It's fine to ignore this concern for now.
3952 // Disable other potential paths.
3953 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3955 short_channel_id: 2,
3958 cltv_expiry_delta: 0,
3959 htlc_minimum_msat: 0,
3960 htlc_maximum_msat: OptionalField::Present(100_000),
3962 fee_proportional_millionths: 0,
3963 excess_data: Vec::new()
3966 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3968 short_channel_id: 7,
3971 cltv_expiry_delta: 0,
3972 htlc_minimum_msat: 0,
3973 htlc_maximum_msat: OptionalField::Present(100_000),
3975 fee_proportional_millionths: 0,
3976 excess_data: Vec::new()
3979 // Path via {node0, node2} is channels {1, 3, 5}.
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: 1,
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()
3992 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3994 short_channel_id: 3,
3997 cltv_expiry_delta: 0,
3998 htlc_minimum_msat: 0,
3999 htlc_maximum_msat: OptionalField::Present(100_000),
4001 fee_proportional_millionths: 0,
4002 excess_data: Vec::new()
4005 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4006 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4007 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4008 short_channel_id: 5,
4011 cltv_expiry_delta: 0,
4012 htlc_minimum_msat: 0,
4013 htlc_maximum_msat: OptionalField::Present(100_000),
4015 fee_proportional_millionths: 0,
4016 excess_data: Vec::new()
4019 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4020 // All channels should be 100 sats capacity. But for the fee experiment,
4021 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4022 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4023 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4024 // so no matter how large are other channels,
4025 // the whole path will be limited by 100 sats with just these 2 conditions:
4026 // - channel 12 capacity is 250 sats
4027 // - fee for channel 6 is 150 sats
4028 // Let's test this by enforcing these 2 conditions and removing other limits.
4029 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4031 short_channel_id: 12,
4034 cltv_expiry_delta: 0,
4035 htlc_minimum_msat: 0,
4036 htlc_maximum_msat: OptionalField::Present(250_000),
4038 fee_proportional_millionths: 0,
4039 excess_data: Vec::new()
4041 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4043 short_channel_id: 13,
4046 cltv_expiry_delta: 0,
4047 htlc_minimum_msat: 0,
4048 htlc_maximum_msat: OptionalField::Absent,
4050 fee_proportional_millionths: 0,
4051 excess_data: Vec::new()
4054 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4056 short_channel_id: 6,
4059 cltv_expiry_delta: 0,
4060 htlc_minimum_msat: 0,
4061 htlc_maximum_msat: OptionalField::Absent,
4062 fee_base_msat: 150_000,
4063 fee_proportional_millionths: 0,
4064 excess_data: Vec::new()
4066 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4068 short_channel_id: 11,
4071 cltv_expiry_delta: 0,
4072 htlc_minimum_msat: 0,
4073 htlc_maximum_msat: OptionalField::Absent,
4075 fee_proportional_millionths: 0,
4076 excess_data: Vec::new()
4080 // Attempt to route more than available results in a failure.
4081 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4082 &our_id, &payee, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4083 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4084 } else { panic!(); }
4088 // Now, attempt to route 200 sats (exact amount we can route).
4089 let route = get_route(&our_id, &payee, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4090 assert_eq!(route.paths.len(), 2);
4092 let mut total_amount_paid_msat = 0;
4093 for path in &route.paths {
4094 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4095 total_amount_paid_msat += path.last().unwrap().fee_msat;
4097 assert_eq!(total_amount_paid_msat, 200_000);
4098 assert_eq!(route.get_total_fees(), 150_000);
4103 fn mpp_with_last_hops() {
4104 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4105 // via a single last-hop route hint, we'd fail to route if we first collected routes
4106 // totaling close but not quite enough to fund the full payment.
4108 // This was because we considered last-hop hints to have exactly the sought payment amount
4109 // instead of the amount we were trying to collect, needlessly limiting our path searching
4110 // at the very first hop.
4112 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4113 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4114 // to only have the remaining to-collect amount in available liquidity.
4116 // This bug appeared in production in some specific channel configurations.
4117 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4118 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4119 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4120 let payee = Payee::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4121 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4122 src_node_id: nodes[2],
4123 short_channel_id: 42,
4124 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4125 cltv_expiry_delta: 42,
4126 htlc_minimum_msat: None,
4127 htlc_maximum_msat: None,
4130 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4131 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4132 // would first use the no-fee route and then fail to find a path along the second route as
4133 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4134 // under 5% of our payment amount.
4135 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4137 short_channel_id: 1,
4140 cltv_expiry_delta: u16::max_value(),
4141 htlc_minimum_msat: 0,
4142 htlc_maximum_msat: OptionalField::Present(99_000),
4143 fee_base_msat: u32::max_value(),
4144 fee_proportional_millionths: u32::max_value(),
4145 excess_data: Vec::new()
4147 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4148 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4149 short_channel_id: 2,
4152 cltv_expiry_delta: u16::max_value(),
4153 htlc_minimum_msat: 0,
4154 htlc_maximum_msat: OptionalField::Present(99_000),
4155 fee_base_msat: u32::max_value(),
4156 fee_proportional_millionths: u32::max_value(),
4157 excess_data: Vec::new()
4159 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4160 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4161 short_channel_id: 4,
4164 cltv_expiry_delta: (4 << 8) | 1,
4165 htlc_minimum_msat: 0,
4166 htlc_maximum_msat: OptionalField::Absent,
4168 fee_proportional_millionths: 0,
4169 excess_data: Vec::new()
4171 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4173 short_channel_id: 13,
4175 flags: 0|2, // Channel disabled
4176 cltv_expiry_delta: (13 << 8) | 1,
4177 htlc_minimum_msat: 0,
4178 htlc_maximum_msat: OptionalField::Absent,
4180 fee_proportional_millionths: 2000000,
4181 excess_data: Vec::new()
4184 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4186 let route = get_route(&our_id, &payee, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4187 assert_eq!(route.paths.len(), 2);
4188 // Paths are somewhat randomly ordered, but:
4189 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4190 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4191 assert_eq!(route.paths[0][0].short_channel_id, 2);
4192 assert_eq!(route.paths[0][0].fee_msat, 1);
4193 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4194 assert_eq!(route.paths[1][0].short_channel_id, 1);
4195 assert_eq!(route.paths[1][0].fee_msat, 0);
4196 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4197 assert_eq!(route.get_total_fees(), 1);
4198 assert_eq!(route.get_total_amount(), 100_000);
4202 fn drop_lowest_channel_mpp_route_test() {
4203 // This test checks that low-capacity channel is dropped when after
4204 // path finding we realize that we found more capacity than we need.
4205 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4206 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4207 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4208 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4210 // We need a route consisting of 3 paths:
4211 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4213 // The first and the second paths should be sufficient, but the third should be
4214 // cheaper, so that we select it but drop later.
4216 // First, we set limits on these (previously unlimited) channels.
4217 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4219 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4220 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4222 short_channel_id: 1,
4225 cltv_expiry_delta: 0,
4226 htlc_minimum_msat: 0,
4227 htlc_maximum_msat: OptionalField::Present(100_000),
4229 fee_proportional_millionths: 0,
4230 excess_data: Vec::new()
4232 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4234 short_channel_id: 3,
4237 cltv_expiry_delta: 0,
4238 htlc_minimum_msat: 0,
4239 htlc_maximum_msat: OptionalField::Present(50_000),
4241 fee_proportional_millionths: 0,
4242 excess_data: Vec::new()
4245 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4246 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4248 short_channel_id: 12,
4251 cltv_expiry_delta: 0,
4252 htlc_minimum_msat: 0,
4253 htlc_maximum_msat: OptionalField::Present(60_000),
4255 fee_proportional_millionths: 0,
4256 excess_data: Vec::new()
4258 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260 short_channel_id: 13,
4263 cltv_expiry_delta: 0,
4264 htlc_minimum_msat: 0,
4265 htlc_maximum_msat: OptionalField::Present(60_000),
4267 fee_proportional_millionths: 0,
4268 excess_data: Vec::new()
4271 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4272 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4273 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4274 short_channel_id: 2,
4277 cltv_expiry_delta: 0,
4278 htlc_minimum_msat: 0,
4279 htlc_maximum_msat: OptionalField::Present(20_000),
4281 fee_proportional_millionths: 0,
4282 excess_data: Vec::new()
4284 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4286 short_channel_id: 4,
4289 cltv_expiry_delta: 0,
4290 htlc_minimum_msat: 0,
4291 htlc_maximum_msat: OptionalField::Present(20_000),
4293 fee_proportional_millionths: 0,
4294 excess_data: Vec::new()
4298 // Attempt to route more than available results in a failure.
4299 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4300 &our_id, &payee, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4301 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4302 } else { panic!(); }
4306 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4307 // Our algorithm should provide us with these 3 paths.
4308 let route = get_route(&our_id, &payee, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4309 assert_eq!(route.paths.len(), 3);
4310 let mut total_amount_paid_msat = 0;
4311 for path in &route.paths {
4312 assert_eq!(path.len(), 2);
4313 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4314 total_amount_paid_msat += path.last().unwrap().fee_msat;
4316 assert_eq!(total_amount_paid_msat, 125_000);
4320 // Attempt to route without the last small cheap channel
4321 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4322 assert_eq!(route.paths.len(), 2);
4323 let mut total_amount_paid_msat = 0;
4324 for path in &route.paths {
4325 assert_eq!(path.len(), 2);
4326 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4327 total_amount_paid_msat += path.last().unwrap().fee_msat;
4329 assert_eq!(total_amount_paid_msat, 90_000);
4334 fn min_criteria_consistency() {
4335 // Test that we don't use an inconsistent metric between updating and walking nodes during
4336 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4337 // was updated with a different criterion from the heap sorting, resulting in loops in
4338 // calculated paths. We test for that specific case here.
4340 // We construct a network that looks like this:
4342 // node2 -1(3)2- node3
4346 // node1 -1(5)2- node4 -1(1)2- node6
4352 // We create a loop on the side of our real path - our destination is node 6, with a
4353 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4354 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4355 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4356 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4357 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4358 // "previous hop" being set to node 3, creating a loop in the path.
4359 let secp_ctx = Secp256k1::new();
4360 let logger = Arc::new(test_utils::TestLogger::new());
4361 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4362 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4363 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4364 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4365 let payee = Payee::from_node_id(nodes[6]);
4367 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4368 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4370 short_channel_id: 6,
4373 cltv_expiry_delta: (6 << 8) | 0,
4374 htlc_minimum_msat: 0,
4375 htlc_maximum_msat: OptionalField::Absent,
4377 fee_proportional_millionths: 0,
4378 excess_data: Vec::new()
4380 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4382 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4383 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4384 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4385 short_channel_id: 5,
4388 cltv_expiry_delta: (5 << 8) | 0,
4389 htlc_minimum_msat: 0,
4390 htlc_maximum_msat: OptionalField::Absent,
4392 fee_proportional_millionths: 0,
4393 excess_data: Vec::new()
4395 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4397 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4398 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4400 short_channel_id: 4,
4403 cltv_expiry_delta: (4 << 8) | 0,
4404 htlc_minimum_msat: 0,
4405 htlc_maximum_msat: OptionalField::Absent,
4407 fee_proportional_millionths: 0,
4408 excess_data: Vec::new()
4410 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4412 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4413 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4414 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4415 short_channel_id: 3,
4418 cltv_expiry_delta: (3 << 8) | 0,
4419 htlc_minimum_msat: 0,
4420 htlc_maximum_msat: OptionalField::Absent,
4422 fee_proportional_millionths: 0,
4423 excess_data: Vec::new()
4425 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4427 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4428 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4429 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4430 short_channel_id: 2,
4433 cltv_expiry_delta: (2 << 8) | 0,
4434 htlc_minimum_msat: 0,
4435 htlc_maximum_msat: OptionalField::Absent,
4437 fee_proportional_millionths: 0,
4438 excess_data: Vec::new()
4441 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4442 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4443 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4444 short_channel_id: 1,
4447 cltv_expiry_delta: (1 << 8) | 0,
4448 htlc_minimum_msat: 100,
4449 htlc_maximum_msat: OptionalField::Absent,
4451 fee_proportional_millionths: 0,
4452 excess_data: Vec::new()
4454 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4457 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4458 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4459 assert_eq!(route.paths.len(), 1);
4460 assert_eq!(route.paths[0].len(), 3);
4462 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4463 assert_eq!(route.paths[0][0].short_channel_id, 6);
4464 assert_eq!(route.paths[0][0].fee_msat, 100);
4465 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4466 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4467 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4469 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4470 assert_eq!(route.paths[0][1].short_channel_id, 5);
4471 assert_eq!(route.paths[0][1].fee_msat, 0);
4472 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4473 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4474 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4476 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4477 assert_eq!(route.paths[0][2].short_channel_id, 1);
4478 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4479 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4480 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4481 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4487 fn exact_fee_liquidity_limit() {
4488 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4489 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4490 // we calculated fees on a higher value, resulting in us ignoring such paths.
4491 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4492 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4493 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4494 let payee = Payee::from_node_id(nodes[2]);
4496 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4498 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4499 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4500 short_channel_id: 2,
4503 cltv_expiry_delta: 0,
4504 htlc_minimum_msat: 0,
4505 htlc_maximum_msat: OptionalField::Present(85_000),
4507 fee_proportional_millionths: 0,
4508 excess_data: Vec::new()
4511 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4512 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4513 short_channel_id: 12,
4516 cltv_expiry_delta: (4 << 8) | 1,
4517 htlc_minimum_msat: 0,
4518 htlc_maximum_msat: OptionalField::Present(270_000),
4520 fee_proportional_millionths: 1000000,
4521 excess_data: Vec::new()
4525 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4526 // 200% fee charged channel 13 in the 1-to-2 direction.
4527 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4528 assert_eq!(route.paths.len(), 1);
4529 assert_eq!(route.paths[0].len(), 2);
4531 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4532 assert_eq!(route.paths[0][0].short_channel_id, 12);
4533 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4534 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4535 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4536 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4538 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4539 assert_eq!(route.paths[0][1].short_channel_id, 13);
4540 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4541 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4542 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4543 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4548 fn htlc_max_reduction_below_min() {
4549 // Test that if, while walking the graph, we reduce the value being sent to meet an
4550 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4551 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4552 // resulting in us thinking there is no possible path, even if other paths exist.
4553 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4554 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4555 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4556 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4558 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4559 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4560 // then try to send 90_000.
4561 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4562 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4563 short_channel_id: 2,
4566 cltv_expiry_delta: 0,
4567 htlc_minimum_msat: 0,
4568 htlc_maximum_msat: OptionalField::Present(80_000),
4570 fee_proportional_millionths: 0,
4571 excess_data: Vec::new()
4573 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4574 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4575 short_channel_id: 4,
4578 cltv_expiry_delta: (4 << 8) | 1,
4579 htlc_minimum_msat: 90_000,
4580 htlc_maximum_msat: OptionalField::Absent,
4582 fee_proportional_millionths: 0,
4583 excess_data: Vec::new()
4587 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4588 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4589 // expensive) channels 12-13 path.
4590 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4591 assert_eq!(route.paths.len(), 1);
4592 assert_eq!(route.paths[0].len(), 2);
4594 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4595 assert_eq!(route.paths[0][0].short_channel_id, 12);
4596 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4597 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4598 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4599 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4601 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4602 assert_eq!(route.paths[0][1].short_channel_id, 13);
4603 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4604 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4605 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4606 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4611 fn multiple_direct_first_hops() {
4612 // Previously we'd only ever considered one first hop path per counterparty.
4613 // However, as we don't restrict users to one channel per peer, we really need to support
4614 // looking at all first hop paths.
4615 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4616 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4617 // route over multiple channels with the same first hop.
4618 let secp_ctx = Secp256k1::new();
4619 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4620 let logger = Arc::new(test_utils::TestLogger::new());
4621 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4622 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4623 let payee = Payee::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4626 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4627 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4628 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4629 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4630 assert_eq!(route.paths.len(), 1);
4631 assert_eq!(route.paths[0].len(), 1);
4633 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4634 assert_eq!(route.paths[0][0].short_channel_id, 3);
4635 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4638 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4639 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4640 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4641 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4642 assert_eq!(route.paths.len(), 2);
4643 assert_eq!(route.paths[0].len(), 1);
4644 assert_eq!(route.paths[1].len(), 1);
4646 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4647 assert_eq!(route.paths[0][0].short_channel_id, 3);
4648 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4650 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4651 assert_eq!(route.paths[1][0].short_channel_id, 2);
4652 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4657 fn prefers_shorter_route_with_higher_fees() {
4658 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4659 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4660 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4662 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4663 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4664 let route = get_route(
4665 &our_id, &payee, &network_graph, None, 100, 42,
4666 Arc::clone(&logger), &scorer
4668 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4670 assert_eq!(route.get_total_fees(), 100);
4671 assert_eq!(route.get_total_amount(), 100);
4672 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4674 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4675 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4676 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4677 let route = get_route(
4678 &our_id, &payee, &network_graph, None, 100, 42,
4679 Arc::clone(&logger), &scorer
4681 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4683 assert_eq!(route.get_total_fees(), 300);
4684 assert_eq!(route.get_total_amount(), 100);
4685 assert_eq!(path, vec![2, 4, 7, 10]);
4688 struct BadChannelScorer {
4689 short_channel_id: u64,
4693 impl Writeable for BadChannelScorer {
4694 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4696 impl Score for BadChannelScorer {
4697 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4698 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4701 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4702 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4705 struct BadNodeScorer {
4710 impl Writeable for BadNodeScorer {
4711 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4714 impl Score for BadNodeScorer {
4715 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4716 if *target == self.node_id { u64::max_value() } else { 0 }
4719 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4720 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4724 fn avoids_routing_through_bad_channels_and_nodes() {
4725 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4726 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4727 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4729 // A path to nodes[6] exists when no penalties are applied to any channel.
4730 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4731 let route = get_route(
4732 &our_id, &payee, &network_graph, None, 100, 42,
4733 Arc::clone(&logger), &scorer
4735 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4737 assert_eq!(route.get_total_fees(), 100);
4738 assert_eq!(route.get_total_amount(), 100);
4739 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4741 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4742 let scorer = BadChannelScorer { short_channel_id: 6 };
4743 let route = get_route(
4744 &our_id, &payee, &network_graph, None, 100, 42,
4745 Arc::clone(&logger), &scorer
4747 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4749 assert_eq!(route.get_total_fees(), 300);
4750 assert_eq!(route.get_total_amount(), 100);
4751 assert_eq!(path, vec![2, 4, 7, 10]);
4753 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4754 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4756 &our_id, &payee, &network_graph, None, 100, 42,
4757 Arc::clone(&logger), &scorer
4759 Err(LightningError { err, .. } ) => {
4760 assert_eq!(err, "Failed to find a path to the given destination");
4762 Ok(_) => panic!("Expected error"),
4767 fn total_fees_single_path() {
4771 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4772 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4773 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4776 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4777 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4778 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4781 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4782 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4783 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4789 assert_eq!(route.get_total_fees(), 250);
4790 assert_eq!(route.get_total_amount(), 225);
4794 fn total_fees_multi_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
4809 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4810 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4811 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4814 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4815 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4816 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4822 assert_eq!(route.get_total_fees(), 200);
4823 assert_eq!(route.get_total_amount(), 300);
4827 fn total_empty_route_no_panic() {
4828 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4829 // would both panic if the route was completely empty. We test to ensure they return 0
4830 // here, even though its somewhat nonsensical as a route.
4831 let route = Route { paths: Vec::new(), payee: None };
4833 assert_eq!(route.get_total_fees(), 0);
4834 assert_eq!(route.get_total_amount(), 0);
4837 #[cfg(not(feature = "no-std"))]
4838 pub(super) fn random_init_seed() -> u64 {
4839 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4840 use core::hash::{BuildHasher, Hasher};
4841 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4842 println!("Using seed of {}", seed);
4845 #[cfg(not(feature = "no-std"))]
4846 use util::ser::Readable;
4849 #[cfg(not(feature = "no-std"))]
4850 fn generate_routes() {
4851 let mut d = match super::test_utils::get_route_file() {
4858 let graph = NetworkGraph::read(&mut d).unwrap();
4859 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4861 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4862 let mut seed = random_init_seed() as usize;
4863 let nodes = graph.read_only().nodes().clone();
4864 'load_endpoints: for _ in 0..10 {
4866 seed = seed.overflowing_mul(0xdeadbeef).0;
4867 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4868 seed = seed.overflowing_mul(0xdeadbeef).0;
4869 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4870 let payee = Payee::from_node_id(dst);
4871 let amt = seed as u64 % 200_000_000;
4872 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4873 continue 'load_endpoints;
4880 #[cfg(not(feature = "no-std"))]
4881 fn generate_routes_mpp() {
4882 let mut d = match super::test_utils::get_route_file() {
4889 let graph = NetworkGraph::read(&mut d).unwrap();
4890 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4892 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4893 let mut seed = random_init_seed() as usize;
4894 let nodes = graph.read_only().nodes().clone();
4895 'load_endpoints: for _ in 0..10 {
4897 seed = seed.overflowing_mul(0xdeadbeef).0;
4898 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4899 seed = seed.overflowing_mul(0xdeadbeef).0;
4900 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4901 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4902 let amt = seed as u64 % 200_000_000;
4903 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4904 continue 'load_endpoints;
4911 #[cfg(all(test, not(feature = "no-std")))]
4912 pub(crate) mod test_utils {
4914 /// Tries to open a network graph file, or panics with a URL to fetch it.
4915 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4916 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4917 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4918 .or_else(|_| { // Fall back to guessing based on the binary location
4919 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4920 let mut path = std::env::current_exe().unwrap();
4921 path.pop(); // lightning-...
4923 path.pop(); // debug
4924 path.pop(); // target
4925 path.push("lightning");
4926 path.push("net_graph-2021-05-31.bin");
4927 eprintln!("{}", path.to_str().unwrap());
4930 .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");
4931 #[cfg(require_route_graph_test)]
4932 return Ok(res.unwrap());
4933 #[cfg(not(require_route_graph_test))]
4938 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4941 use routing::scoring::Scorer;
4942 use util::logger::{Logger, Record};
4946 struct DummyLogger {}
4947 impl Logger for DummyLogger {
4948 fn log(&self, _record: &Record) {}
4952 fn generate_routes(bench: &mut Bencher) {
4953 let mut d = test_utils::get_route_file().unwrap();
4954 let graph = NetworkGraph::read(&mut d).unwrap();
4955 let nodes = graph.read_only().nodes().clone();
4956 let scorer = Scorer::with_fixed_penalty(0);
4958 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4959 let mut path_endpoints = Vec::new();
4960 let mut seed: usize = 0xdeadbeef;
4961 'load_endpoints: for _ in 0..100 {
4964 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4966 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4967 let payee = Payee::from_node_id(dst);
4968 let amt = seed as u64 % 1_000_000;
4969 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4970 path_endpoints.push((src, dst, amt));
4971 continue 'load_endpoints;
4976 // ...then benchmark finding paths between the nodes we learned.
4979 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4980 let payee = Payee::from_node_id(dst);
4981 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4987 fn generate_mpp_routes(bench: &mut Bencher) {
4988 let mut d = test_utils::get_route_file().unwrap();
4989 let graph = NetworkGraph::read(&mut d).unwrap();
4990 let nodes = graph.read_only().nodes().clone();
4991 let scorer = Scorer::with_fixed_penalty(0);
4993 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4994 let mut path_endpoints = Vec::new();
4995 let mut seed: usize = 0xdeadbeef;
4996 'load_endpoints: for _ in 0..100 {
4999 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5001 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5002 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
5003 let amt = seed as u64 % 1_000_000;
5004 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
5005 path_endpoints.push((src, dst, amt));
5006 continue 'load_endpoints;
5011 // ...then benchmark finding paths between the nodes we learned.
5014 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
5015 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
5016 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());