1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::scoring::Score;
21 use routing::network_graph::{DirectedChannelInfoWithUpdate, EffectiveCapacity, NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payment_params` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payment_params: Option<PaymentParameters>,
81 pub(crate) trait RoutePath {
82 /// Gets the fees for a given path, excluding any excess paid to the recipient.
83 fn get_path_fees(&self) -> u64;
85 impl RoutePath for Vec<RouteHop> {
86 fn get_path_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
89 .iter().map(|hop| &hop.fee_msat)
95 /// Returns the total amount of fees paid on this [`Route`].
97 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
98 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
99 pub fn get_total_fees(&self) -> u64 {
100 self.paths.iter().map(|path| path.get_path_fees()).sum()
103 /// Returns the total amount paid on this [`Route`], excluding the fees.
104 pub fn get_total_amount(&self) -> u64 {
105 return self.paths.iter()
106 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
111 const SERIALIZATION_VERSION: u8 = 1;
112 const MIN_SERIALIZATION_VERSION: u8 = 1;
114 impl Writeable for Route {
115 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
116 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
117 (self.paths.len() as u64).write(writer)?;
118 for hops in self.paths.iter() {
119 (hops.len() as u8).write(writer)?;
120 for hop in hops.iter() {
124 write_tlv_fields!(writer, {
125 (1, self.payment_params, option),
131 impl Readable for Route {
132 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
133 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
134 let path_count: u64 = Readable::read(reader)?;
135 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
136 for _ in 0..path_count {
137 let hop_count: u8 = Readable::read(reader)?;
138 let mut hops = Vec::with_capacity(hop_count as usize);
139 for _ in 0..hop_count {
140 hops.push(Readable::read(reader)?);
144 let mut payment_params = None;
145 read_tlv_fields!(reader, {
146 (1, payment_params, option),
148 Ok(Route { paths, payment_params })
152 /// Parameters needed to find a [`Route`].
154 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
157 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
158 #[derive(Clone, Debug)]
159 pub struct RouteParameters {
160 /// The parameters of the failed payment path.
161 pub payment_params: PaymentParameters,
163 /// The amount in msats sent on the failed payment path.
164 pub final_value_msat: u64,
166 /// The CLTV on the final hop of the failed payment path.
167 pub final_cltv_expiry_delta: u32,
170 impl_writeable_tlv_based!(RouteParameters, {
171 (0, payment_params, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// Maximum total CTLV difference we allow for a full payment path.
177 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
179 /// The recipient of a payment.
180 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
181 pub struct PaymentParameters {
182 /// The node id of the payee.
183 pub payee_pubkey: PublicKey,
185 /// Features supported by the payee.
187 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
188 /// does not contain any features.
190 /// [`for_keysend`]: Self::for_keysend
191 pub features: Option<InvoiceFeatures>,
193 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
194 pub route_hints: Vec<RouteHint>,
196 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
197 pub expiry_time: Option<u64>,
199 /// The maximum total CLTV delta we accept for the route.
200 pub max_total_cltv_expiry_delta: u32,
203 impl_writeable_tlv_based!(PaymentParameters, {
204 (0, payee_pubkey, required),
205 (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
206 (2, features, option),
207 (4, route_hints, vec_type),
208 (6, expiry_time, option),
211 impl PaymentParameters {
212 /// Creates a payee with the node id of the given `pubkey`.
213 pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
219 max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
223 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
224 pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
225 Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
228 /// Includes the payee's features.
230 /// (C-not exported) since bindings don't support move semantics
231 pub fn with_features(self, features: InvoiceFeatures) -> Self {
232 Self { features: Some(features), ..self }
235 /// Includes hints for routing to the payee.
237 /// (C-not exported) since bindings don't support move semantics
238 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
239 Self { route_hints, ..self }
242 /// Includes a payment expiration in seconds relative to the UNIX epoch.
244 /// (C-not exported) since bindings don't support move semantics
245 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
246 Self { expiry_time: Some(expiry_time), ..self }
249 /// Includes a limit for the total CLTV expiry delta which is considered during routing
251 /// (C-not exported) since bindings don't support move semantics
252 pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
253 Self { max_total_cltv_expiry_delta, ..self }
257 /// A list of hops along a payment path terminating with a channel to the recipient.
258 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
259 pub struct RouteHint(pub Vec<RouteHintHop>);
262 impl Writeable for RouteHint {
263 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
264 (self.0.len() as u64).write(writer)?;
265 for hop in self.0.iter() {
272 impl Readable for RouteHint {
273 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
274 let hop_count: u64 = Readable::read(reader)?;
275 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
276 for _ in 0..hop_count {
277 hops.push(Readable::read(reader)?);
283 /// A channel descriptor for a hop along a payment path.
284 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
285 pub struct RouteHintHop {
286 /// The node_id of the non-target end of the route
287 pub src_node_id: PublicKey,
288 /// The short_channel_id of this channel
289 pub short_channel_id: u64,
290 /// The fees which must be paid to use this channel
291 pub fees: RoutingFees,
292 /// The difference in CLTV values between this node and the next node.
293 pub cltv_expiry_delta: u16,
294 /// The minimum value, in msat, which must be relayed to the next hop.
295 pub htlc_minimum_msat: Option<u64>,
296 /// The maximum value in msat available for routing with a single HTLC.
297 pub htlc_maximum_msat: Option<u64>,
300 impl_writeable_tlv_based!(RouteHintHop, {
301 (0, src_node_id, required),
302 (1, htlc_minimum_msat, option),
303 (2, short_channel_id, required),
304 (3, htlc_maximum_msat, option),
306 (6, cltv_expiry_delta, required),
309 #[derive(Eq, PartialEq)]
310 struct RouteGraphNode {
312 lowest_fee_to_peer_through_node: u64,
313 lowest_fee_to_node: u64,
314 total_cltv_delta: u32,
315 // The maximum value a yet-to-be-constructed payment path might flow through this node.
316 // This value is upper-bounded by us by:
317 // - how much is needed for a path being constructed
318 // - how much value can channels following this node (up to the destination) can contribute,
319 // considering their capacity and fees
320 value_contribution_msat: u64,
321 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
322 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
323 path_htlc_minimum_msat: u64,
324 /// All penalties incurred from this hop on the way to the destination, as calculated using
326 path_penalty_msat: u64,
329 impl cmp::Ord for RouteGraphNode {
330 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
331 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
332 .checked_add(other.path_penalty_msat)
333 .unwrap_or_else(|| u64::max_value());
334 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
335 .checked_add(self.path_penalty_msat)
336 .unwrap_or_else(|| u64::max_value());
337 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
341 impl cmp::PartialOrd for RouteGraphNode {
342 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
343 Some(self.cmp(other))
347 /// A wrapper around the various hop representations.
349 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
350 #[derive(Clone, Debug)]
351 enum CandidateRouteHop<'a> {
352 /// A hop from the payer to the next hop to the payee, where the outbound liquidity is known.
354 details: &'a ChannelDetails,
356 /// A hop found in the [`NetworkGraph`], where the channel capacity may or may not be known.
358 info: DirectedChannelInfoWithUpdate<'a>,
359 short_channel_id: u64,
361 /// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
363 hint: &'a RouteHintHop,
367 impl<'a> CandidateRouteHop<'a> {
368 fn short_channel_id(&self) -> u64 {
370 CandidateRouteHop::FirstHop { details } => details.short_channel_id.unwrap(),
371 CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
372 CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
376 // NOTE: This may copy bytes to so avoid calling it in a hot code path.
377 fn features(&self) -> ChannelFeatures {
379 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
380 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
381 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
385 fn cltv_expiry_delta(&self) -> u32 {
387 CandidateRouteHop::FirstHop { .. } => 0,
388 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
389 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
393 fn htlc_minimum_msat(&self) -> u64 {
395 CandidateRouteHop::FirstHop { .. } => 0,
396 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
397 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
401 fn fees(&self) -> RoutingFees {
403 CandidateRouteHop::FirstHop { .. } => RoutingFees {
404 base_msat: 0, proportional_millionths: 0,
406 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
407 CandidateRouteHop::PrivateHop { hint } => hint.fees,
411 fn effective_capacity(&self) -> EffectiveCapacity {
413 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
414 liquidity_msat: details.outbound_capacity_msat,
416 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
417 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
422 /// It's useful to keep track of the hops associated with the fees required to use them,
423 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
424 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
425 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
426 #[derive(Clone, Debug)]
427 struct PathBuildingHop<'a> {
428 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
429 // is a larger refactor and will require careful performance analysis.
431 candidate: CandidateRouteHop<'a>,
434 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
435 src_lowest_inbound_fees: RoutingFees,
436 /// All the fees paid *after* this channel on the way to the destination
437 next_hops_fee_msat: u64,
438 /// Fee paid for the use of the current channel (see candidate.fees()).
439 /// The value will be actually deducted from the counterparty balance on the previous link.
440 hop_use_fee_msat: u64,
441 /// Used to compare channels when choosing the for routing.
442 /// Includes paying for the use of a hop and the following hops, as well as
443 /// an estimated cost of reaching this hop.
444 /// Might get stale when fees are recomputed. Primarily for internal use.
446 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
447 /// walk and may be invalid thereafter.
448 path_htlc_minimum_msat: u64,
449 /// All penalties incurred from this channel on the way to the destination, as calculated using
451 path_penalty_msat: u64,
452 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
453 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
454 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
455 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
456 /// avoid processing them again.
458 #[cfg(any(test, feature = "fuzztarget"))]
459 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
460 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
461 // value_contribution_msat, which requires tracking it here. See comments below where it is
462 // used for more info.
463 value_contribution_msat: u64,
466 // Instantiated with a list of hops with correct data in them collected during path finding,
467 // an instance of this struct should be further modified only via given methods.
469 struct PaymentPath<'a> {
470 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
473 impl<'a> PaymentPath<'a> {
474 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
475 fn get_value_msat(&self) -> u64 {
476 self.hops.last().unwrap().0.fee_msat
479 fn get_total_fee_paid_msat(&self) -> u64 {
480 if self.hops.len() < 1 {
484 // Can't use next_hops_fee_msat because it gets outdated.
485 for (i, (hop, _)) in self.hops.iter().enumerate() {
486 if i != self.hops.len() - 1 {
487 result += hop.fee_msat;
493 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
494 // to change fees may result in an inconsistency.
496 // Sometimes we call this function right after constructing a path which is inconsistent in
497 // that it the value being transferred has decreased while we were doing path finding, leading
498 // to the fees being paid not lining up with the actual limits.
500 // Note that this function is not aware of the available_liquidity limit, and thus does not
501 // support increasing the value being transferred.
502 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
503 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
505 let mut total_fee_paid_msat = 0 as u64;
506 for i in (0..self.hops.len()).rev() {
507 let last_hop = i == self.hops.len() - 1;
509 // For non-last-hop, this value will represent the fees paid on the current hop. It
510 // will consist of the fees for the use of the next hop, and extra fees to match
511 // htlc_minimum_msat of the current channel. Last hop is handled separately.
512 let mut cur_hop_fees_msat = 0;
514 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
517 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
518 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
519 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
520 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
521 // set it too high just to maliciously take more fees by exploiting this
522 // match htlc_minimum_msat logic.
523 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
524 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
525 // Note that there is a risk that *previous hops* (those closer to us, as we go
526 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
528 // This might make us end up with a broken route, although this should be super-rare
529 // in practice, both because of how healthy channels look like, and how we pick
530 // channels in add_entry.
531 // Also, this can't be exploited more heavily than *announce a free path and fail
533 cur_hop_transferred_amount_msat += extra_fees_msat;
534 total_fee_paid_msat += extra_fees_msat;
535 cur_hop_fees_msat += extra_fees_msat;
539 // Final hop is a special case: it usually has just value_msat (by design), but also
540 // it still could overpay for the htlc_minimum_msat.
541 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
543 // Propagate updated fees for the use of the channels to one hop back, where they
544 // will be actually paid (fee_msat). The last hop is handled above separately.
545 cur_hop.fee_msat = cur_hop_fees_msat;
548 // Fee for the use of the current hop which will be deducted on the previous hop.
549 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
550 // this channel is free for us.
552 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
553 cur_hop.hop_use_fee_msat = new_fee;
554 total_fee_paid_msat += new_fee;
556 // It should not be possible because this function is called only to reduce the
557 // value. In that case, compute_fee was already called with the same fees for
558 // larger amount and there was no overflow.
566 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
567 let proportional_fee_millions =
568 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
569 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
570 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
574 // This function may be (indirectly) called without any verification,
575 // with channel_fees provided by a caller. We should handle it gracefully.
580 /// Finds a route from us (payer) to the given target node (payee).
582 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
583 /// Without this, MPP will only be used if the payee's features are available in the network graph.
585 /// Private routing paths between a public node and the target may be included in `params.payee`.
587 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
588 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
589 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
591 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
592 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
593 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
597 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
598 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
603 /// Panics if first_hops contains channels without short_channel_ids;
604 /// [`ChannelManager::list_usable_channels`] will never include such channels.
606 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
607 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
608 pub fn find_route<L: Deref, S: Score>(
609 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
610 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
611 ) -> Result<Route, LightningError>
612 where L::Target: Logger {
614 our_node_pubkey, &route_params.payment_params, network, first_hops, route_params.final_value_msat,
615 route_params.final_cltv_expiry_delta, logger, scorer
619 pub(crate) fn get_route<L: Deref, S: Score>(
620 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network: &NetworkGraph,
621 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
622 logger: L, scorer: &S
623 ) -> Result<Route, LightningError>
624 where L::Target: Logger {
625 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
626 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
628 if payee_node_id == our_node_id {
629 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
632 if final_value_msat > MAX_VALUE_MSAT {
633 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
636 if final_value_msat == 0 {
637 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
640 for route in payment_params.route_hints.iter() {
641 for hop in &route.0 {
642 if hop.src_node_id == payment_params.payee_pubkey {
643 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
648 // The general routing idea is the following:
649 // 1. Fill first/last hops communicated by the caller.
650 // 2. Attempt to construct a path from payer to payee for transferring
651 // any ~sufficient (described later) value.
652 // If succeed, remember which channels were used and how much liquidity they have available,
653 // so that future paths don't rely on the same liquidity.
654 // 3. Proceed to the next step if:
655 // - we hit the recommended target value;
656 // - OR if we could not construct a new path. Any next attempt will fail too.
657 // Otherwise, repeat step 2.
658 // 4. See if we managed to collect paths which aggregately are able to transfer target value
659 // (not recommended value). If yes, proceed. If not, fail routing.
660 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
661 // 6. Of all the found paths, select only those with the lowest total fee.
662 // 7. The last path in every selected route is likely to be more than we need.
663 // Reduce its value-to-transfer and recompute fees.
664 // 8. Choose the best route by the lowest total fee.
666 // As for the actual search algorithm,
667 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
668 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
670 // We are not a faithful Dijkstra's implementation because we can change values which impact
671 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
672 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
673 // the value we are currently attempting to send over a path, we simply reduce the value being
674 // sent along the path for any hops after that channel. This may imply that later fees (which
675 // we've already tabulated) are lower because a smaller value is passing through the channels
676 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
677 // channels which were selected earlier (and which may still be used for other paths without a
678 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
681 // One potentially problematic case for this algorithm would be if there are many
682 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
683 // graph walking), we may never find a path which is not liquidity-limited and has lower
684 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
685 // Because we only consider paths with at least 5% of the total value being sent, the damage
686 // from such a case should be limited, however this could be further reduced in the future by
687 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
688 // limits for the purposes of fee calculation.
690 // Alternatively, we could store more detailed path information in the heap (targets, below)
691 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
692 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
693 // and practically (as we would need to store dynamically-allocated path information in heap
694 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
695 // results of such an algorithm would likely be biased towards lower-value paths.
697 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
698 // outside of our current search value, running a path search more times to gather candidate
699 // paths at different values. While this may be acceptable, further path searches may increase
700 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
701 // graph for candidate paths, calculating the maximum value which can realistically be sent at
702 // the same time, remaining generic across different payment values.
704 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
705 // to use as the A* heuristic beyond just the cost to get one node further than the current
708 let network_graph = network.read_only();
709 let network_channels = network_graph.channels();
710 let network_nodes = network_graph.nodes();
712 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
713 // it. If the payee supports it they're supposed to include it in the invoice, so that should
715 let allow_mpp = if let Some(features) = &payment_params.features {
716 features.supports_basic_mpp()
717 } else if let Some(node) = network_nodes.get(&payee_node_id) {
718 if let Some(node_info) = node.announcement_info.as_ref() {
719 node_info.features.supports_basic_mpp()
722 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
723 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" });
726 // Prepare the data we'll use for payee-to-payer search by
727 // inserting first hops suggested by the caller as targets.
728 // Our search will then attempt to reach them while traversing from the payee node.
729 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
730 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
731 if let Some(hops) = first_hops {
733 if chan.short_channel_id.is_none() {
734 panic!("first_hops should be filled in with usable channels, not pending ones");
736 if chan.counterparty.node_id == *our_node_pubkey {
737 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
740 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
741 .or_insert(Vec::new())
744 if first_hop_targets.is_empty() {
745 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
749 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
750 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
751 // adding duplicate entries when we find a better path to a given node.
752 let mut targets = BinaryHeap::new();
754 // Map from node_id to information about the best current path to that node, including feerate
756 let mut dist = HashMap::with_capacity(network_nodes.len());
758 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
759 // indicating that we may wish to try again with a higher value, potentially paying to meet an
760 // htlc_minimum with extra fees while still finding a cheaper path.
761 let mut hit_minimum_limit;
763 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
764 // We start with a path_value of the exact amount we want, and if that generates a route we may
765 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
766 // amount we want in total across paths, selecting the best subset at the end.
767 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
768 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
769 let mut path_value_msat = final_value_msat;
771 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
772 // This map allows paths to be aware of the channel use by other paths in the same call.
773 // This would help to make a better path finding decisions and not "overbook" channels.
774 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
775 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
777 // Keeping track of how much value we already collected across other paths. Helps to decide:
778 // - how much a new path should be transferring (upper bound);
779 // - whether a channel should be disregarded because
780 // it's available liquidity is too small comparing to how much more we need to collect;
781 // - when we want to stop looking for new paths.
782 let mut already_collected_value_msat = 0;
784 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
786 macro_rules! add_entry {
787 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
788 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
789 // since that value has to be transferred over this channel.
790 // Returns whether this channel caused an update to `targets`.
791 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
792 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
793 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
794 // We "return" whether we updated the path at the end, via this:
795 let mut did_add_update_path_to_src_node = false;
796 // Channels to self should not be used. This is more of belt-and-suspenders, because in
797 // practice these cases should be caught earlier:
798 // - for regular channels at channel announcement (TODO)
799 // - for first and last hops early in get_route
800 if $src_node_id != $dest_node_id {
801 let short_channel_id = $candidate.short_channel_id();
802 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
803 .entry(short_channel_id)
804 .or_insert_with(|| $candidate.effective_capacity().as_msat());
806 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
807 // It may be misleading because we might later choose to reduce the value transferred
808 // over these channels, and the channel which was insufficient might become sufficient.
809 // Worst case: we drop a good channel here because it can't cover the high following
810 // fees caused by one expensive channel, but then this channel could have been used
811 // if the amount being transferred over this path is lower.
812 // We do this for now, but this is a subject for removal.
813 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
815 // Routing Fragmentation Mitigation heuristic:
817 // Routing fragmentation across many payment paths increases the overall routing
818 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
819 // Taking too many smaller paths also increases the chance of payment failure.
820 // Thus to avoid this effect, we require from our collected links to provide
821 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
823 // This requirement is currently 5% of the remaining-to-be-collected value.
824 // This means as we successfully advance in our collection,
825 // the absolute liquidity contribution is lowered,
826 // thus increasing the number of potential channels to be selected.
828 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
829 // or 100% if we're not allowed to do multipath payments.
830 let minimal_value_contribution_msat: u64 = if allow_mpp {
831 (recommended_value_msat - already_collected_value_msat + 19) / 20
835 // Verify the liquidity offered by this channel complies to the minimal contribution.
836 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
838 // Do not consider candidates that exceed the maximum total cltv expiry limit.
839 let max_total_cltv_expiry_delta = payment_params.max_total_cltv_expiry_delta;
840 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
841 .checked_add($candidate.cltv_expiry_delta())
842 .unwrap_or(u32::max_value());
843 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
845 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
846 // Includes paying fees for the use of the following channels.
847 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
848 Some(result) => result,
849 // Can't overflow due to how the values were computed right above.
850 None => unreachable!(),
852 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
853 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
854 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
856 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
857 // bother considering this channel.
858 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
859 // be only reduced later (not increased), so this channel should just be skipped
860 // as not sufficient.
861 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
862 hit_minimum_limit = true;
863 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
864 // Note that low contribution here (limited by available_liquidity_msat)
865 // might violate htlc_minimum_msat on the hops which are next along the
866 // payment path (upstream to the payee). To avoid that, we recompute
867 // path fees knowing the final path contribution after constructing it.
868 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
869 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
870 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
871 .unwrap_or_else(|| u64::max_value());
872 let hm_entry = dist.entry($src_node_id);
873 let old_entry = hm_entry.or_insert_with(|| {
874 // If there was previously no known way to access the source node
875 // (recall it goes payee-to-payer) of short_channel_id, first add a
876 // semi-dummy record just to compute the fees to reach the source node.
877 // This will affect our decision on selecting short_channel_id
878 // as a way to reach the $dest_node_id.
879 let mut fee_base_msat = u32::max_value();
880 let mut fee_proportional_millionths = u32::max_value();
881 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
882 fee_base_msat = fees.base_msat;
883 fee_proportional_millionths = fees.proportional_millionths;
886 node_id: $dest_node_id.clone(),
887 candidate: $candidate.clone(),
889 src_lowest_inbound_fees: RoutingFees {
890 base_msat: fee_base_msat,
891 proportional_millionths: fee_proportional_millionths,
893 next_hops_fee_msat: u64::max_value(),
894 hop_use_fee_msat: u64::max_value(),
895 total_fee_msat: u64::max_value(),
896 path_htlc_minimum_msat,
897 path_penalty_msat: u64::max_value(),
898 was_processed: false,
899 #[cfg(any(test, feature = "fuzztarget"))]
900 value_contribution_msat,
904 #[allow(unused_mut)] // We only use the mut in cfg(test)
905 let mut should_process = !old_entry.was_processed;
906 #[cfg(any(test, feature = "fuzztarget"))]
908 // In test/fuzzing builds, we do extra checks to make sure the skipping
909 // of already-seen nodes only happens in cases we expect (see below).
910 if !should_process { should_process = true; }
914 let mut hop_use_fee_msat = 0;
915 let mut total_fee_msat = $next_hops_fee_msat;
917 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
918 // will have the same effective-fee
919 if $src_node_id != our_node_id {
920 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
921 // max_value means we'll always fail
922 // the old_entry.total_fee_msat > total_fee_msat check
923 None => total_fee_msat = u64::max_value(),
925 hop_use_fee_msat = fee_msat;
926 total_fee_msat += hop_use_fee_msat;
927 // When calculating the lowest inbound fees to a node, we
928 // calculate fees here not based on the actual value we think
929 // will flow over this channel, but on the minimum value that
930 // we'll accept flowing over it. The minimum accepted value
931 // is a constant through each path collection run, ensuring
932 // consistent basis. Otherwise we may later find a
933 // different path to the source node that is more expensive,
934 // but which we consider to be cheaper because we are capacity
935 // constrained and the relative fee becomes lower.
936 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
937 .map(|a| a.checked_add(total_fee_msat)) {
942 total_fee_msat = u64::max_value();
949 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
950 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
951 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
952 let new_graph_node = RouteGraphNode {
953 node_id: $src_node_id,
954 lowest_fee_to_peer_through_node: total_fee_msat,
955 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
956 total_cltv_delta: hop_total_cltv_delta,
957 value_contribution_msat: value_contribution_msat,
958 path_htlc_minimum_msat,
962 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
963 // if this way is cheaper than the already known
964 // (considering the cost to "reach" this channel from the route destination,
965 // the cost of using this channel,
966 // and the cost of routing to the source node of this channel).
967 // Also, consider that htlc_minimum_msat_difference, because we might end up
968 // paying it. Consider the following exploit:
969 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
970 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
971 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
972 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
974 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
975 // but it may require additional tracking - we don't want to double-count
976 // the fees included in $next_hops_path_htlc_minimum_msat, but also
977 // can't use something that may decrease on future hops.
978 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
979 .checked_add(old_entry.path_penalty_msat)
980 .unwrap_or_else(|| u64::max_value());
981 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
982 .checked_add(path_penalty_msat)
983 .unwrap_or_else(|| u64::max_value());
985 if !old_entry.was_processed && new_cost < old_cost {
986 targets.push(new_graph_node);
987 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
988 old_entry.hop_use_fee_msat = hop_use_fee_msat;
989 old_entry.total_fee_msat = total_fee_msat;
990 old_entry.node_id = $dest_node_id.clone();
991 old_entry.candidate = $candidate.clone();
992 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
993 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
994 old_entry.path_penalty_msat = path_penalty_msat;
995 #[cfg(any(test, feature = "fuzztarget"))]
997 old_entry.value_contribution_msat = value_contribution_msat;
999 did_add_update_path_to_src_node = true;
1000 } else if old_entry.was_processed && new_cost < old_cost {
1001 #[cfg(any(test, feature = "fuzztarget"))]
1003 // If we're skipping processing a node which was previously
1004 // processed even though we found another path to it with a
1005 // cheaper fee, check that it was because the second path we
1006 // found (which we are processing now) has a lower value
1007 // contribution due to an HTLC minimum limit.
1009 // e.g. take a graph with two paths from node 1 to node 2, one
1010 // through channel A, and one through channel B. Channel A and
1011 // B are both in the to-process heap, with their scores set by
1012 // a higher htlc_minimum than fee.
1013 // Channel A is processed first, and the channels onwards from
1014 // node 1 are added to the to-process heap. Thereafter, we pop
1015 // Channel B off of the heap, note that it has a much more
1016 // restrictive htlc_maximum_msat, and recalculate the fees for
1017 // all of node 1's channels using the new, reduced, amount.
1019 // This would be bogus - we'd be selecting a higher-fee path
1020 // with a lower htlc_maximum_msat instead of the one we'd
1021 // already decided to use.
1022 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1024 value_contribution_msat + path_penalty_msat <
1025 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1033 did_add_update_path_to_src_node
1037 let empty_node_features = NodeFeatures::empty();
1038 // Find ways (channels with destination) to reach a given node and store them
1039 // in the corresponding data structures (routing graph etc).
1040 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1041 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1042 // This data can later be helpful to optimize routing (pay lower fees).
1043 macro_rules! add_entries_to_cheapest_to_target_node {
1044 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => {
1045 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1046 let was_processed = elem.was_processed;
1047 elem.was_processed = true;
1050 // Entries are added to dist in add_entry!() when there is a channel from a node.
1051 // Because there are no channels from payee, it will not have a dist entry at this point.
1052 // If we're processing any other node, it is always be the result of a channel from it.
1053 assert_eq!($node_id, payee_node_id);
1058 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1059 for details in first_channels {
1060 let candidate = CandidateRouteHop::FirstHop { details };
1061 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1065 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1068 &empty_node_features
1071 if !features.requires_unknown_bits() {
1072 for chan_id in $node.channels.iter() {
1073 let chan = network_channels.get(chan_id).unwrap();
1074 if !chan.features.requires_unknown_bits() {
1075 let (directed_channel, source) =
1076 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1077 if first_hops.is_none() || *source != our_node_id {
1078 if let Some(direction) = directed_channel.direction() {
1079 if direction.enabled {
1080 let candidate = CandidateRouteHop::PublicHop {
1081 info: directed_channel.with_update().unwrap(),
1082 short_channel_id: *chan_id,
1084 add_entry!(candidate, *source, $node_id, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1095 let mut payment_paths = Vec::<PaymentPath>::new();
1097 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1098 'paths_collection: loop {
1099 // For every new path, start from scratch, except
1100 // bookkept_channels_liquidity_available_msat, which will improve
1101 // the further iterations of path finding. Also don't erase first_hop_targets.
1104 hit_minimum_limit = false;
1106 // If first hop is a private channel and the only way to reach the payee, this is the only
1107 // place where it could be added.
1108 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1109 for details in first_channels {
1110 let candidate = CandidateRouteHop::FirstHop { details };
1111 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1112 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1116 // Add the payee as a target, so that the payee-to-payer
1117 // search algorithm knows what to start with.
1118 match network_nodes.get(&payee_node_id) {
1119 // The payee is not in our network graph, so nothing to add here.
1120 // There is still a chance of reaching them via last_hops though,
1121 // so don't yet fail the payment here.
1122 // If not, targets.pop() will not even let us enter the loop in step 2.
1125 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1130 // If a caller provided us with last hops, add them to routing targets. Since this happens
1131 // earlier than general path finding, they will be somewhat prioritized, although currently
1132 // it matters only if the fees are exactly the same.
1133 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1134 let first_hop_in_route = &(route.0)[0];
1135 let have_hop_src_in_graph =
1136 // Only add the hops in this route to our candidate set if either
1137 // we have a direct channel to the first hop or the first hop is
1138 // in the regular network graph.
1139 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1140 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1141 if have_hop_src_in_graph {
1142 // We start building the path from reverse, i.e., from payee
1143 // to the first RouteHintHop in the path.
1144 let hop_iter = route.0.iter().rev();
1145 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1146 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1147 let mut hop_used = true;
1148 let mut aggregate_next_hops_fee_msat: u64 = 0;
1149 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1150 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1151 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1153 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1154 let source = NodeId::from_pubkey(&hop.src_node_id);
1155 let target = NodeId::from_pubkey(&prev_hop_id);
1156 let candidate = network_channels
1157 .get(&hop.short_channel_id)
1158 .and_then(|channel| channel.as_directed_to(&target))
1159 .and_then(|(channel, _)| channel.with_update())
1160 .map(|info| CandidateRouteHop::PublicHop {
1162 short_channel_id: hop.short_channel_id,
1164 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1165 let capacity_msat = candidate.effective_capacity().as_msat();
1166 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1167 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1168 .unwrap_or_else(|| u64::max_value());
1170 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1171 .checked_add(hop.cltv_expiry_delta as u32)
1172 .unwrap_or_else(|| u32::max_value());
1174 if !add_entry!(candidate, source, target, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta) {
1175 // If this hop was not used then there is no use checking the preceding hops
1176 // in the RouteHint. We can break by just searching for a direct channel between
1177 // last checked hop and first_hop_targets
1181 // Searching for a direct channel between last checked hop and first_hop_targets
1182 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1183 for details in first_channels {
1184 let candidate = CandidateRouteHop::FirstHop { details };
1185 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1193 // In the next values of the iterator, the aggregate fees already reflects
1194 // the sum of value sent from payer (final_value_msat) and routing fees
1195 // for the last node in the RouteHint. We need to just add the fees to
1196 // route through the current node so that the preceeding node (next iteration)
1198 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1199 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1200 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1202 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1203 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1204 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1205 .checked_add(hop_htlc_minimum_msat_inc);
1206 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1208 if idx == route.0.len() - 1 {
1209 // The last hop in this iterator is the first hop in
1210 // overall RouteHint.
1211 // If this hop connects to a node with which we have a direct channel,
1212 // ignore the network graph and, if the last hop was added, add our
1213 // direct channel to the candidate set.
1215 // Note that we *must* check if the last hop was added as `add_entry`
1216 // always assumes that the third argument is a node to which we have a
1218 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1219 for details in first_channels {
1220 let candidate = CandidateRouteHop::FirstHop { details };
1221 add_entry!(candidate, our_node_id, NodeId::from_pubkey(&hop.src_node_id), aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat, aggregate_next_hops_cltv_delta);
1229 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1231 // At this point, targets are filled with the data from first and
1232 // last hops communicated by the caller, and the payment receiver.
1233 let mut found_new_path = false;
1236 // If this loop terminates due the exhaustion of targets, two situations are possible:
1237 // - not enough outgoing liquidity:
1238 // 0 < already_collected_value_msat < final_value_msat
1239 // - enough outgoing liquidity:
1240 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1241 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1242 // paths_collection will be stopped because found_new_path==false.
1243 // This is not necessarily a routing failure.
1244 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1246 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1247 // traversing the graph and arrange the path out of what we found.
1248 if node_id == our_node_id {
1249 let mut new_entry = dist.remove(&our_node_id).unwrap();
1250 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1253 let mut features_set = false;
1254 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1255 for details in first_channels {
1256 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1257 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1258 features_set = true;
1264 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1265 if let Some(node_info) = node.announcement_info.as_ref() {
1266 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1268 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1271 // We should be able to fill in features for everything except the last
1272 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1273 // should be able to extend it further as BOLT 11 does have feature
1274 // flags for the last hop node itself).
1275 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1279 // Means we succesfully traversed from the payer to the payee, now
1280 // save this path for the payment route. Also, update the liquidity
1281 // remaining on the used hops, so that we take them into account
1282 // while looking for more paths.
1283 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1287 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1288 Some(payment_hop) => payment_hop,
1289 // We can't arrive at None because, if we ever add an entry to targets,
1290 // we also fill in the entry in dist (see add_entry!).
1291 None => unreachable!(),
1293 // We "propagate" the fees one hop backward (topologically) here,
1294 // so that fees paid for a HTLC forwarding on the current channel are
1295 // associated with the previous channel (where they will be subtracted).
1296 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1297 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1299 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1300 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1302 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1303 ordered_hops.len(), value_contribution_msat, ordered_hops);
1305 let mut payment_path = PaymentPath {hops: ordered_hops};
1307 // We could have possibly constructed a slightly inconsistent path: since we reduce
1308 // value being transferred along the way, we could have violated htlc_minimum_msat
1309 // on some channels we already passed (assuming dest->source direction). Here, we
1310 // recompute the fees again, so that if that's the case, we match the currently
1311 // underpaid htlc_minimum_msat with fees.
1312 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1314 // Since a path allows to transfer as much value as
1315 // the smallest channel it has ("bottleneck"), we should recompute
1316 // the fees so sender HTLC don't overpay fees when traversing
1317 // larger channels than the bottleneck. This may happen because
1318 // when we were selecting those channels we were not aware how much value
1319 // this path will transfer, and the relative fee for them
1320 // might have been computed considering a larger value.
1321 // Remember that we used these channels so that we don't rely
1322 // on the same liquidity in future paths.
1323 let mut prevented_redundant_path_selection = false;
1324 for (payment_hop, _) in payment_path.hops.iter() {
1325 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1326 let mut spent_on_hop_msat = value_contribution_msat;
1327 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1328 spent_on_hop_msat += next_hops_fee_msat;
1329 if spent_on_hop_msat == *channel_liquidity_available_msat {
1330 // If this path used all of this channel's available liquidity, we know
1331 // this path will not be selected again in the next loop iteration.
1332 prevented_redundant_path_selection = true;
1334 *channel_liquidity_available_msat -= spent_on_hop_msat;
1336 if !prevented_redundant_path_selection {
1337 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1338 // we'll probably end up picking the same path again on the next iteration.
1339 // Decrease the available liquidity of a hop in the middle of the path.
1340 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1341 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1342 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1343 *victim_liquidity = 0;
1346 // Track the total amount all our collected paths allow to send so that we:
1347 // - know when to stop looking for more paths
1348 // - know which of the hops are useless considering how much more sats we need
1349 // (contributes_sufficient_value)
1350 already_collected_value_msat += value_contribution_msat;
1352 payment_paths.push(payment_path);
1353 found_new_path = true;
1354 break 'path_construction;
1357 // If we found a path back to the payee, we shouldn't try to process it again. This is
1358 // the equivalent of the `elem.was_processed` check in
1359 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1360 if node_id == payee_node_id { continue 'path_construction; }
1362 // Otherwise, since the current target node is not us,
1363 // keep "unrolling" the payment graph from payee to payer by
1364 // finding a way to reach the current target from the payer side.
1365 match network_nodes.get(&node_id) {
1368 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, total_cltv_delta);
1374 // If we don't support MPP, no use trying to gather more value ever.
1375 break 'paths_collection;
1379 // Stop either when the recommended value is reached or if no new path was found in this
1381 // In the latter case, making another path finding attempt won't help,
1382 // because we deterministically terminated the search due to low liquidity.
1383 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1384 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1385 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1386 break 'paths_collection;
1387 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1388 // Further, if this was our first walk of the graph, and we weren't limited by an
1389 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1390 // limited by an htlc_minimum_msat value, find another path with a higher value,
1391 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1392 // still keeping a lower total fee than this path.
1393 if !hit_minimum_limit {
1394 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1395 break 'paths_collection;
1397 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1398 path_value_msat = recommended_value_msat;
1403 if payment_paths.len() == 0 {
1404 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1407 if already_collected_value_msat < final_value_msat {
1408 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1411 // Sort by total fees and take the best paths.
1412 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1413 if payment_paths.len() > 50 {
1414 payment_paths.truncate(50);
1417 // Draw multiple sufficient routes by randomly combining the selected paths.
1418 let mut drawn_routes = Vec::new();
1419 for i in 0..payment_paths.len() {
1420 let mut cur_route = Vec::<PaymentPath>::new();
1421 let mut aggregate_route_value_msat = 0;
1424 // TODO: real random shuffle
1425 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1426 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1429 for payment_path in cur_payment_paths {
1430 cur_route.push(payment_path.clone());
1431 aggregate_route_value_msat += payment_path.get_value_msat();
1432 if aggregate_route_value_msat > final_value_msat {
1433 // Last path likely overpaid. Substract it from the most expensive
1434 // (in terms of proportional fee) path in this route and recompute fees.
1435 // This might be not the most economically efficient way, but fewer paths
1436 // also makes routing more reliable.
1437 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1439 // First, drop some expensive low-value paths entirely if possible.
1440 // Sort by value so that we drop many really-low values first, since
1441 // fewer paths is better: the payment is less likely to fail.
1442 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1443 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1444 cur_route.sort_by_key(|path| path.get_value_msat());
1445 // We should make sure that at least 1 path left.
1446 let mut paths_left = cur_route.len();
1447 cur_route.retain(|path| {
1448 if paths_left == 1 {
1451 let mut keep = true;
1452 let path_value_msat = path.get_value_msat();
1453 if path_value_msat <= overpaid_value_msat {
1455 overpaid_value_msat -= path_value_msat;
1461 if overpaid_value_msat == 0 {
1465 assert!(cur_route.len() > 0);
1468 // Now, substract the overpaid value from the most-expensive path.
1469 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1470 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1471 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1472 let expensive_payment_path = cur_route.first_mut().unwrap();
1473 // We already dropped all the small channels above, meaning all the
1474 // remaining channels are larger than remaining overpaid_value_msat.
1475 // Thus, this can't be negative.
1476 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1477 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1481 drawn_routes.push(cur_route);
1485 // Select the best route by lowest total fee.
1486 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1487 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1488 for payment_path in drawn_routes.first().unwrap() {
1489 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1491 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)})?,
1492 node_features: node_features.clone(),
1493 short_channel_id: payment_hop.candidate.short_channel_id(),
1494 channel_features: payment_hop.candidate.features(),
1495 fee_msat: payment_hop.fee_msat,
1496 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1498 }).collect::<Vec<_>>();
1499 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1500 // applicable for the previous hop.
1501 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1502 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1504 selected_paths.push(path);
1507 if let Some(features) = &payment_params.features {
1508 for path in selected_paths.iter_mut() {
1509 if let Ok(route_hop) = path.last_mut().unwrap() {
1510 route_hop.node_features = features.to_context();
1516 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1517 payment_params: Some(payment_params.clone()),
1519 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1525 use routing::scoring::Score;
1526 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1527 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1528 use chain::transaction::OutPoint;
1529 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1530 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1531 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1532 use ln::channelmanager;
1533 use util::test_utils;
1534 use util::ser::Writeable;
1536 use util::ser::Writer;
1538 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1539 use bitcoin::hashes::Hash;
1540 use bitcoin::network::constants::Network;
1541 use bitcoin::blockdata::constants::genesis_block;
1542 use bitcoin::blockdata::script::Builder;
1543 use bitcoin::blockdata::opcodes;
1544 use bitcoin::blockdata::transaction::TxOut;
1548 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1549 use bitcoin::secp256k1::{Secp256k1, All};
1552 use sync::{self, Arc};
1554 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1555 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1556 channelmanager::ChannelDetails {
1557 channel_id: [0; 32],
1558 counterparty: channelmanager::ChannelCounterparty {
1561 unspendable_punishment_reserve: 0,
1562 forwarding_info: None,
1564 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1566 channel_value_satoshis: 0,
1569 outbound_capacity_msat,
1570 inbound_capacity_msat: 42,
1571 unspendable_punishment_reserve: None,
1572 confirmations_required: None,
1573 force_close_spend_delay: None,
1574 is_outbound: true, is_funding_locked: true,
1575 is_usable: true, is_public: true,
1579 // Using the same keys for LN and BTC ids
1581 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1582 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1584 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1585 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1587 let unsigned_announcement = UnsignedChannelAnnouncement {
1589 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1593 bitcoin_key_1: node_id_1,
1594 bitcoin_key_2: node_id_2,
1595 excess_data: Vec::new(),
1598 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1599 let valid_announcement = ChannelAnnouncement {
1600 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1601 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1602 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1603 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1604 contents: unsigned_announcement.clone(),
1606 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1607 Ok(res) => assert!(res),
1613 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1614 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1616 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1617 let valid_channel_update = ChannelUpdate {
1618 signature: secp_ctx.sign(&msghash, node_privkey),
1619 contents: update.clone()
1622 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1623 Ok(res) => assert!(res),
1628 fn add_or_update_node(
1629 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1630 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1632 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1633 let unsigned_announcement = UnsignedNodeAnnouncement {
1639 addresses: Vec::new(),
1640 excess_address_data: Vec::new(),
1641 excess_data: Vec::new(),
1643 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1644 let valid_announcement = NodeAnnouncement {
1645 signature: secp_ctx.sign(&msghash, node_privkey),
1646 contents: unsigned_announcement.clone()
1649 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1655 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1656 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1657 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1660 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1662 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1663 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1665 (our_privkey, our_id, privkeys, pubkeys)
1668 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1669 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1670 // test for it later.
1671 let idx = (id - 1) * 2 + 1;
1673 vec![1 << (idx - 8*3), 0, 0, 0]
1674 } else if idx > 8*2 {
1675 vec![1 << (idx - 8*2), 0, 0]
1676 } else if idx > 8*1 {
1677 vec![1 << (idx - 8*1), 0]
1683 fn build_graph() -> (
1685 sync::Arc<NetworkGraph>,
1686 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1687 sync::Arc<test_utils::TestChainSource>,
1688 sync::Arc<test_utils::TestLogger>,
1690 let secp_ctx = Secp256k1::new();
1691 let logger = Arc::new(test_utils::TestLogger::new());
1692 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1693 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1694 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1695 // Build network from our_id to node6:
1697 // -1(1)2- node0 -1(3)2-
1699 // our_id -1(12)2- node7 -1(13)2--- node2
1701 // -1(2)2- node1 -1(4)2-
1704 // chan1 1-to-2: disabled
1705 // chan1 2-to-1: enabled, 0 fee
1707 // chan2 1-to-2: enabled, ignored fee
1708 // chan2 2-to-1: enabled, 0 fee
1710 // chan3 1-to-2: enabled, 0 fee
1711 // chan3 2-to-1: enabled, 100 msat fee
1713 // chan4 1-to-2: enabled, 100% fee
1714 // chan4 2-to-1: enabled, 0 fee
1716 // chan12 1-to-2: enabled, ignored fee
1717 // chan12 2-to-1: enabled, 0 fee
1719 // chan13 1-to-2: enabled, 200% fee
1720 // chan13 2-to-1: enabled, 0 fee
1723 // -1(5)2- node3 -1(8)2--
1727 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1729 // -1(7)2- node5 -1(10)2-
1731 // Channels 5, 8, 9 and 10 are private channels.
1733 // chan5 1-to-2: enabled, 100 msat fee
1734 // chan5 2-to-1: enabled, 0 fee
1736 // chan6 1-to-2: enabled, 0 fee
1737 // chan6 2-to-1: enabled, 0 fee
1739 // chan7 1-to-2: enabled, 100% fee
1740 // chan7 2-to-1: enabled, 0 fee
1742 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1743 // chan8 2-to-1: enabled, 0 fee
1745 // chan9 1-to-2: enabled, 1001 msat fee
1746 // chan9 2-to-1: enabled, 0 fee
1748 // chan10 1-to-2: enabled, 0 fee
1749 // chan10 2-to-1: enabled, 0 fee
1751 // chan11 1-to-2: enabled, 0 fee
1752 // chan11 2-to-1: enabled, 0 fee
1754 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1756 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1757 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1758 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1759 short_channel_id: 1,
1762 cltv_expiry_delta: 0,
1763 htlc_minimum_msat: 0,
1764 htlc_maximum_msat: OptionalField::Absent,
1766 fee_proportional_millionths: 0,
1767 excess_data: Vec::new()
1770 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1772 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1773 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1774 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1775 short_channel_id: 2,
1778 cltv_expiry_delta: (5 << 4) | 3,
1779 htlc_minimum_msat: 0,
1780 htlc_maximum_msat: OptionalField::Absent,
1781 fee_base_msat: u32::max_value(),
1782 fee_proportional_millionths: u32::max_value(),
1783 excess_data: Vec::new()
1785 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1786 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1787 short_channel_id: 2,
1790 cltv_expiry_delta: 0,
1791 htlc_minimum_msat: 0,
1792 htlc_maximum_msat: OptionalField::Absent,
1794 fee_proportional_millionths: 0,
1795 excess_data: Vec::new()
1798 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1800 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1801 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1802 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1803 short_channel_id: 12,
1806 cltv_expiry_delta: (5 << 4) | 3,
1807 htlc_minimum_msat: 0,
1808 htlc_maximum_msat: OptionalField::Absent,
1809 fee_base_msat: u32::max_value(),
1810 fee_proportional_millionths: u32::max_value(),
1811 excess_data: Vec::new()
1813 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1814 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1815 short_channel_id: 12,
1818 cltv_expiry_delta: 0,
1819 htlc_minimum_msat: 0,
1820 htlc_maximum_msat: OptionalField::Absent,
1822 fee_proportional_millionths: 0,
1823 excess_data: Vec::new()
1826 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1828 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1829 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1831 short_channel_id: 3,
1834 cltv_expiry_delta: (3 << 4) | 1,
1835 htlc_minimum_msat: 0,
1836 htlc_maximum_msat: OptionalField::Absent,
1838 fee_proportional_millionths: 0,
1839 excess_data: Vec::new()
1841 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1842 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1843 short_channel_id: 3,
1846 cltv_expiry_delta: (3 << 4) | 2,
1847 htlc_minimum_msat: 0,
1848 htlc_maximum_msat: OptionalField::Absent,
1850 fee_proportional_millionths: 0,
1851 excess_data: Vec::new()
1854 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1855 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1856 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1857 short_channel_id: 4,
1860 cltv_expiry_delta: (4 << 4) | 1,
1861 htlc_minimum_msat: 0,
1862 htlc_maximum_msat: OptionalField::Absent,
1864 fee_proportional_millionths: 1000000,
1865 excess_data: Vec::new()
1867 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1868 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1869 short_channel_id: 4,
1872 cltv_expiry_delta: (4 << 4) | 2,
1873 htlc_minimum_msat: 0,
1874 htlc_maximum_msat: OptionalField::Absent,
1876 fee_proportional_millionths: 0,
1877 excess_data: Vec::new()
1880 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1881 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1883 short_channel_id: 13,
1886 cltv_expiry_delta: (13 << 4) | 1,
1887 htlc_minimum_msat: 0,
1888 htlc_maximum_msat: OptionalField::Absent,
1890 fee_proportional_millionths: 2000000,
1891 excess_data: Vec::new()
1893 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1895 short_channel_id: 13,
1898 cltv_expiry_delta: (13 << 4) | 2,
1899 htlc_minimum_msat: 0,
1900 htlc_maximum_msat: OptionalField::Absent,
1902 fee_proportional_millionths: 0,
1903 excess_data: Vec::new()
1906 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1908 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1909 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1911 short_channel_id: 6,
1914 cltv_expiry_delta: (6 << 4) | 1,
1915 htlc_minimum_msat: 0,
1916 htlc_maximum_msat: OptionalField::Absent,
1918 fee_proportional_millionths: 0,
1919 excess_data: Vec::new()
1921 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1922 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1923 short_channel_id: 6,
1926 cltv_expiry_delta: (6 << 4) | 2,
1927 htlc_minimum_msat: 0,
1928 htlc_maximum_msat: OptionalField::Absent,
1930 fee_proportional_millionths: 0,
1931 excess_data: Vec::new(),
1934 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1935 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1936 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1937 short_channel_id: 11,
1940 cltv_expiry_delta: (11 << 4) | 1,
1941 htlc_minimum_msat: 0,
1942 htlc_maximum_msat: OptionalField::Absent,
1944 fee_proportional_millionths: 0,
1945 excess_data: Vec::new()
1947 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1948 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1949 short_channel_id: 11,
1952 cltv_expiry_delta: (11 << 4) | 2,
1953 htlc_minimum_msat: 0,
1954 htlc_maximum_msat: OptionalField::Absent,
1956 fee_proportional_millionths: 0,
1957 excess_data: Vec::new()
1960 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1962 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1964 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1965 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1967 short_channel_id: 7,
1970 cltv_expiry_delta: (7 << 4) | 1,
1971 htlc_minimum_msat: 0,
1972 htlc_maximum_msat: OptionalField::Absent,
1974 fee_proportional_millionths: 1000000,
1975 excess_data: Vec::new()
1977 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1979 short_channel_id: 7,
1982 cltv_expiry_delta: (7 << 4) | 2,
1983 htlc_minimum_msat: 0,
1984 htlc_maximum_msat: OptionalField::Absent,
1986 fee_proportional_millionths: 0,
1987 excess_data: Vec::new()
1990 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1992 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1996 fn simple_route_test() {
1997 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1998 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1999 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2000 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2002 // Simple route to 2 via 1
2004 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
2005 assert_eq!(err, "Cannot send a payment of 0 msat");
2006 } else { panic!(); }
2008 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2009 assert_eq!(route.paths[0].len(), 2);
2011 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2012 assert_eq!(route.paths[0][0].short_channel_id, 2);
2013 assert_eq!(route.paths[0][0].fee_msat, 100);
2014 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2015 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2016 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2018 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2019 assert_eq!(route.paths[0][1].short_channel_id, 4);
2020 assert_eq!(route.paths[0][1].fee_msat, 100);
2021 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2022 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2023 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2027 fn invalid_first_hop_test() {
2028 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2029 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2030 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2031 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2033 // Simple route to 2 via 1
2035 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2037 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
2038 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2039 } else { panic!(); }
2041 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2042 assert_eq!(route.paths[0].len(), 2);
2046 fn htlc_minimum_test() {
2047 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2048 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2049 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2050 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2052 // Simple route to 2 via 1
2054 // Disable other paths
2055 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2056 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2057 short_channel_id: 12,
2059 flags: 2, // to disable
2060 cltv_expiry_delta: 0,
2061 htlc_minimum_msat: 0,
2062 htlc_maximum_msat: OptionalField::Absent,
2064 fee_proportional_millionths: 0,
2065 excess_data: Vec::new()
2067 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2069 short_channel_id: 3,
2071 flags: 2, // to disable
2072 cltv_expiry_delta: 0,
2073 htlc_minimum_msat: 0,
2074 htlc_maximum_msat: OptionalField::Absent,
2076 fee_proportional_millionths: 0,
2077 excess_data: Vec::new()
2079 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2080 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2081 short_channel_id: 13,
2083 flags: 2, // to disable
2084 cltv_expiry_delta: 0,
2085 htlc_minimum_msat: 0,
2086 htlc_maximum_msat: OptionalField::Absent,
2088 fee_proportional_millionths: 0,
2089 excess_data: Vec::new()
2091 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2092 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2093 short_channel_id: 6,
2095 flags: 2, // to disable
2096 cltv_expiry_delta: 0,
2097 htlc_minimum_msat: 0,
2098 htlc_maximum_msat: OptionalField::Absent,
2100 fee_proportional_millionths: 0,
2101 excess_data: Vec::new()
2103 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2104 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2105 short_channel_id: 7,
2107 flags: 2, // to disable
2108 cltv_expiry_delta: 0,
2109 htlc_minimum_msat: 0,
2110 htlc_maximum_msat: OptionalField::Absent,
2112 fee_proportional_millionths: 0,
2113 excess_data: Vec::new()
2116 // Check against amount_to_transfer_over_msat.
2117 // Set minimal HTLC of 200_000_000 msat.
2118 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2119 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2120 short_channel_id: 2,
2123 cltv_expiry_delta: 0,
2124 htlc_minimum_msat: 200_000_000,
2125 htlc_maximum_msat: OptionalField::Absent,
2127 fee_proportional_millionths: 0,
2128 excess_data: Vec::new()
2131 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2133 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2134 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2135 short_channel_id: 4,
2138 cltv_expiry_delta: 0,
2139 htlc_minimum_msat: 0,
2140 htlc_maximum_msat: OptionalField::Present(199_999_999),
2142 fee_proportional_millionths: 0,
2143 excess_data: Vec::new()
2146 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2147 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2148 assert_eq!(err, "Failed to find a path to the given destination");
2149 } else { panic!(); }
2151 // Lift the restriction on the first hop.
2152 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2153 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2154 short_channel_id: 2,
2157 cltv_expiry_delta: 0,
2158 htlc_minimum_msat: 0,
2159 htlc_maximum_msat: OptionalField::Absent,
2161 fee_proportional_millionths: 0,
2162 excess_data: Vec::new()
2165 // A payment above the minimum should pass
2166 let route = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2167 assert_eq!(route.paths[0].len(), 2);
2171 fn htlc_minimum_overpay_test() {
2172 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2173 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2174 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2175 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2177 // A route to node#2 via two paths.
2178 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2179 // Thus, they can't send 60 without overpaying.
2180 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2181 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2182 short_channel_id: 2,
2185 cltv_expiry_delta: 0,
2186 htlc_minimum_msat: 35_000,
2187 htlc_maximum_msat: OptionalField::Present(40_000),
2189 fee_proportional_millionths: 0,
2190 excess_data: Vec::new()
2192 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2193 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2194 short_channel_id: 12,
2197 cltv_expiry_delta: 0,
2198 htlc_minimum_msat: 35_000,
2199 htlc_maximum_msat: OptionalField::Present(40_000),
2201 fee_proportional_millionths: 0,
2202 excess_data: Vec::new()
2206 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2208 short_channel_id: 13,
2211 cltv_expiry_delta: 0,
2212 htlc_minimum_msat: 0,
2213 htlc_maximum_msat: OptionalField::Absent,
2215 fee_proportional_millionths: 0,
2216 excess_data: Vec::new()
2218 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2220 short_channel_id: 4,
2223 cltv_expiry_delta: 0,
2224 htlc_minimum_msat: 0,
2225 htlc_maximum_msat: OptionalField::Absent,
2227 fee_proportional_millionths: 0,
2228 excess_data: Vec::new()
2231 // Disable other paths
2232 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2234 short_channel_id: 1,
2236 flags: 2, // to disable
2237 cltv_expiry_delta: 0,
2238 htlc_minimum_msat: 0,
2239 htlc_maximum_msat: OptionalField::Absent,
2241 fee_proportional_millionths: 0,
2242 excess_data: Vec::new()
2245 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2246 // Overpay fees to hit htlc_minimum_msat.
2247 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2248 // TODO: this could be better balanced to overpay 10k and not 15k.
2249 assert_eq!(overpaid_fees, 15_000);
2251 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2252 // while taking even more fee to match htlc_minimum_msat.
2253 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2254 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2255 short_channel_id: 12,
2258 cltv_expiry_delta: 0,
2259 htlc_minimum_msat: 65_000,
2260 htlc_maximum_msat: OptionalField::Present(80_000),
2262 fee_proportional_millionths: 0,
2263 excess_data: Vec::new()
2265 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2266 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2267 short_channel_id: 2,
2270 cltv_expiry_delta: 0,
2271 htlc_minimum_msat: 0,
2272 htlc_maximum_msat: OptionalField::Absent,
2274 fee_proportional_millionths: 0,
2275 excess_data: Vec::new()
2277 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2278 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2279 short_channel_id: 4,
2282 cltv_expiry_delta: 0,
2283 htlc_minimum_msat: 0,
2284 htlc_maximum_msat: OptionalField::Absent,
2286 fee_proportional_millionths: 100_000,
2287 excess_data: Vec::new()
2290 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2291 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2292 assert_eq!(route.paths.len(), 1);
2293 assert_eq!(route.paths[0][0].short_channel_id, 12);
2294 let fees = route.paths[0][0].fee_msat;
2295 assert_eq!(fees, 5_000);
2297 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2298 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2299 // the other channel.
2300 assert_eq!(route.paths.len(), 1);
2301 assert_eq!(route.paths[0][0].short_channel_id, 2);
2302 let fees = route.paths[0][0].fee_msat;
2303 assert_eq!(fees, 5_000);
2307 fn disable_channels_test() {
2308 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2309 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2310 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2311 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2313 // // Disable channels 4 and 12 by flags=2
2314 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2316 short_channel_id: 4,
2318 flags: 2, // to disable
2319 cltv_expiry_delta: 0,
2320 htlc_minimum_msat: 0,
2321 htlc_maximum_msat: OptionalField::Absent,
2323 fee_proportional_millionths: 0,
2324 excess_data: Vec::new()
2326 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2327 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2328 short_channel_id: 12,
2330 flags: 2, // to disable
2331 cltv_expiry_delta: 0,
2332 htlc_minimum_msat: 0,
2333 htlc_maximum_msat: OptionalField::Absent,
2335 fee_proportional_millionths: 0,
2336 excess_data: Vec::new()
2339 // If all the channels require some features we don't understand, route should fail
2340 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2341 assert_eq!(err, "Failed to find a path to the given destination");
2342 } else { panic!(); }
2344 // If we specify a channel to node7, that overrides our local channel view and that gets used
2345 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2346 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2347 assert_eq!(route.paths[0].len(), 2);
2349 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2350 assert_eq!(route.paths[0][0].short_channel_id, 42);
2351 assert_eq!(route.paths[0][0].fee_msat, 200);
2352 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2353 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2354 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2356 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2357 assert_eq!(route.paths[0][1].short_channel_id, 13);
2358 assert_eq!(route.paths[0][1].fee_msat, 100);
2359 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2360 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2361 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2365 fn disable_node_test() {
2366 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2367 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2368 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2369 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2371 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2372 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2373 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2374 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2375 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2377 // If all nodes require some features we don't understand, route should fail
2378 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2379 assert_eq!(err, "Failed to find a path to the given destination");
2380 } else { panic!(); }
2382 // If we specify a channel to node7, that overrides our local channel view and that gets used
2383 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2384 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2385 assert_eq!(route.paths[0].len(), 2);
2387 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2388 assert_eq!(route.paths[0][0].short_channel_id, 42);
2389 assert_eq!(route.paths[0][0].fee_msat, 200);
2390 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2391 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2392 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2394 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2395 assert_eq!(route.paths[0][1].short_channel_id, 13);
2396 assert_eq!(route.paths[0][1].fee_msat, 100);
2397 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2398 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2399 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2401 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2402 // naively) assume that the user checked the feature bits on the invoice, which override
2403 // the node_announcement.
2407 fn our_chans_test() {
2408 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2409 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2410 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2412 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2413 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2414 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2415 assert_eq!(route.paths[0].len(), 3);
2417 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2418 assert_eq!(route.paths[0][0].short_channel_id, 2);
2419 assert_eq!(route.paths[0][0].fee_msat, 200);
2420 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2421 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2422 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2424 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2425 assert_eq!(route.paths[0][1].short_channel_id, 4);
2426 assert_eq!(route.paths[0][1].fee_msat, 100);
2427 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2428 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2429 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2431 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2432 assert_eq!(route.paths[0][2].short_channel_id, 3);
2433 assert_eq!(route.paths[0][2].fee_msat, 100);
2434 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2435 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2436 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2438 // If we specify a channel to node7, that overrides our local channel view and that gets used
2439 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2440 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2441 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2442 assert_eq!(route.paths[0].len(), 2);
2444 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2445 assert_eq!(route.paths[0][0].short_channel_id, 42);
2446 assert_eq!(route.paths[0][0].fee_msat, 200);
2447 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2448 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2449 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2451 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2452 assert_eq!(route.paths[0][1].short_channel_id, 13);
2453 assert_eq!(route.paths[0][1].fee_msat, 100);
2454 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2455 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2456 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2459 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2460 let zero_fees = RoutingFees {
2462 proportional_millionths: 0,
2464 vec![RouteHint(vec![RouteHintHop {
2465 src_node_id: nodes[3],
2466 short_channel_id: 8,
2468 cltv_expiry_delta: (8 << 4) | 1,
2469 htlc_minimum_msat: None,
2470 htlc_maximum_msat: None,
2472 ]), RouteHint(vec![RouteHintHop {
2473 src_node_id: nodes[4],
2474 short_channel_id: 9,
2477 proportional_millionths: 0,
2479 cltv_expiry_delta: (9 << 4) | 1,
2480 htlc_minimum_msat: None,
2481 htlc_maximum_msat: None,
2482 }]), RouteHint(vec![RouteHintHop {
2483 src_node_id: nodes[5],
2484 short_channel_id: 10,
2486 cltv_expiry_delta: (10 << 4) | 1,
2487 htlc_minimum_msat: None,
2488 htlc_maximum_msat: None,
2492 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2493 let zero_fees = RoutingFees {
2495 proportional_millionths: 0,
2497 vec![RouteHint(vec![RouteHintHop {
2498 src_node_id: nodes[2],
2499 short_channel_id: 5,
2502 proportional_millionths: 0,
2504 cltv_expiry_delta: (5 << 4) | 1,
2505 htlc_minimum_msat: None,
2506 htlc_maximum_msat: None,
2508 src_node_id: nodes[3],
2509 short_channel_id: 8,
2511 cltv_expiry_delta: (8 << 4) | 1,
2512 htlc_minimum_msat: None,
2513 htlc_maximum_msat: None,
2515 ]), RouteHint(vec![RouteHintHop {
2516 src_node_id: nodes[4],
2517 short_channel_id: 9,
2520 proportional_millionths: 0,
2522 cltv_expiry_delta: (9 << 4) | 1,
2523 htlc_minimum_msat: None,
2524 htlc_maximum_msat: None,
2525 }]), RouteHint(vec![RouteHintHop {
2526 src_node_id: nodes[5],
2527 short_channel_id: 10,
2529 cltv_expiry_delta: (10 << 4) | 1,
2530 htlc_minimum_msat: None,
2531 htlc_maximum_msat: None,
2536 fn partial_route_hint_test() {
2537 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2538 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2539 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2541 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2542 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2543 // RouteHint may be partially used by the algo to build the best path.
2545 // First check that last hop can't have its source as the payee.
2546 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2547 src_node_id: nodes[6],
2548 short_channel_id: 8,
2551 proportional_millionths: 0,
2553 cltv_expiry_delta: (8 << 4) | 1,
2554 htlc_minimum_msat: None,
2555 htlc_maximum_msat: None,
2558 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2559 invalid_last_hops.push(invalid_last_hop);
2561 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2562 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2563 assert_eq!(err, "Route hint cannot have the payee as the source.");
2564 } else { panic!(); }
2567 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2568 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2569 assert_eq!(route.paths[0].len(), 5);
2571 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2572 assert_eq!(route.paths[0][0].short_channel_id, 2);
2573 assert_eq!(route.paths[0][0].fee_msat, 100);
2574 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2575 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2576 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2578 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2579 assert_eq!(route.paths[0][1].short_channel_id, 4);
2580 assert_eq!(route.paths[0][1].fee_msat, 0);
2581 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2582 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2583 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2585 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2586 assert_eq!(route.paths[0][2].short_channel_id, 6);
2587 assert_eq!(route.paths[0][2].fee_msat, 0);
2588 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2589 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2590 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2592 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2593 assert_eq!(route.paths[0][3].short_channel_id, 11);
2594 assert_eq!(route.paths[0][3].fee_msat, 0);
2595 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2596 // If we have a peer in the node map, we'll use their features here since we don't have
2597 // a way of figuring out their features from the invoice:
2598 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2599 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2601 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2602 assert_eq!(route.paths[0][4].short_channel_id, 8);
2603 assert_eq!(route.paths[0][4].fee_msat, 100);
2604 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2605 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2606 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2609 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2610 let zero_fees = RoutingFees {
2612 proportional_millionths: 0,
2614 vec![RouteHint(vec![RouteHintHop {
2615 src_node_id: nodes[3],
2616 short_channel_id: 8,
2618 cltv_expiry_delta: (8 << 4) | 1,
2619 htlc_minimum_msat: None,
2620 htlc_maximum_msat: None,
2621 }]), RouteHint(vec![
2623 ]), RouteHint(vec![RouteHintHop {
2624 src_node_id: nodes[5],
2625 short_channel_id: 10,
2627 cltv_expiry_delta: (10 << 4) | 1,
2628 htlc_minimum_msat: None,
2629 htlc_maximum_msat: None,
2634 fn ignores_empty_last_hops_test() {
2635 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2636 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2637 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2638 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2640 // Test handling of an empty RouteHint passed in Invoice.
2642 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2643 assert_eq!(route.paths[0].len(), 5);
2645 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2646 assert_eq!(route.paths[0][0].short_channel_id, 2);
2647 assert_eq!(route.paths[0][0].fee_msat, 100);
2648 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2649 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2650 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2652 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2653 assert_eq!(route.paths[0][1].short_channel_id, 4);
2654 assert_eq!(route.paths[0][1].fee_msat, 0);
2655 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2656 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2657 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2659 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2660 assert_eq!(route.paths[0][2].short_channel_id, 6);
2661 assert_eq!(route.paths[0][2].fee_msat, 0);
2662 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2663 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2664 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2666 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2667 assert_eq!(route.paths[0][3].short_channel_id, 11);
2668 assert_eq!(route.paths[0][3].fee_msat, 0);
2669 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2670 // If we have a peer in the node map, we'll use their features here since we don't have
2671 // a way of figuring out their features from the invoice:
2672 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2673 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2675 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2676 assert_eq!(route.paths[0][4].short_channel_id, 8);
2677 assert_eq!(route.paths[0][4].fee_msat, 100);
2678 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2679 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2680 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2683 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2684 let zero_fees = RoutingFees {
2686 proportional_millionths: 0,
2688 vec![RouteHint(vec![RouteHintHop {
2689 src_node_id: nodes[2],
2690 short_channel_id: 5,
2693 proportional_millionths: 0,
2695 cltv_expiry_delta: (5 << 4) | 1,
2696 htlc_minimum_msat: None,
2697 htlc_maximum_msat: None,
2699 src_node_id: nodes[3],
2700 short_channel_id: 8,
2702 cltv_expiry_delta: (8 << 4) | 1,
2703 htlc_minimum_msat: None,
2704 htlc_maximum_msat: None,
2705 }]), RouteHint(vec![RouteHintHop {
2706 src_node_id: nodes[5],
2707 short_channel_id: 10,
2709 cltv_expiry_delta: (10 << 4) | 1,
2710 htlc_minimum_msat: None,
2711 htlc_maximum_msat: None,
2716 fn multi_hint_last_hops_test() {
2717 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2718 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2719 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2720 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2721 // Test through channels 2, 3, 5, 8.
2722 // Test shows that multiple hop hints are considered.
2724 // Disabling channels 6 & 7 by flags=2
2725 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2726 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2727 short_channel_id: 6,
2729 flags: 2, // to disable
2730 cltv_expiry_delta: 0,
2731 htlc_minimum_msat: 0,
2732 htlc_maximum_msat: OptionalField::Absent,
2734 fee_proportional_millionths: 0,
2735 excess_data: Vec::new()
2737 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2739 short_channel_id: 7,
2741 flags: 2, // to disable
2742 cltv_expiry_delta: 0,
2743 htlc_minimum_msat: 0,
2744 htlc_maximum_msat: OptionalField::Absent,
2746 fee_proportional_millionths: 0,
2747 excess_data: Vec::new()
2750 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2751 assert_eq!(route.paths[0].len(), 4);
2753 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2754 assert_eq!(route.paths[0][0].short_channel_id, 2);
2755 assert_eq!(route.paths[0][0].fee_msat, 200);
2756 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2757 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2758 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2760 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2761 assert_eq!(route.paths[0][1].short_channel_id, 4);
2762 assert_eq!(route.paths[0][1].fee_msat, 100);
2763 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2764 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2765 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2767 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2768 assert_eq!(route.paths[0][2].short_channel_id, 5);
2769 assert_eq!(route.paths[0][2].fee_msat, 0);
2770 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2771 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2772 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2774 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2775 assert_eq!(route.paths[0][3].short_channel_id, 8);
2776 assert_eq!(route.paths[0][3].fee_msat, 100);
2777 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2778 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2779 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2782 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2783 let zero_fees = RoutingFees {
2785 proportional_millionths: 0,
2787 vec![RouteHint(vec![RouteHintHop {
2788 src_node_id: nodes[4],
2789 short_channel_id: 11,
2791 cltv_expiry_delta: (11 << 4) | 1,
2792 htlc_minimum_msat: None,
2793 htlc_maximum_msat: None,
2795 src_node_id: nodes[3],
2796 short_channel_id: 8,
2798 cltv_expiry_delta: (8 << 4) | 1,
2799 htlc_minimum_msat: None,
2800 htlc_maximum_msat: None,
2801 }]), RouteHint(vec![RouteHintHop {
2802 src_node_id: nodes[4],
2803 short_channel_id: 9,
2806 proportional_millionths: 0,
2808 cltv_expiry_delta: (9 << 4) | 1,
2809 htlc_minimum_msat: None,
2810 htlc_maximum_msat: None,
2811 }]), RouteHint(vec![RouteHintHop {
2812 src_node_id: nodes[5],
2813 short_channel_id: 10,
2815 cltv_expiry_delta: (10 << 4) | 1,
2816 htlc_minimum_msat: None,
2817 htlc_maximum_msat: None,
2822 fn last_hops_with_public_channel_test() {
2823 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2824 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2825 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2826 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2827 // This test shows that public routes can be present in the invoice
2828 // which would be handled in the same manner.
2830 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2831 assert_eq!(route.paths[0].len(), 5);
2833 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2834 assert_eq!(route.paths[0][0].short_channel_id, 2);
2835 assert_eq!(route.paths[0][0].fee_msat, 100);
2836 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2837 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2838 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2840 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2841 assert_eq!(route.paths[0][1].short_channel_id, 4);
2842 assert_eq!(route.paths[0][1].fee_msat, 0);
2843 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2844 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2845 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2847 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2848 assert_eq!(route.paths[0][2].short_channel_id, 6);
2849 assert_eq!(route.paths[0][2].fee_msat, 0);
2850 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2851 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2852 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2854 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2855 assert_eq!(route.paths[0][3].short_channel_id, 11);
2856 assert_eq!(route.paths[0][3].fee_msat, 0);
2857 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2858 // If we have a peer in the node map, we'll use their features here since we don't have
2859 // a way of figuring out their features from the invoice:
2860 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2861 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2863 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2864 assert_eq!(route.paths[0][4].short_channel_id, 8);
2865 assert_eq!(route.paths[0][4].fee_msat, 100);
2866 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2867 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2868 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2872 fn our_chans_last_hop_connect_test() {
2873 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2874 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2875 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2877 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2878 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2879 let mut last_hops = last_hops(&nodes);
2880 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2881 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2882 assert_eq!(route.paths[0].len(), 2);
2884 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2885 assert_eq!(route.paths[0][0].short_channel_id, 42);
2886 assert_eq!(route.paths[0][0].fee_msat, 0);
2887 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2888 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2889 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2891 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2892 assert_eq!(route.paths[0][1].short_channel_id, 8);
2893 assert_eq!(route.paths[0][1].fee_msat, 100);
2894 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2895 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2896 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2898 last_hops[0].0[0].fees.base_msat = 1000;
2900 // Revert to via 6 as the fee on 8 goes up
2901 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
2902 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2903 assert_eq!(route.paths[0].len(), 4);
2905 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2906 assert_eq!(route.paths[0][0].short_channel_id, 2);
2907 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2908 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2909 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2910 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2912 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2913 assert_eq!(route.paths[0][1].short_channel_id, 4);
2914 assert_eq!(route.paths[0][1].fee_msat, 100);
2915 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
2916 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2917 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2919 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2920 assert_eq!(route.paths[0][2].short_channel_id, 7);
2921 assert_eq!(route.paths[0][2].fee_msat, 0);
2922 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
2923 // If we have a peer in the node map, we'll use their features here since we don't have
2924 // a way of figuring out their features from the invoice:
2925 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2926 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2928 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2929 assert_eq!(route.paths[0][3].short_channel_id, 10);
2930 assert_eq!(route.paths[0][3].fee_msat, 100);
2931 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2932 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2933 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2935 // ...but still use 8 for larger payments as 6 has a variable feerate
2936 let route = get_route(&our_id, &payment_params, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2937 assert_eq!(route.paths[0].len(), 5);
2939 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2940 assert_eq!(route.paths[0][0].short_channel_id, 2);
2941 assert_eq!(route.paths[0][0].fee_msat, 3000);
2942 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2943 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2944 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2946 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2947 assert_eq!(route.paths[0][1].short_channel_id, 4);
2948 assert_eq!(route.paths[0][1].fee_msat, 0);
2949 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2950 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2951 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2953 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2954 assert_eq!(route.paths[0][2].short_channel_id, 6);
2955 assert_eq!(route.paths[0][2].fee_msat, 0);
2956 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2957 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2958 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2960 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2961 assert_eq!(route.paths[0][3].short_channel_id, 11);
2962 assert_eq!(route.paths[0][3].fee_msat, 1000);
2963 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2964 // If we have a peer in the node map, we'll use their features here since we don't have
2965 // a way of figuring out their features from the invoice:
2966 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2967 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2969 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2970 assert_eq!(route.paths[0][4].short_channel_id, 8);
2971 assert_eq!(route.paths[0][4].fee_msat, 2000);
2972 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2973 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2974 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2977 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> {
2978 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2979 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2980 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2982 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2983 let last_hops = RouteHint(vec![RouteHintHop {
2984 src_node_id: middle_node_id,
2985 short_channel_id: 8,
2988 proportional_millionths: last_hop_fee_prop,
2990 cltv_expiry_delta: (8 << 4) | 1,
2991 htlc_minimum_msat: None,
2992 htlc_maximum_msat: last_hop_htlc_max,
2994 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
2995 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2996 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2997 get_route(&source_node_id, &payment_params, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer)
3001 fn unannounced_path_test() {
3002 // We should be able to send a payment to a destination without any help of a routing graph
3003 // if we have a channel with a common counterparty that appears in the first and last hop
3005 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3007 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3008 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3009 assert_eq!(route.paths[0].len(), 2);
3011 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3012 assert_eq!(route.paths[0][0].short_channel_id, 42);
3013 assert_eq!(route.paths[0][0].fee_msat, 1001);
3014 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3015 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3016 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3018 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3019 assert_eq!(route.paths[0][1].short_channel_id, 8);
3020 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3021 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3022 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3023 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3027 fn overflow_unannounced_path_test_liquidity_underflow() {
3028 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3029 // the last-hop had a fee which overflowed a u64, we'd panic.
3030 // This was due to us adding the first-hop from us unconditionally, causing us to think
3031 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3032 // In this test, we previously hit a subtraction underflow due to having less available
3033 // liquidity at the last hop than 0.
3034 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());
3038 fn overflow_unannounced_path_test_feerate_overflow() {
3039 // This tests for the same case as above, except instead of hitting a subtraction
3040 // underflow, we hit a case where the fee charged at a hop overflowed.
3041 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());
3045 fn available_amount_while_routing_test() {
3046 // Tests whether we choose the correct available channel amount while routing.
3048 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3049 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3050 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3051 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3053 // We will use a simple single-path route from
3054 // our node to node2 via node0: channels {1, 3}.
3056 // First disable all other paths.
3057 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3059 short_channel_id: 2,
3062 cltv_expiry_delta: 0,
3063 htlc_minimum_msat: 0,
3064 htlc_maximum_msat: OptionalField::Present(100_000),
3066 fee_proportional_millionths: 0,
3067 excess_data: Vec::new()
3069 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3071 short_channel_id: 12,
3074 cltv_expiry_delta: 0,
3075 htlc_minimum_msat: 0,
3076 htlc_maximum_msat: OptionalField::Present(100_000),
3078 fee_proportional_millionths: 0,
3079 excess_data: Vec::new()
3082 // Make the first channel (#1) very permissive,
3083 // and we will be testing all limits on the second channel.
3084 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3085 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3086 short_channel_id: 1,
3089 cltv_expiry_delta: 0,
3090 htlc_minimum_msat: 0,
3091 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3093 fee_proportional_millionths: 0,
3094 excess_data: Vec::new()
3097 // First, let's see if routing works if we have absolutely no idea about the available amount.
3098 // In this case, it should be set to 250_000 sats.
3099 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3101 short_channel_id: 3,
3104 cltv_expiry_delta: 0,
3105 htlc_minimum_msat: 0,
3106 htlc_maximum_msat: OptionalField::Absent,
3108 fee_proportional_millionths: 0,
3109 excess_data: Vec::new()
3113 // Attempt to route more than available results in a failure.
3114 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3115 &our_id, &payment_params, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3116 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3117 } else { panic!(); }
3121 // Now, attempt to route an exact amount we have should be fine.
3122 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3123 assert_eq!(route.paths.len(), 1);
3124 let path = route.paths.last().unwrap();
3125 assert_eq!(path.len(), 2);
3126 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3127 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3130 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3131 // Disable channel #1 and use another first hop.
3132 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3133 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3134 short_channel_id: 1,
3137 cltv_expiry_delta: 0,
3138 htlc_minimum_msat: 0,
3139 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3141 fee_proportional_millionths: 0,
3142 excess_data: Vec::new()
3145 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3146 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3149 // Attempt to route more than available results in a failure.
3150 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3151 &our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3152 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3153 } else { panic!(); }
3157 // Now, attempt to route an exact amount we have should be fine.
3158 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3159 assert_eq!(route.paths.len(), 1);
3160 let path = route.paths.last().unwrap();
3161 assert_eq!(path.len(), 2);
3162 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3163 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3166 // Enable channel #1 back.
3167 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3168 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3169 short_channel_id: 1,
3172 cltv_expiry_delta: 0,
3173 htlc_minimum_msat: 0,
3174 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3176 fee_proportional_millionths: 0,
3177 excess_data: Vec::new()
3181 // Now let's see if routing works if we know only htlc_maximum_msat.
3182 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3184 short_channel_id: 3,
3187 cltv_expiry_delta: 0,
3188 htlc_minimum_msat: 0,
3189 htlc_maximum_msat: OptionalField::Present(15_000),
3191 fee_proportional_millionths: 0,
3192 excess_data: Vec::new()
3196 // Attempt to route more than available results in a failure.
3197 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3198 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3199 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3200 } else { panic!(); }
3204 // Now, attempt to route an exact amount we have should be fine.
3205 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3206 assert_eq!(route.paths.len(), 1);
3207 let path = route.paths.last().unwrap();
3208 assert_eq!(path.len(), 2);
3209 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3210 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3213 // Now let's see if routing works if we know only capacity from the UTXO.
3215 // We can't change UTXO capacity on the fly, so we'll disable
3216 // the existing channel and add another one with the capacity we need.
3217 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3219 short_channel_id: 3,
3222 cltv_expiry_delta: 0,
3223 htlc_minimum_msat: 0,
3224 htlc_maximum_msat: OptionalField::Absent,
3226 fee_proportional_millionths: 0,
3227 excess_data: Vec::new()
3230 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3231 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3232 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3233 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3234 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3236 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3237 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3239 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3240 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3241 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3242 short_channel_id: 333,
3245 cltv_expiry_delta: (3 << 4) | 1,
3246 htlc_minimum_msat: 0,
3247 htlc_maximum_msat: OptionalField::Absent,
3249 fee_proportional_millionths: 0,
3250 excess_data: Vec::new()
3252 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3253 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3254 short_channel_id: 333,
3257 cltv_expiry_delta: (3 << 4) | 2,
3258 htlc_minimum_msat: 0,
3259 htlc_maximum_msat: OptionalField::Absent,
3261 fee_proportional_millionths: 0,
3262 excess_data: Vec::new()
3266 // Attempt to route more than available results in a failure.
3267 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3268 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3269 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3270 } else { panic!(); }
3274 // Now, attempt to route an exact amount we have should be fine.
3275 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3276 assert_eq!(route.paths.len(), 1);
3277 let path = route.paths.last().unwrap();
3278 assert_eq!(path.len(), 2);
3279 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3280 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3283 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3284 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3286 short_channel_id: 333,
3289 cltv_expiry_delta: 0,
3290 htlc_minimum_msat: 0,
3291 htlc_maximum_msat: OptionalField::Present(10_000),
3293 fee_proportional_millionths: 0,
3294 excess_data: Vec::new()
3298 // Attempt to route more than available results in a failure.
3299 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3300 &our_id, &payment_params, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3301 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3302 } else { panic!(); }
3306 // Now, attempt to route an exact amount we have should be fine.
3307 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3308 assert_eq!(route.paths.len(), 1);
3309 let path = route.paths.last().unwrap();
3310 assert_eq!(path.len(), 2);
3311 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3312 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3317 fn available_liquidity_last_hop_test() {
3318 // Check that available liquidity properly limits the path even when only
3319 // one of the latter hops is limited.
3320 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3321 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3322 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3323 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3325 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3326 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3327 // Total capacity: 50 sats.
3329 // Disable other potential paths.
3330 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3331 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3332 short_channel_id: 2,
3335 cltv_expiry_delta: 0,
3336 htlc_minimum_msat: 0,
3337 htlc_maximum_msat: OptionalField::Present(100_000),
3339 fee_proportional_millionths: 0,
3340 excess_data: Vec::new()
3342 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3343 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3344 short_channel_id: 7,
3347 cltv_expiry_delta: 0,
3348 htlc_minimum_msat: 0,
3349 htlc_maximum_msat: OptionalField::Present(100_000),
3351 fee_proportional_millionths: 0,
3352 excess_data: Vec::new()
3357 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3358 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3359 short_channel_id: 12,
3362 cltv_expiry_delta: 0,
3363 htlc_minimum_msat: 0,
3364 htlc_maximum_msat: OptionalField::Present(100_000),
3366 fee_proportional_millionths: 0,
3367 excess_data: Vec::new()
3369 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3370 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3371 short_channel_id: 13,
3374 cltv_expiry_delta: 0,
3375 htlc_minimum_msat: 0,
3376 htlc_maximum_msat: OptionalField::Present(100_000),
3378 fee_proportional_millionths: 0,
3379 excess_data: Vec::new()
3382 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3384 short_channel_id: 6,
3387 cltv_expiry_delta: 0,
3388 htlc_minimum_msat: 0,
3389 htlc_maximum_msat: OptionalField::Present(50_000),
3391 fee_proportional_millionths: 0,
3392 excess_data: Vec::new()
3394 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3396 short_channel_id: 11,
3399 cltv_expiry_delta: 0,
3400 htlc_minimum_msat: 0,
3401 htlc_maximum_msat: OptionalField::Present(100_000),
3403 fee_proportional_millionths: 0,
3404 excess_data: Vec::new()
3407 // Attempt to route more than available results in a failure.
3408 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3409 &our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3410 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3411 } else { panic!(); }
3415 // Now, attempt to route 49 sats (just a bit below the capacity).
3416 let route = get_route(&our_id, &payment_params, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3417 assert_eq!(route.paths.len(), 1);
3418 let mut total_amount_paid_msat = 0;
3419 for path in &route.paths {
3420 assert_eq!(path.len(), 4);
3421 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3422 total_amount_paid_msat += path.last().unwrap().fee_msat;
3424 assert_eq!(total_amount_paid_msat, 49_000);
3428 // Attempt to route an exact amount is also fine
3429 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3430 assert_eq!(route.paths.len(), 1);
3431 let mut total_amount_paid_msat = 0;
3432 for path in &route.paths {
3433 assert_eq!(path.len(), 4);
3434 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3435 total_amount_paid_msat += path.last().unwrap().fee_msat;
3437 assert_eq!(total_amount_paid_msat, 50_000);
3442 fn ignore_fee_first_hop_test() {
3443 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3444 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3445 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3446 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3448 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3449 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3450 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3451 short_channel_id: 1,
3454 cltv_expiry_delta: 0,
3455 htlc_minimum_msat: 0,
3456 htlc_maximum_msat: OptionalField::Present(100_000),
3457 fee_base_msat: 1_000_000,
3458 fee_proportional_millionths: 0,
3459 excess_data: Vec::new()
3461 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3463 short_channel_id: 3,
3466 cltv_expiry_delta: 0,
3467 htlc_minimum_msat: 0,
3468 htlc_maximum_msat: OptionalField::Present(50_000),
3470 fee_proportional_millionths: 0,
3471 excess_data: Vec::new()
3475 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3476 assert_eq!(route.paths.len(), 1);
3477 let mut total_amount_paid_msat = 0;
3478 for path in &route.paths {
3479 assert_eq!(path.len(), 2);
3480 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3481 total_amount_paid_msat += path.last().unwrap().fee_msat;
3483 assert_eq!(total_amount_paid_msat, 50_000);
3488 fn simple_mpp_route_test() {
3489 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3490 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3491 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3492 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3494 // We need a route consisting of 3 paths:
3495 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3496 // To achieve this, the amount being transferred should be around
3497 // the total capacity of these 3 paths.
3499 // First, we set limits on these (previously unlimited) channels.
3500 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3502 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3503 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3504 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3505 short_channel_id: 1,
3508 cltv_expiry_delta: 0,
3509 htlc_minimum_msat: 0,
3510 htlc_maximum_msat: OptionalField::Present(100_000),
3512 fee_proportional_millionths: 0,
3513 excess_data: Vec::new()
3515 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3517 short_channel_id: 3,
3520 cltv_expiry_delta: 0,
3521 htlc_minimum_msat: 0,
3522 htlc_maximum_msat: OptionalField::Present(50_000),
3524 fee_proportional_millionths: 0,
3525 excess_data: Vec::new()
3528 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3529 // (total limit 60).
3530 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3531 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3532 short_channel_id: 12,
3535 cltv_expiry_delta: 0,
3536 htlc_minimum_msat: 0,
3537 htlc_maximum_msat: OptionalField::Present(60_000),
3539 fee_proportional_millionths: 0,
3540 excess_data: Vec::new()
3542 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3544 short_channel_id: 13,
3547 cltv_expiry_delta: 0,
3548 htlc_minimum_msat: 0,
3549 htlc_maximum_msat: OptionalField::Present(60_000),
3551 fee_proportional_millionths: 0,
3552 excess_data: Vec::new()
3555 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3556 // (total capacity 180 sats).
3557 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3558 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3559 short_channel_id: 2,
3562 cltv_expiry_delta: 0,
3563 htlc_minimum_msat: 0,
3564 htlc_maximum_msat: OptionalField::Present(200_000),
3566 fee_proportional_millionths: 0,
3567 excess_data: Vec::new()
3569 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3570 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3571 short_channel_id: 4,
3574 cltv_expiry_delta: 0,
3575 htlc_minimum_msat: 0,
3576 htlc_maximum_msat: OptionalField::Present(180_000),
3578 fee_proportional_millionths: 0,
3579 excess_data: Vec::new()
3583 // Attempt to route more than available results in a failure.
3584 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3585 &our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3586 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3587 } else { panic!(); }
3591 // Now, attempt to route 250 sats (just a bit below the capacity).
3592 // Our algorithm should provide us with these 3 paths.
3593 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3594 assert_eq!(route.paths.len(), 3);
3595 let mut total_amount_paid_msat = 0;
3596 for path in &route.paths {
3597 assert_eq!(path.len(), 2);
3598 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3599 total_amount_paid_msat += path.last().unwrap().fee_msat;
3601 assert_eq!(total_amount_paid_msat, 250_000);
3605 // Attempt to route an exact amount is also fine
3606 let route = get_route(&our_id, &payment_params, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3607 assert_eq!(route.paths.len(), 3);
3608 let mut total_amount_paid_msat = 0;
3609 for path in &route.paths {
3610 assert_eq!(path.len(), 2);
3611 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3612 total_amount_paid_msat += path.last().unwrap().fee_msat;
3614 assert_eq!(total_amount_paid_msat, 290_000);
3619 fn long_mpp_route_test() {
3620 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3621 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3622 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3623 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3625 // We need a route consisting of 3 paths:
3626 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3627 // Note that these paths overlap (channels 5, 12, 13).
3628 // We will route 300 sats.
3629 // Each path will have 100 sats capacity, those channels which
3630 // are used twice will have 200 sats capacity.
3632 // Disable other potential paths.
3633 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3635 short_channel_id: 2,
3638 cltv_expiry_delta: 0,
3639 htlc_minimum_msat: 0,
3640 htlc_maximum_msat: OptionalField::Present(100_000),
3642 fee_proportional_millionths: 0,
3643 excess_data: Vec::new()
3645 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3646 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3647 short_channel_id: 7,
3650 cltv_expiry_delta: 0,
3651 htlc_minimum_msat: 0,
3652 htlc_maximum_msat: OptionalField::Present(100_000),
3654 fee_proportional_millionths: 0,
3655 excess_data: Vec::new()
3658 // Path via {node0, node2} is channels {1, 3, 5}.
3659 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3661 short_channel_id: 1,
3664 cltv_expiry_delta: 0,
3665 htlc_minimum_msat: 0,
3666 htlc_maximum_msat: OptionalField::Present(100_000),
3668 fee_proportional_millionths: 0,
3669 excess_data: Vec::new()
3671 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3673 short_channel_id: 3,
3676 cltv_expiry_delta: 0,
3677 htlc_minimum_msat: 0,
3678 htlc_maximum_msat: OptionalField::Present(100_000),
3680 fee_proportional_millionths: 0,
3681 excess_data: Vec::new()
3684 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3685 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3686 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3687 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3688 short_channel_id: 5,
3691 cltv_expiry_delta: 0,
3692 htlc_minimum_msat: 0,
3693 htlc_maximum_msat: OptionalField::Present(200_000),
3695 fee_proportional_millionths: 0,
3696 excess_data: Vec::new()
3699 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3700 // Add 100 sats to the capacities of {12, 13}, because these channels
3701 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3702 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3704 short_channel_id: 12,
3707 cltv_expiry_delta: 0,
3708 htlc_minimum_msat: 0,
3709 htlc_maximum_msat: OptionalField::Present(200_000),
3711 fee_proportional_millionths: 0,
3712 excess_data: Vec::new()
3714 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3715 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3716 short_channel_id: 13,
3719 cltv_expiry_delta: 0,
3720 htlc_minimum_msat: 0,
3721 htlc_maximum_msat: OptionalField::Present(200_000),
3723 fee_proportional_millionths: 0,
3724 excess_data: Vec::new()
3727 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3729 short_channel_id: 6,
3732 cltv_expiry_delta: 0,
3733 htlc_minimum_msat: 0,
3734 htlc_maximum_msat: OptionalField::Present(100_000),
3736 fee_proportional_millionths: 0,
3737 excess_data: Vec::new()
3739 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3741 short_channel_id: 11,
3744 cltv_expiry_delta: 0,
3745 htlc_minimum_msat: 0,
3746 htlc_maximum_msat: OptionalField::Present(100_000),
3748 fee_proportional_millionths: 0,
3749 excess_data: Vec::new()
3752 // Path via {node7, node2} is channels {12, 13, 5}.
3753 // We already limited them to 200 sats (they are used twice for 100 sats).
3754 // Nothing to do here.
3757 // Attempt to route more than available results in a failure.
3758 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3759 &our_id, &payment_params, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3760 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3761 } else { panic!(); }
3765 // Now, attempt to route 300 sats (exact amount we can route).
3766 // Our algorithm should provide us with these 3 paths, 100 sats each.
3767 let route = get_route(&our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3768 assert_eq!(route.paths.len(), 3);
3770 let mut total_amount_paid_msat = 0;
3771 for path in &route.paths {
3772 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3773 total_amount_paid_msat += path.last().unwrap().fee_msat;
3775 assert_eq!(total_amount_paid_msat, 300_000);
3781 fn mpp_cheaper_route_test() {
3782 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3783 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3784 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3785 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3787 // This test checks that if we have two cheaper paths and one more expensive path,
3788 // so that liquidity-wise any 2 of 3 combination is sufficient,
3789 // two cheaper paths will be taken.
3790 // These paths have equal available liquidity.
3792 // We need a combination of 3 paths:
3793 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3794 // Note that these paths overlap (channels 5, 12, 13).
3795 // Each path will have 100 sats capacity, those channels which
3796 // are used twice will have 200 sats capacity.
3798 // Disable other potential paths.
3799 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3801 short_channel_id: 2,
3804 cltv_expiry_delta: 0,
3805 htlc_minimum_msat: 0,
3806 htlc_maximum_msat: OptionalField::Present(100_000),
3808 fee_proportional_millionths: 0,
3809 excess_data: Vec::new()
3811 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3812 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3813 short_channel_id: 7,
3816 cltv_expiry_delta: 0,
3817 htlc_minimum_msat: 0,
3818 htlc_maximum_msat: OptionalField::Present(100_000),
3820 fee_proportional_millionths: 0,
3821 excess_data: Vec::new()
3824 // Path via {node0, node2} is channels {1, 3, 5}.
3825 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3826 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3827 short_channel_id: 1,
3830 cltv_expiry_delta: 0,
3831 htlc_minimum_msat: 0,
3832 htlc_maximum_msat: OptionalField::Present(100_000),
3834 fee_proportional_millionths: 0,
3835 excess_data: Vec::new()
3837 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3838 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3839 short_channel_id: 3,
3842 cltv_expiry_delta: 0,
3843 htlc_minimum_msat: 0,
3844 htlc_maximum_msat: OptionalField::Present(100_000),
3846 fee_proportional_millionths: 0,
3847 excess_data: Vec::new()
3850 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3851 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3852 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3853 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3854 short_channel_id: 5,
3857 cltv_expiry_delta: 0,
3858 htlc_minimum_msat: 0,
3859 htlc_maximum_msat: OptionalField::Present(200_000),
3861 fee_proportional_millionths: 0,
3862 excess_data: Vec::new()
3865 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3866 // Add 100 sats to the capacities of {12, 13}, because these channels
3867 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3868 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3870 short_channel_id: 12,
3873 cltv_expiry_delta: 0,
3874 htlc_minimum_msat: 0,
3875 htlc_maximum_msat: OptionalField::Present(200_000),
3877 fee_proportional_millionths: 0,
3878 excess_data: Vec::new()
3880 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3882 short_channel_id: 13,
3885 cltv_expiry_delta: 0,
3886 htlc_minimum_msat: 0,
3887 htlc_maximum_msat: OptionalField::Present(200_000),
3889 fee_proportional_millionths: 0,
3890 excess_data: Vec::new()
3893 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3894 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3895 short_channel_id: 6,
3898 cltv_expiry_delta: 0,
3899 htlc_minimum_msat: 0,
3900 htlc_maximum_msat: OptionalField::Present(100_000),
3901 fee_base_msat: 1_000,
3902 fee_proportional_millionths: 0,
3903 excess_data: Vec::new()
3905 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3906 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3907 short_channel_id: 11,
3910 cltv_expiry_delta: 0,
3911 htlc_minimum_msat: 0,
3912 htlc_maximum_msat: OptionalField::Present(100_000),
3914 fee_proportional_millionths: 0,
3915 excess_data: Vec::new()
3918 // Path via {node7, node2} is channels {12, 13, 5}.
3919 // We already limited them to 200 sats (they are used twice for 100 sats).
3920 // Nothing to do here.
3923 // Now, attempt to route 180 sats.
3924 // Our algorithm should provide us with these 2 paths.
3925 let route = get_route(&our_id, &payment_params, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3926 assert_eq!(route.paths.len(), 2);
3928 let mut total_value_transferred_msat = 0;
3929 let mut total_paid_msat = 0;
3930 for path in &route.paths {
3931 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3932 total_value_transferred_msat += path.last().unwrap().fee_msat;
3934 total_paid_msat += hop.fee_msat;
3937 // If we paid fee, this would be higher.
3938 assert_eq!(total_value_transferred_msat, 180_000);
3939 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3940 assert_eq!(total_fees_paid, 0);
3945 fn fees_on_mpp_route_test() {
3946 // This test makes sure that MPP algorithm properly takes into account
3947 // fees charged on the channels, by making the fees impactful:
3948 // if the fee is not properly accounted for, the behavior is different.
3949 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3950 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3951 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3952 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3954 // We need a route consisting of 2 paths:
3955 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3956 // We will route 200 sats, Each path will have 100 sats capacity.
3958 // This test is not particularly stable: e.g.,
3959 // there's a way to route via {node0, node2, node4}.
3960 // It works while pathfinding is deterministic, but can be broken otherwise.
3961 // It's fine to ignore this concern for now.
3963 // Disable other potential paths.
3964 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3965 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3966 short_channel_id: 2,
3969 cltv_expiry_delta: 0,
3970 htlc_minimum_msat: 0,
3971 htlc_maximum_msat: OptionalField::Present(100_000),
3973 fee_proportional_millionths: 0,
3974 excess_data: Vec::new()
3977 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3979 short_channel_id: 7,
3982 cltv_expiry_delta: 0,
3983 htlc_minimum_msat: 0,
3984 htlc_maximum_msat: OptionalField::Present(100_000),
3986 fee_proportional_millionths: 0,
3987 excess_data: Vec::new()
3990 // Path via {node0, node2} is channels {1, 3, 5}.
3991 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3992 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3993 short_channel_id: 1,
3996 cltv_expiry_delta: 0,
3997 htlc_minimum_msat: 0,
3998 htlc_maximum_msat: OptionalField::Present(100_000),
4000 fee_proportional_millionths: 0,
4001 excess_data: Vec::new()
4003 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4005 short_channel_id: 3,
4008 cltv_expiry_delta: 0,
4009 htlc_minimum_msat: 0,
4010 htlc_maximum_msat: OptionalField::Present(100_000),
4012 fee_proportional_millionths: 0,
4013 excess_data: Vec::new()
4016 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4017 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4018 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4019 short_channel_id: 5,
4022 cltv_expiry_delta: 0,
4023 htlc_minimum_msat: 0,
4024 htlc_maximum_msat: OptionalField::Present(100_000),
4026 fee_proportional_millionths: 0,
4027 excess_data: Vec::new()
4030 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4031 // All channels should be 100 sats capacity. But for the fee experiment,
4032 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4033 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4034 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4035 // so no matter how large are other channels,
4036 // the whole path will be limited by 100 sats with just these 2 conditions:
4037 // - channel 12 capacity is 250 sats
4038 // - fee for channel 6 is 150 sats
4039 // Let's test this by enforcing these 2 conditions and removing other limits.
4040 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4041 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4042 short_channel_id: 12,
4045 cltv_expiry_delta: 0,
4046 htlc_minimum_msat: 0,
4047 htlc_maximum_msat: OptionalField::Present(250_000),
4049 fee_proportional_millionths: 0,
4050 excess_data: Vec::new()
4052 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4054 short_channel_id: 13,
4057 cltv_expiry_delta: 0,
4058 htlc_minimum_msat: 0,
4059 htlc_maximum_msat: OptionalField::Absent,
4061 fee_proportional_millionths: 0,
4062 excess_data: Vec::new()
4065 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4066 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4067 short_channel_id: 6,
4070 cltv_expiry_delta: 0,
4071 htlc_minimum_msat: 0,
4072 htlc_maximum_msat: OptionalField::Absent,
4073 fee_base_msat: 150_000,
4074 fee_proportional_millionths: 0,
4075 excess_data: Vec::new()
4077 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4079 short_channel_id: 11,
4082 cltv_expiry_delta: 0,
4083 htlc_minimum_msat: 0,
4084 htlc_maximum_msat: OptionalField::Absent,
4086 fee_proportional_millionths: 0,
4087 excess_data: Vec::new()
4091 // Attempt to route more than available results in a failure.
4092 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4093 &our_id, &payment_params, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4094 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4095 } else { panic!(); }
4099 // Now, attempt to route 200 sats (exact amount we can route).
4100 let route = get_route(&our_id, &payment_params, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4101 assert_eq!(route.paths.len(), 2);
4103 let mut total_amount_paid_msat = 0;
4104 for path in &route.paths {
4105 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4106 total_amount_paid_msat += path.last().unwrap().fee_msat;
4108 assert_eq!(total_amount_paid_msat, 200_000);
4109 assert_eq!(route.get_total_fees(), 150_000);
4114 fn mpp_with_last_hops() {
4115 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4116 // via a single last-hop route hint, we'd fail to route if we first collected routes
4117 // totaling close but not quite enough to fund the full payment.
4119 // This was because we considered last-hop hints to have exactly the sought payment amount
4120 // instead of the amount we were trying to collect, needlessly limiting our path searching
4121 // at the very first hop.
4123 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4124 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4125 // to only have the remaining to-collect amount in available liquidity.
4127 // This bug appeared in production in some specific channel configurations.
4128 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4129 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4130 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4131 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4132 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4133 src_node_id: nodes[2],
4134 short_channel_id: 42,
4135 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4136 cltv_expiry_delta: 42,
4137 htlc_minimum_msat: None,
4138 htlc_maximum_msat: None,
4141 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4142 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4143 // would first use the no-fee route and then fail to find a path along the second route as
4144 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4145 // under 5% of our payment amount.
4146 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4147 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4148 short_channel_id: 1,
4151 cltv_expiry_delta: (5 << 4) | 5,
4152 htlc_minimum_msat: 0,
4153 htlc_maximum_msat: OptionalField::Present(99_000),
4154 fee_base_msat: u32::max_value(),
4155 fee_proportional_millionths: u32::max_value(),
4156 excess_data: Vec::new()
4158 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4160 short_channel_id: 2,
4163 cltv_expiry_delta: (5 << 4) | 3,
4164 htlc_minimum_msat: 0,
4165 htlc_maximum_msat: OptionalField::Present(99_000),
4166 fee_base_msat: u32::max_value(),
4167 fee_proportional_millionths: u32::max_value(),
4168 excess_data: Vec::new()
4170 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4172 short_channel_id: 4,
4175 cltv_expiry_delta: (4 << 4) | 1,
4176 htlc_minimum_msat: 0,
4177 htlc_maximum_msat: OptionalField::Absent,
4179 fee_proportional_millionths: 0,
4180 excess_data: Vec::new()
4182 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4184 short_channel_id: 13,
4186 flags: 0|2, // Channel disabled
4187 cltv_expiry_delta: (13 << 4) | 1,
4188 htlc_minimum_msat: 0,
4189 htlc_maximum_msat: OptionalField::Absent,
4191 fee_proportional_millionths: 2000000,
4192 excess_data: Vec::new()
4195 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4197 let route = get_route(&our_id, &payment_params, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4198 assert_eq!(route.paths.len(), 2);
4199 // Paths are somewhat randomly ordered, but:
4200 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4201 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4202 assert_eq!(route.paths[0][0].short_channel_id, 2);
4203 assert_eq!(route.paths[0][0].fee_msat, 1);
4204 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4205 assert_eq!(route.paths[1][0].short_channel_id, 1);
4206 assert_eq!(route.paths[1][0].fee_msat, 0);
4207 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4208 assert_eq!(route.get_total_fees(), 1);
4209 assert_eq!(route.get_total_amount(), 100_000);
4213 fn drop_lowest_channel_mpp_route_test() {
4214 // This test checks that low-capacity channel is dropped when after
4215 // path finding we realize that we found more capacity than we need.
4216 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4217 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4218 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4219 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4221 // We need a route consisting of 3 paths:
4222 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4224 // The first and the second paths should be sufficient, but the third should be
4225 // cheaper, so that we select it but drop later.
4227 // First, we set limits on these (previously unlimited) channels.
4228 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4230 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4231 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4232 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4233 short_channel_id: 1,
4236 cltv_expiry_delta: 0,
4237 htlc_minimum_msat: 0,
4238 htlc_maximum_msat: OptionalField::Present(100_000),
4240 fee_proportional_millionths: 0,
4241 excess_data: Vec::new()
4243 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4244 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4245 short_channel_id: 3,
4248 cltv_expiry_delta: 0,
4249 htlc_minimum_msat: 0,
4250 htlc_maximum_msat: OptionalField::Present(50_000),
4252 fee_proportional_millionths: 0,
4253 excess_data: Vec::new()
4256 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4257 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4259 short_channel_id: 12,
4262 cltv_expiry_delta: 0,
4263 htlc_minimum_msat: 0,
4264 htlc_maximum_msat: OptionalField::Present(60_000),
4266 fee_proportional_millionths: 0,
4267 excess_data: Vec::new()
4269 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4271 short_channel_id: 13,
4274 cltv_expiry_delta: 0,
4275 htlc_minimum_msat: 0,
4276 htlc_maximum_msat: OptionalField::Present(60_000),
4278 fee_proportional_millionths: 0,
4279 excess_data: Vec::new()
4282 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4283 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4285 short_channel_id: 2,
4288 cltv_expiry_delta: 0,
4289 htlc_minimum_msat: 0,
4290 htlc_maximum_msat: OptionalField::Present(20_000),
4292 fee_proportional_millionths: 0,
4293 excess_data: Vec::new()
4295 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4297 short_channel_id: 4,
4300 cltv_expiry_delta: 0,
4301 htlc_minimum_msat: 0,
4302 htlc_maximum_msat: OptionalField::Present(20_000),
4304 fee_proportional_millionths: 0,
4305 excess_data: Vec::new()
4309 // Attempt to route more than available results in a failure.
4310 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4311 &our_id, &payment_params, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4312 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4313 } else { panic!(); }
4317 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4318 // Our algorithm should provide us with these 3 paths.
4319 let route = get_route(&our_id, &payment_params, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4320 assert_eq!(route.paths.len(), 3);
4321 let mut total_amount_paid_msat = 0;
4322 for path in &route.paths {
4323 assert_eq!(path.len(), 2);
4324 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4325 total_amount_paid_msat += path.last().unwrap().fee_msat;
4327 assert_eq!(total_amount_paid_msat, 125_000);
4331 // Attempt to route without the last small cheap channel
4332 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4333 assert_eq!(route.paths.len(), 2);
4334 let mut total_amount_paid_msat = 0;
4335 for path in &route.paths {
4336 assert_eq!(path.len(), 2);
4337 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4338 total_amount_paid_msat += path.last().unwrap().fee_msat;
4340 assert_eq!(total_amount_paid_msat, 90_000);
4345 fn min_criteria_consistency() {
4346 // Test that we don't use an inconsistent metric between updating and walking nodes during
4347 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4348 // was updated with a different criterion from the heap sorting, resulting in loops in
4349 // calculated paths. We test for that specific case here.
4351 // We construct a network that looks like this:
4353 // node2 -1(3)2- node3
4357 // node1 -1(5)2- node4 -1(1)2- node6
4363 // We create a loop on the side of our real path - our destination is node 6, with a
4364 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4365 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4366 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4367 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4368 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4369 // "previous hop" being set to node 3, creating a loop in the path.
4370 let secp_ctx = Secp256k1::new();
4371 let logger = Arc::new(test_utils::TestLogger::new());
4372 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4373 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4374 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4375 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4376 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4378 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4379 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4381 short_channel_id: 6,
4384 cltv_expiry_delta: (6 << 4) | 0,
4385 htlc_minimum_msat: 0,
4386 htlc_maximum_msat: OptionalField::Absent,
4388 fee_proportional_millionths: 0,
4389 excess_data: Vec::new()
4391 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4393 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4394 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4396 short_channel_id: 5,
4399 cltv_expiry_delta: (5 << 4) | 0,
4400 htlc_minimum_msat: 0,
4401 htlc_maximum_msat: OptionalField::Absent,
4403 fee_proportional_millionths: 0,
4404 excess_data: Vec::new()
4406 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4408 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4409 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4410 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4411 short_channel_id: 4,
4414 cltv_expiry_delta: (4 << 4) | 0,
4415 htlc_minimum_msat: 0,
4416 htlc_maximum_msat: OptionalField::Absent,
4418 fee_proportional_millionths: 0,
4419 excess_data: Vec::new()
4421 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4423 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4424 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4425 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4426 short_channel_id: 3,
4429 cltv_expiry_delta: (3 << 4) | 0,
4430 htlc_minimum_msat: 0,
4431 htlc_maximum_msat: OptionalField::Absent,
4433 fee_proportional_millionths: 0,
4434 excess_data: Vec::new()
4436 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4438 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4439 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4440 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4441 short_channel_id: 2,
4444 cltv_expiry_delta: (2 << 4) | 0,
4445 htlc_minimum_msat: 0,
4446 htlc_maximum_msat: OptionalField::Absent,
4448 fee_proportional_millionths: 0,
4449 excess_data: Vec::new()
4452 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4453 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4454 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4455 short_channel_id: 1,
4458 cltv_expiry_delta: (1 << 4) | 0,
4459 htlc_minimum_msat: 100,
4460 htlc_maximum_msat: OptionalField::Absent,
4462 fee_proportional_millionths: 0,
4463 excess_data: Vec::new()
4465 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4468 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4469 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4470 assert_eq!(route.paths.len(), 1);
4471 assert_eq!(route.paths[0].len(), 3);
4473 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4474 assert_eq!(route.paths[0][0].short_channel_id, 6);
4475 assert_eq!(route.paths[0][0].fee_msat, 100);
4476 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4477 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4478 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4480 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4481 assert_eq!(route.paths[0][1].short_channel_id, 5);
4482 assert_eq!(route.paths[0][1].fee_msat, 0);
4483 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4484 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4485 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4487 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4488 assert_eq!(route.paths[0][2].short_channel_id, 1);
4489 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4490 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4491 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4492 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4498 fn exact_fee_liquidity_limit() {
4499 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4500 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4501 // we calculated fees on a higher value, resulting in us ignoring such paths.
4502 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4503 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4504 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4505 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4507 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4509 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4510 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4511 short_channel_id: 2,
4514 cltv_expiry_delta: 0,
4515 htlc_minimum_msat: 0,
4516 htlc_maximum_msat: OptionalField::Present(85_000),
4518 fee_proportional_millionths: 0,
4519 excess_data: Vec::new()
4522 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4523 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4524 short_channel_id: 12,
4527 cltv_expiry_delta: (4 << 4) | 1,
4528 htlc_minimum_msat: 0,
4529 htlc_maximum_msat: OptionalField::Present(270_000),
4531 fee_proportional_millionths: 1000000,
4532 excess_data: Vec::new()
4536 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4537 // 200% fee charged channel 13 in the 1-to-2 direction.
4538 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4539 assert_eq!(route.paths.len(), 1);
4540 assert_eq!(route.paths[0].len(), 2);
4542 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4543 assert_eq!(route.paths[0][0].short_channel_id, 12);
4544 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4545 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4546 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4547 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4549 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4550 assert_eq!(route.paths[0][1].short_channel_id, 13);
4551 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4552 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4553 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4554 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4559 fn htlc_max_reduction_below_min() {
4560 // Test that if, while walking the graph, we reduce the value being sent to meet an
4561 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4562 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4563 // resulting in us thinking there is no possible path, even if other paths exist.
4564 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4565 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4566 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4567 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4569 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4570 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4571 // then try to send 90_000.
4572 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4573 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4574 short_channel_id: 2,
4577 cltv_expiry_delta: 0,
4578 htlc_minimum_msat: 0,
4579 htlc_maximum_msat: OptionalField::Present(80_000),
4581 fee_proportional_millionths: 0,
4582 excess_data: Vec::new()
4584 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4585 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4586 short_channel_id: 4,
4589 cltv_expiry_delta: (4 << 4) | 1,
4590 htlc_minimum_msat: 90_000,
4591 htlc_maximum_msat: OptionalField::Absent,
4593 fee_proportional_millionths: 0,
4594 excess_data: Vec::new()
4598 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4599 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4600 // expensive) channels 12-13 path.
4601 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4602 assert_eq!(route.paths.len(), 1);
4603 assert_eq!(route.paths[0].len(), 2);
4605 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4606 assert_eq!(route.paths[0][0].short_channel_id, 12);
4607 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4608 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4609 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4610 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4612 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4613 assert_eq!(route.paths[0][1].short_channel_id, 13);
4614 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4615 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4616 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4617 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4622 fn multiple_direct_first_hops() {
4623 // Previously we'd only ever considered one first hop path per counterparty.
4624 // However, as we don't restrict users to one channel per peer, we really need to support
4625 // looking at all first hop paths.
4626 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4627 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4628 // route over multiple channels with the same first hop.
4629 let secp_ctx = Secp256k1::new();
4630 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4631 let logger = Arc::new(test_utils::TestLogger::new());
4632 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4633 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4634 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4637 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4638 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4639 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4640 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4641 assert_eq!(route.paths.len(), 1);
4642 assert_eq!(route.paths[0].len(), 1);
4644 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4645 assert_eq!(route.paths[0][0].short_channel_id, 3);
4646 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4649 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4650 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4651 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4652 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4653 assert_eq!(route.paths.len(), 2);
4654 assert_eq!(route.paths[0].len(), 1);
4655 assert_eq!(route.paths[1].len(), 1);
4657 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4658 assert_eq!(route.paths[0][0].short_channel_id, 3);
4659 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4661 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4662 assert_eq!(route.paths[1][0].short_channel_id, 2);
4663 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4668 fn prefers_shorter_route_with_higher_fees() {
4669 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4670 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4671 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4673 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4674 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4675 let route = get_route(
4676 &our_id, &payment_params, &network_graph, None, 100, 42,
4677 Arc::clone(&logger), &scorer
4679 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4681 assert_eq!(route.get_total_fees(), 100);
4682 assert_eq!(route.get_total_amount(), 100);
4683 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4685 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4686 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4687 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4688 let route = get_route(
4689 &our_id, &payment_params, &network_graph, None, 100, 42,
4690 Arc::clone(&logger), &scorer
4692 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4694 assert_eq!(route.get_total_fees(), 300);
4695 assert_eq!(route.get_total_amount(), 100);
4696 assert_eq!(path, vec![2, 4, 7, 10]);
4699 struct BadChannelScorer {
4700 short_channel_id: u64,
4704 impl Writeable for BadChannelScorer {
4705 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4707 impl Score for BadChannelScorer {
4708 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4709 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4712 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4713 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4716 struct BadNodeScorer {
4721 impl Writeable for BadNodeScorer {
4722 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4725 impl Score for BadNodeScorer {
4726 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4727 if *target == self.node_id { u64::max_value() } else { 0 }
4730 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4731 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4735 fn avoids_routing_through_bad_channels_and_nodes() {
4736 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4737 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4738 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4740 // A path to nodes[6] exists when no penalties are applied to any channel.
4741 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4742 let route = get_route(
4743 &our_id, &payment_params, &network_graph, None, 100, 42,
4744 Arc::clone(&logger), &scorer
4746 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4748 assert_eq!(route.get_total_fees(), 100);
4749 assert_eq!(route.get_total_amount(), 100);
4750 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4752 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4753 let scorer = BadChannelScorer { short_channel_id: 6 };
4754 let route = get_route(
4755 &our_id, &payment_params, &network_graph, None, 100, 42,
4756 Arc::clone(&logger), &scorer
4758 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4760 assert_eq!(route.get_total_fees(), 300);
4761 assert_eq!(route.get_total_amount(), 100);
4762 assert_eq!(path, vec![2, 4, 7, 10]);
4764 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4765 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4767 &our_id, &payment_params, &network_graph, None, 100, 42,
4768 Arc::clone(&logger), &scorer
4770 Err(LightningError { err, .. } ) => {
4771 assert_eq!(err, "Failed to find a path to the given destination");
4773 Ok(_) => panic!("Expected error"),
4778 fn total_fees_single_path() {
4782 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4783 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4784 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4787 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4788 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4789 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4792 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4793 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4794 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4797 payment_params: None,
4800 assert_eq!(route.get_total_fees(), 250);
4801 assert_eq!(route.get_total_amount(), 225);
4805 fn total_fees_multi_path() {
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
4820 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4821 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4822 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4825 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4826 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4827 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4830 payment_params: None,
4833 assert_eq!(route.get_total_fees(), 200);
4834 assert_eq!(route.get_total_amount(), 300);
4838 fn total_empty_route_no_panic() {
4839 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4840 // would both panic if the route was completely empty. We test to ensure they return 0
4841 // here, even though its somewhat nonsensical as a route.
4842 let route = Route { paths: Vec::new(), payment_params: None };
4844 assert_eq!(route.get_total_fees(), 0);
4845 assert_eq!(route.get_total_amount(), 0);
4849 fn limits_total_cltv_delta() {
4850 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4851 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4853 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4855 // Make sure that generally there is at least one route available
4856 let feasible_max_total_cltv_delta = 1008;
4857 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4858 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
4859 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
4860 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4861 assert_ne!(path.len(), 0);
4863 // But not if we exclude all paths on the basis of their accumulated CLTV delta
4864 let fail_max_total_cltv_delta = 23;
4865 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4866 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
4867 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer)
4869 Err(LightningError { err, .. } ) => {
4870 assert_eq!(err, "Failed to find a path to the given destination");
4872 Ok(_) => panic!("Expected error"),
4876 #[cfg(not(feature = "no-std"))]
4877 pub(super) fn random_init_seed() -> u64 {
4878 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4879 use core::hash::{BuildHasher, Hasher};
4880 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4881 println!("Using seed of {}", seed);
4884 #[cfg(not(feature = "no-std"))]
4885 use util::ser::Readable;
4888 #[cfg(not(feature = "no-std"))]
4889 fn generate_routes() {
4890 let mut d = match super::test_utils::get_route_file() {
4897 let graph = NetworkGraph::read(&mut d).unwrap();
4898 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4900 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4901 let mut seed = random_init_seed() as usize;
4902 let nodes = graph.read_only().nodes().clone();
4903 'load_endpoints: for _ in 0..10 {
4905 seed = seed.overflowing_mul(0xdeadbeef).0;
4906 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4907 seed = seed.overflowing_mul(0xdeadbeef).0;
4908 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4909 let payment_params = PaymentParameters::from_node_id(dst);
4910 let amt = seed as u64 % 200_000_000;
4911 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4912 continue 'load_endpoints;
4919 #[cfg(not(feature = "no-std"))]
4920 fn generate_routes_mpp() {
4921 let mut d = match super::test_utils::get_route_file() {
4928 let graph = NetworkGraph::read(&mut d).unwrap();
4929 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4931 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4932 let mut seed = random_init_seed() as usize;
4933 let nodes = graph.read_only().nodes().clone();
4934 'load_endpoints: for _ in 0..10 {
4936 seed = seed.overflowing_mul(0xdeadbeef).0;
4937 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4938 seed = seed.overflowing_mul(0xdeadbeef).0;
4939 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4940 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
4941 let amt = seed as u64 % 200_000_000;
4942 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4943 continue 'load_endpoints;
4950 #[cfg(all(test, not(feature = "no-std")))]
4951 pub(crate) mod test_utils {
4953 /// Tries to open a network graph file, or panics with a URL to fetch it.
4954 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4955 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4956 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4957 .or_else(|_| { // Fall back to guessing based on the binary location
4958 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4959 let mut path = std::env::current_exe().unwrap();
4960 path.pop(); // lightning-...
4962 path.pop(); // debug
4963 path.pop(); // target
4964 path.push("lightning");
4965 path.push("net_graph-2021-05-31.bin");
4966 eprintln!("{}", path.to_str().unwrap());
4969 .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");
4970 #[cfg(require_route_graph_test)]
4971 return Ok(res.unwrap());
4972 #[cfg(not(require_route_graph_test))]
4977 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4980 use bitcoin::hashes::Hash;
4981 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
4982 use chain::transaction::OutPoint;
4983 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
4984 use ln::features::{InitFeatures, InvoiceFeatures};
4985 use routing::scoring::Scorer;
4986 use util::logger::{Logger, Record};
4990 struct DummyLogger {}
4991 impl Logger for DummyLogger {
4992 fn log(&self, _record: &Record) {}
4995 struct ZeroPenaltyScorer;
4996 impl Score for ZeroPenaltyScorer {
4997 fn channel_penalty_msat(
4998 &self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId
5000 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5001 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5004 fn read_network_graph() -> NetworkGraph {
5005 let mut d = test_utils::get_route_file().unwrap();
5006 NetworkGraph::read(&mut d).unwrap()
5009 fn payer_pubkey() -> PublicKey {
5010 let secp_ctx = Secp256k1::new();
5011 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5015 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5017 channel_id: [0; 32],
5018 counterparty: ChannelCounterparty {
5019 features: InitFeatures::known(),
5021 unspendable_punishment_reserve: 0,
5022 forwarding_info: None,
5024 funding_txo: Some(OutPoint {
5025 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5027 short_channel_id: Some(1),
5028 channel_value_satoshis: 10_000_000,
5030 balance_msat: 10_000_000,
5031 outbound_capacity_msat: 10_000_000,
5032 inbound_capacity_msat: 0,
5033 unspendable_punishment_reserve: None,
5034 confirmations_required: None,
5035 force_close_spend_delay: None,
5037 is_funding_locked: true,
5044 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5045 let network_graph = read_network_graph();
5046 let scorer = ZeroPenaltyScorer;
5047 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5051 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5052 let network_graph = read_network_graph();
5053 let scorer = ZeroPenaltyScorer;
5054 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5058 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5059 let network_graph = read_network_graph();
5060 let scorer = Scorer::default();
5061 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5065 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5066 let network_graph = read_network_graph();
5067 let scorer = Scorer::default();
5068 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5071 fn generate_routes<S: Score>(
5072 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5074 let nodes = graph.read_only().nodes().clone();
5075 let payer = payer_pubkey();
5077 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5078 let mut routes = Vec::new();
5079 let mut route_endpoints = Vec::new();
5080 let mut seed: usize = 0xdeadbeef;
5081 'load_endpoints: for _ in 0..100 {
5084 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5086 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5087 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5088 let first_hop = first_hop(src);
5089 let amt = seed as u64 % 1_000_000;
5090 if let Ok(route) = get_route(&payer, ¶ms, &graph, Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer) {
5092 route_endpoints.push((first_hop, params, amt));
5093 continue 'load_endpoints;
5098 // ...and seed the scorer with success and failure data...
5099 for route in routes {
5100 let amount = route.get_total_amount();
5101 if amount < 250_000 {
5102 for path in route.paths {
5103 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5105 } else if amount > 750_000 {
5106 for path in route.paths {
5107 let short_channel_id = path[path.len() / 2].short_channel_id;
5108 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5113 // ...then benchmark finding paths between the nodes we learned.
5116 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5117 assert!(get_route(&payer, params, &graph, Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer).is_ok());