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 =
1076 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1077 let source = directed_channel.source();
1078 let target = directed_channel.target();
1079 if first_hops.is_none() || *source != our_node_id {
1080 if let Some(direction) = directed_channel.direction() {
1081 if direction.enabled {
1082 let candidate = CandidateRouteHop::PublicHop {
1083 info: directed_channel.with_update().unwrap(),
1084 short_channel_id: *chan_id,
1086 add_entry!(candidate, *source, *target, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat, $next_hops_cltv_delta);
1097 let mut payment_paths = Vec::<PaymentPath>::new();
1099 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1100 'paths_collection: loop {
1101 // For every new path, start from scratch, except
1102 // bookkept_channels_liquidity_available_msat, which will improve
1103 // the further iterations of path finding. Also don't erase first_hop_targets.
1106 hit_minimum_limit = false;
1108 // If first hop is a private channel and the only way to reach the payee, this is the only
1109 // place where it could be added.
1110 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1111 for details in first_channels {
1112 let candidate = CandidateRouteHop::FirstHop { details };
1113 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1114 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1118 // Add the payee as a target, so that the payee-to-payer
1119 // search algorithm knows what to start with.
1120 match network_nodes.get(&payee_node_id) {
1121 // The payee is not in our network graph, so nothing to add here.
1122 // There is still a chance of reaching them via last_hops though,
1123 // so don't yet fail the payment here.
1124 // If not, targets.pop() will not even let us enter the loop in step 2.
1127 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1132 // If a caller provided us with last hops, add them to routing targets. Since this happens
1133 // earlier than general path finding, they will be somewhat prioritized, although currently
1134 // it matters only if the fees are exactly the same.
1135 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1136 let first_hop_in_route = &(route.0)[0];
1137 let have_hop_src_in_graph =
1138 // Only add the hops in this route to our candidate set if either
1139 // we have a direct channel to the first hop or the first hop is
1140 // in the regular network graph.
1141 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1142 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1143 if have_hop_src_in_graph {
1144 // We start building the path from reverse, i.e., from payee
1145 // to the first RouteHintHop in the path.
1146 let hop_iter = route.0.iter().rev();
1147 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1148 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1149 let mut hop_used = true;
1150 let mut aggregate_next_hops_fee_msat: u64 = 0;
1151 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1152 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1153 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1155 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1156 let source = NodeId::from_pubkey(&hop.src_node_id);
1157 let target = NodeId::from_pubkey(&prev_hop_id);
1158 let candidate = network_channels
1159 .get(&hop.short_channel_id)
1160 .and_then(|channel| channel.as_directed_to(&target))
1161 .and_then(|channel| channel.with_update())
1162 .map(|info| CandidateRouteHop::PublicHop {
1164 short_channel_id: hop.short_channel_id,
1166 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1167 let capacity_msat = candidate.effective_capacity().as_msat();
1168 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1169 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1170 .unwrap_or_else(|| u64::max_value());
1172 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1173 .checked_add(hop.cltv_expiry_delta as u32)
1174 .unwrap_or_else(|| u32::max_value());
1176 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) {
1177 // If this hop was not used then there is no use checking the preceding hops
1178 // in the RouteHint. We can break by just searching for a direct channel between
1179 // last checked hop and first_hop_targets
1183 // Searching for a direct channel between last checked hop and first_hop_targets
1184 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1185 for details in first_channels {
1186 let candidate = CandidateRouteHop::FirstHop { details };
1187 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);
1195 // In the next values of the iterator, the aggregate fees already reflects
1196 // the sum of value sent from payer (final_value_msat) and routing fees
1197 // for the last node in the RouteHint. We need to just add the fees to
1198 // route through the current node so that the preceeding node (next iteration)
1200 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1201 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1202 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1204 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1205 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1206 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1207 .checked_add(hop_htlc_minimum_msat_inc);
1208 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1210 if idx == route.0.len() - 1 {
1211 // The last hop in this iterator is the first hop in
1212 // overall RouteHint.
1213 // If this hop connects to a node with which we have a direct channel,
1214 // ignore the network graph and, if the last hop was added, add our
1215 // direct channel to the candidate set.
1217 // Note that we *must* check if the last hop was added as `add_entry`
1218 // always assumes that the third argument is a node to which we have a
1220 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1221 for details in first_channels {
1222 let candidate = CandidateRouteHop::FirstHop { details };
1223 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);
1231 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1233 // At this point, targets are filled with the data from first and
1234 // last hops communicated by the caller, and the payment receiver.
1235 let mut found_new_path = false;
1238 // If this loop terminates due the exhaustion of targets, two situations are possible:
1239 // - not enough outgoing liquidity:
1240 // 0 < already_collected_value_msat < final_value_msat
1241 // - enough outgoing liquidity:
1242 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1243 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1244 // paths_collection will be stopped because found_new_path==false.
1245 // This is not necessarily a routing failure.
1246 '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() {
1248 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1249 // traversing the graph and arrange the path out of what we found.
1250 if node_id == our_node_id {
1251 let mut new_entry = dist.remove(&our_node_id).unwrap();
1252 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1255 let mut features_set = false;
1256 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1257 for details in first_channels {
1258 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1259 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1260 features_set = true;
1266 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1267 if let Some(node_info) = node.announcement_info.as_ref() {
1268 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1270 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1273 // We should be able to fill in features for everything except the last
1274 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1275 // should be able to extend it further as BOLT 11 does have feature
1276 // flags for the last hop node itself).
1277 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1281 // Means we succesfully traversed from the payer to the payee, now
1282 // save this path for the payment route. Also, update the liquidity
1283 // remaining on the used hops, so that we take them into account
1284 // while looking for more paths.
1285 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1289 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1290 Some(payment_hop) => payment_hop,
1291 // We can't arrive at None because, if we ever add an entry to targets,
1292 // we also fill in the entry in dist (see add_entry!).
1293 None => unreachable!(),
1295 // We "propagate" the fees one hop backward (topologically) here,
1296 // so that fees paid for a HTLC forwarding on the current channel are
1297 // associated with the previous channel (where they will be subtracted).
1298 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1299 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1301 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1302 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1304 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1305 ordered_hops.len(), value_contribution_msat, ordered_hops);
1307 let mut payment_path = PaymentPath {hops: ordered_hops};
1309 // We could have possibly constructed a slightly inconsistent path: since we reduce
1310 // value being transferred along the way, we could have violated htlc_minimum_msat
1311 // on some channels we already passed (assuming dest->source direction). Here, we
1312 // recompute the fees again, so that if that's the case, we match the currently
1313 // underpaid htlc_minimum_msat with fees.
1314 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1316 // Since a path allows to transfer as much value as
1317 // the smallest channel it has ("bottleneck"), we should recompute
1318 // the fees so sender HTLC don't overpay fees when traversing
1319 // larger channels than the bottleneck. This may happen because
1320 // when we were selecting those channels we were not aware how much value
1321 // this path will transfer, and the relative fee for them
1322 // might have been computed considering a larger value.
1323 // Remember that we used these channels so that we don't rely
1324 // on the same liquidity in future paths.
1325 let mut prevented_redundant_path_selection = false;
1326 for (payment_hop, _) in payment_path.hops.iter() {
1327 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1328 let mut spent_on_hop_msat = value_contribution_msat;
1329 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1330 spent_on_hop_msat += next_hops_fee_msat;
1331 if spent_on_hop_msat == *channel_liquidity_available_msat {
1332 // If this path used all of this channel's available liquidity, we know
1333 // this path will not be selected again in the next loop iteration.
1334 prevented_redundant_path_selection = true;
1336 *channel_liquidity_available_msat -= spent_on_hop_msat;
1338 if !prevented_redundant_path_selection {
1339 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1340 // we'll probably end up picking the same path again on the next iteration.
1341 // Decrease the available liquidity of a hop in the middle of the path.
1342 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1343 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1344 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1345 *victim_liquidity = 0;
1348 // Track the total amount all our collected paths allow to send so that we:
1349 // - know when to stop looking for more paths
1350 // - know which of the hops are useless considering how much more sats we need
1351 // (contributes_sufficient_value)
1352 already_collected_value_msat += value_contribution_msat;
1354 payment_paths.push(payment_path);
1355 found_new_path = true;
1356 break 'path_construction;
1359 // If we found a path back to the payee, we shouldn't try to process it again. This is
1360 // the equivalent of the `elem.was_processed` check in
1361 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1362 if node_id == payee_node_id { continue 'path_construction; }
1364 // Otherwise, since the current target node is not us,
1365 // keep "unrolling" the payment graph from payee to payer by
1366 // finding a way to reach the current target from the payer side.
1367 match network_nodes.get(&node_id) {
1370 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);
1376 // If we don't support MPP, no use trying to gather more value ever.
1377 break 'paths_collection;
1381 // Stop either when the recommended value is reached or if no new path was found in this
1383 // In the latter case, making another path finding attempt won't help,
1384 // because we deterministically terminated the search due to low liquidity.
1385 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1386 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1387 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1388 break 'paths_collection;
1389 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1390 // Further, if this was our first walk of the graph, and we weren't limited by an
1391 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1392 // limited by an htlc_minimum_msat value, find another path with a higher value,
1393 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1394 // still keeping a lower total fee than this path.
1395 if !hit_minimum_limit {
1396 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1397 break 'paths_collection;
1399 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1400 path_value_msat = recommended_value_msat;
1405 if payment_paths.len() == 0 {
1406 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1409 if already_collected_value_msat < final_value_msat {
1410 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1413 // Sort by total fees and take the best paths.
1414 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1415 if payment_paths.len() > 50 {
1416 payment_paths.truncate(50);
1419 // Draw multiple sufficient routes by randomly combining the selected paths.
1420 let mut drawn_routes = Vec::new();
1421 for i in 0..payment_paths.len() {
1422 let mut cur_route = Vec::<PaymentPath>::new();
1423 let mut aggregate_route_value_msat = 0;
1426 // TODO: real random shuffle
1427 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1428 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1431 for payment_path in cur_payment_paths {
1432 cur_route.push(payment_path.clone());
1433 aggregate_route_value_msat += payment_path.get_value_msat();
1434 if aggregate_route_value_msat > final_value_msat {
1435 // Last path likely overpaid. Substract it from the most expensive
1436 // (in terms of proportional fee) path in this route and recompute fees.
1437 // This might be not the most economically efficient way, but fewer paths
1438 // also makes routing more reliable.
1439 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1441 // First, drop some expensive low-value paths entirely if possible.
1442 // Sort by value so that we drop many really-low values first, since
1443 // fewer paths is better: the payment is less likely to fail.
1444 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1445 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1446 cur_route.sort_by_key(|path| path.get_value_msat());
1447 // We should make sure that at least 1 path left.
1448 let mut paths_left = cur_route.len();
1449 cur_route.retain(|path| {
1450 if paths_left == 1 {
1453 let mut keep = true;
1454 let path_value_msat = path.get_value_msat();
1455 if path_value_msat <= overpaid_value_msat {
1457 overpaid_value_msat -= path_value_msat;
1463 if overpaid_value_msat == 0 {
1467 assert!(cur_route.len() > 0);
1470 // Now, substract the overpaid value from the most-expensive path.
1471 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1472 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1473 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1474 let expensive_payment_path = cur_route.first_mut().unwrap();
1475 // We already dropped all the small channels above, meaning all the
1476 // remaining channels are larger than remaining overpaid_value_msat.
1477 // Thus, this can't be negative.
1478 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1479 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1483 drawn_routes.push(cur_route);
1487 // Select the best route by lowest total fee.
1488 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1489 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1490 for payment_path in drawn_routes.first().unwrap() {
1491 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1493 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)})?,
1494 node_features: node_features.clone(),
1495 short_channel_id: payment_hop.candidate.short_channel_id(),
1496 channel_features: payment_hop.candidate.features(),
1497 fee_msat: payment_hop.fee_msat,
1498 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1500 }).collect::<Vec<_>>();
1501 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1502 // applicable for the previous hop.
1503 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1504 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1506 selected_paths.push(path);
1509 if let Some(features) = &payment_params.features {
1510 for path in selected_paths.iter_mut() {
1511 if let Ok(route_hop) = path.last_mut().unwrap() {
1512 route_hop.node_features = features.to_context();
1518 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1519 payment_params: Some(payment_params.clone()),
1521 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1527 use routing::scoring::Score;
1528 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1529 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1530 use chain::transaction::OutPoint;
1531 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1532 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1533 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1534 use ln::channelmanager;
1535 use util::test_utils;
1536 use util::ser::Writeable;
1538 use util::ser::Writer;
1540 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1541 use bitcoin::hashes::Hash;
1542 use bitcoin::network::constants::Network;
1543 use bitcoin::blockdata::constants::genesis_block;
1544 use bitcoin::blockdata::script::Builder;
1545 use bitcoin::blockdata::opcodes;
1546 use bitcoin::blockdata::transaction::TxOut;
1550 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1551 use bitcoin::secp256k1::{Secp256k1, All};
1554 use sync::{self, Arc};
1556 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1557 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1558 channelmanager::ChannelDetails {
1559 channel_id: [0; 32],
1560 counterparty: channelmanager::ChannelCounterparty {
1563 unspendable_punishment_reserve: 0,
1564 forwarding_info: None,
1566 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1568 channel_value_satoshis: 0,
1571 outbound_capacity_msat,
1572 inbound_capacity_msat: 42,
1573 unspendable_punishment_reserve: None,
1574 confirmations_required: None,
1575 force_close_spend_delay: None,
1576 is_outbound: true, is_funding_locked: true,
1577 is_usable: true, is_public: true,
1581 // Using the same keys for LN and BTC ids
1583 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1584 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1586 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1587 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1589 let unsigned_announcement = UnsignedChannelAnnouncement {
1591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1595 bitcoin_key_1: node_id_1,
1596 bitcoin_key_2: node_id_2,
1597 excess_data: Vec::new(),
1600 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1601 let valid_announcement = ChannelAnnouncement {
1602 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1603 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1604 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1605 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1606 contents: unsigned_announcement.clone(),
1608 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1609 Ok(res) => assert!(res),
1615 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1616 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1618 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1619 let valid_channel_update = ChannelUpdate {
1620 signature: secp_ctx.sign(&msghash, node_privkey),
1621 contents: update.clone()
1624 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1625 Ok(res) => assert!(res),
1630 fn add_or_update_node(
1631 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1632 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1634 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1635 let unsigned_announcement = UnsignedNodeAnnouncement {
1641 addresses: Vec::new(),
1642 excess_address_data: Vec::new(),
1643 excess_data: Vec::new(),
1645 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1646 let valid_announcement = NodeAnnouncement {
1647 signature: secp_ctx.sign(&msghash, node_privkey),
1648 contents: unsigned_announcement.clone()
1651 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1657 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1658 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1659 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1662 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1664 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1665 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1667 (our_privkey, our_id, privkeys, pubkeys)
1670 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1671 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1672 // test for it later.
1673 let idx = (id - 1) * 2 + 1;
1675 vec![1 << (idx - 8*3), 0, 0, 0]
1676 } else if idx > 8*2 {
1677 vec![1 << (idx - 8*2), 0, 0]
1678 } else if idx > 8*1 {
1679 vec![1 << (idx - 8*1), 0]
1685 fn build_graph() -> (
1687 sync::Arc<NetworkGraph>,
1688 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1689 sync::Arc<test_utils::TestChainSource>,
1690 sync::Arc<test_utils::TestLogger>,
1692 let secp_ctx = Secp256k1::new();
1693 let logger = Arc::new(test_utils::TestLogger::new());
1694 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1695 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1696 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1697 // Build network from our_id to node6:
1699 // -1(1)2- node0 -1(3)2-
1701 // our_id -1(12)2- node7 -1(13)2--- node2
1703 // -1(2)2- node1 -1(4)2-
1706 // chan1 1-to-2: disabled
1707 // chan1 2-to-1: enabled, 0 fee
1709 // chan2 1-to-2: enabled, ignored fee
1710 // chan2 2-to-1: enabled, 0 fee
1712 // chan3 1-to-2: enabled, 0 fee
1713 // chan3 2-to-1: enabled, 100 msat fee
1715 // chan4 1-to-2: enabled, 100% fee
1716 // chan4 2-to-1: enabled, 0 fee
1718 // chan12 1-to-2: enabled, ignored fee
1719 // chan12 2-to-1: enabled, 0 fee
1721 // chan13 1-to-2: enabled, 200% fee
1722 // chan13 2-to-1: enabled, 0 fee
1725 // -1(5)2- node3 -1(8)2--
1729 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1731 // -1(7)2- node5 -1(10)2-
1733 // Channels 5, 8, 9 and 10 are private channels.
1735 // chan5 1-to-2: enabled, 100 msat fee
1736 // chan5 2-to-1: enabled, 0 fee
1738 // chan6 1-to-2: enabled, 0 fee
1739 // chan6 2-to-1: enabled, 0 fee
1741 // chan7 1-to-2: enabled, 100% fee
1742 // chan7 2-to-1: enabled, 0 fee
1744 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1745 // chan8 2-to-1: enabled, 0 fee
1747 // chan9 1-to-2: enabled, 1001 msat fee
1748 // chan9 2-to-1: enabled, 0 fee
1750 // chan10 1-to-2: enabled, 0 fee
1751 // chan10 2-to-1: enabled, 0 fee
1753 // chan11 1-to-2: enabled, 0 fee
1754 // chan11 2-to-1: enabled, 0 fee
1756 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1758 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1759 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1760 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1761 short_channel_id: 1,
1764 cltv_expiry_delta: 0,
1765 htlc_minimum_msat: 0,
1766 htlc_maximum_msat: OptionalField::Absent,
1768 fee_proportional_millionths: 0,
1769 excess_data: Vec::new()
1772 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1774 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1775 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1777 short_channel_id: 2,
1780 cltv_expiry_delta: (5 << 4) | 3,
1781 htlc_minimum_msat: 0,
1782 htlc_maximum_msat: OptionalField::Absent,
1783 fee_base_msat: u32::max_value(),
1784 fee_proportional_millionths: u32::max_value(),
1785 excess_data: Vec::new()
1787 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1788 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1789 short_channel_id: 2,
1792 cltv_expiry_delta: 0,
1793 htlc_minimum_msat: 0,
1794 htlc_maximum_msat: OptionalField::Absent,
1796 fee_proportional_millionths: 0,
1797 excess_data: Vec::new()
1800 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1802 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1803 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1804 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1805 short_channel_id: 12,
1808 cltv_expiry_delta: (5 << 4) | 3,
1809 htlc_minimum_msat: 0,
1810 htlc_maximum_msat: OptionalField::Absent,
1811 fee_base_msat: u32::max_value(),
1812 fee_proportional_millionths: u32::max_value(),
1813 excess_data: Vec::new()
1815 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1816 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1817 short_channel_id: 12,
1820 cltv_expiry_delta: 0,
1821 htlc_minimum_msat: 0,
1822 htlc_maximum_msat: OptionalField::Absent,
1824 fee_proportional_millionths: 0,
1825 excess_data: Vec::new()
1828 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1830 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1831 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1832 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1833 short_channel_id: 3,
1836 cltv_expiry_delta: (3 << 4) | 1,
1837 htlc_minimum_msat: 0,
1838 htlc_maximum_msat: OptionalField::Absent,
1840 fee_proportional_millionths: 0,
1841 excess_data: Vec::new()
1843 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1844 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1845 short_channel_id: 3,
1848 cltv_expiry_delta: (3 << 4) | 2,
1849 htlc_minimum_msat: 0,
1850 htlc_maximum_msat: OptionalField::Absent,
1852 fee_proportional_millionths: 0,
1853 excess_data: Vec::new()
1856 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1857 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1859 short_channel_id: 4,
1862 cltv_expiry_delta: (4 << 4) | 1,
1863 htlc_minimum_msat: 0,
1864 htlc_maximum_msat: OptionalField::Absent,
1866 fee_proportional_millionths: 1000000,
1867 excess_data: Vec::new()
1869 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1870 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1871 short_channel_id: 4,
1874 cltv_expiry_delta: (4 << 4) | 2,
1875 htlc_minimum_msat: 0,
1876 htlc_maximum_msat: OptionalField::Absent,
1878 fee_proportional_millionths: 0,
1879 excess_data: Vec::new()
1882 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1883 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1884 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1885 short_channel_id: 13,
1888 cltv_expiry_delta: (13 << 4) | 1,
1889 htlc_minimum_msat: 0,
1890 htlc_maximum_msat: OptionalField::Absent,
1892 fee_proportional_millionths: 2000000,
1893 excess_data: Vec::new()
1895 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1897 short_channel_id: 13,
1900 cltv_expiry_delta: (13 << 4) | 2,
1901 htlc_minimum_msat: 0,
1902 htlc_maximum_msat: OptionalField::Absent,
1904 fee_proportional_millionths: 0,
1905 excess_data: Vec::new()
1908 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1910 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1911 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1912 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1913 short_channel_id: 6,
1916 cltv_expiry_delta: (6 << 4) | 1,
1917 htlc_minimum_msat: 0,
1918 htlc_maximum_msat: OptionalField::Absent,
1920 fee_proportional_millionths: 0,
1921 excess_data: Vec::new()
1923 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1924 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1925 short_channel_id: 6,
1928 cltv_expiry_delta: (6 << 4) | 2,
1929 htlc_minimum_msat: 0,
1930 htlc_maximum_msat: OptionalField::Absent,
1932 fee_proportional_millionths: 0,
1933 excess_data: Vec::new(),
1936 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1937 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1938 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1939 short_channel_id: 11,
1942 cltv_expiry_delta: (11 << 4) | 1,
1943 htlc_minimum_msat: 0,
1944 htlc_maximum_msat: OptionalField::Absent,
1946 fee_proportional_millionths: 0,
1947 excess_data: Vec::new()
1949 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1950 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1951 short_channel_id: 11,
1954 cltv_expiry_delta: (11 << 4) | 2,
1955 htlc_minimum_msat: 0,
1956 htlc_maximum_msat: OptionalField::Absent,
1958 fee_proportional_millionths: 0,
1959 excess_data: Vec::new()
1962 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1964 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1966 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1967 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1968 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1969 short_channel_id: 7,
1972 cltv_expiry_delta: (7 << 4) | 1,
1973 htlc_minimum_msat: 0,
1974 htlc_maximum_msat: OptionalField::Absent,
1976 fee_proportional_millionths: 1000000,
1977 excess_data: Vec::new()
1979 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1981 short_channel_id: 7,
1984 cltv_expiry_delta: (7 << 4) | 2,
1985 htlc_minimum_msat: 0,
1986 htlc_maximum_msat: OptionalField::Absent,
1988 fee_proportional_millionths: 0,
1989 excess_data: Vec::new()
1992 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1994 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1998 fn simple_route_test() {
1999 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2000 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2001 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2002 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2004 // Simple route to 2 via 1
2006 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
2007 assert_eq!(err, "Cannot send a payment of 0 msat");
2008 } else { panic!(); }
2010 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2011 assert_eq!(route.paths[0].len(), 2);
2013 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2014 assert_eq!(route.paths[0][0].short_channel_id, 2);
2015 assert_eq!(route.paths[0][0].fee_msat, 100);
2016 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2017 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2018 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2020 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2021 assert_eq!(route.paths[0][1].short_channel_id, 4);
2022 assert_eq!(route.paths[0][1].fee_msat, 100);
2023 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2024 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2025 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2029 fn invalid_first_hop_test() {
2030 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2031 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2032 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2033 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2035 // Simple route to 2 via 1
2037 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2039 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) {
2040 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2041 } else { panic!(); }
2043 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2044 assert_eq!(route.paths[0].len(), 2);
2048 fn htlc_minimum_test() {
2049 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2050 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2051 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2052 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2054 // Simple route to 2 via 1
2056 // Disable other paths
2057 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2059 short_channel_id: 12,
2061 flags: 2, // to disable
2062 cltv_expiry_delta: 0,
2063 htlc_minimum_msat: 0,
2064 htlc_maximum_msat: OptionalField::Absent,
2066 fee_proportional_millionths: 0,
2067 excess_data: Vec::new()
2069 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2070 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2071 short_channel_id: 3,
2073 flags: 2, // to disable
2074 cltv_expiry_delta: 0,
2075 htlc_minimum_msat: 0,
2076 htlc_maximum_msat: OptionalField::Absent,
2078 fee_proportional_millionths: 0,
2079 excess_data: Vec::new()
2081 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2082 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2083 short_channel_id: 13,
2085 flags: 2, // to disable
2086 cltv_expiry_delta: 0,
2087 htlc_minimum_msat: 0,
2088 htlc_maximum_msat: OptionalField::Absent,
2090 fee_proportional_millionths: 0,
2091 excess_data: Vec::new()
2093 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2094 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2095 short_channel_id: 6,
2097 flags: 2, // to disable
2098 cltv_expiry_delta: 0,
2099 htlc_minimum_msat: 0,
2100 htlc_maximum_msat: OptionalField::Absent,
2102 fee_proportional_millionths: 0,
2103 excess_data: Vec::new()
2105 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2107 short_channel_id: 7,
2109 flags: 2, // to disable
2110 cltv_expiry_delta: 0,
2111 htlc_minimum_msat: 0,
2112 htlc_maximum_msat: OptionalField::Absent,
2114 fee_proportional_millionths: 0,
2115 excess_data: Vec::new()
2118 // Check against amount_to_transfer_over_msat.
2119 // Set minimal HTLC of 200_000_000 msat.
2120 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2121 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2122 short_channel_id: 2,
2125 cltv_expiry_delta: 0,
2126 htlc_minimum_msat: 200_000_000,
2127 htlc_maximum_msat: OptionalField::Absent,
2129 fee_proportional_millionths: 0,
2130 excess_data: Vec::new()
2133 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2135 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2137 short_channel_id: 4,
2140 cltv_expiry_delta: 0,
2141 htlc_minimum_msat: 0,
2142 htlc_maximum_msat: OptionalField::Present(199_999_999),
2144 fee_proportional_millionths: 0,
2145 excess_data: Vec::new()
2148 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2149 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) {
2150 assert_eq!(err, "Failed to find a path to the given destination");
2151 } else { panic!(); }
2153 // Lift the restriction on the first hop.
2154 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2155 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2156 short_channel_id: 2,
2159 cltv_expiry_delta: 0,
2160 htlc_minimum_msat: 0,
2161 htlc_maximum_msat: OptionalField::Absent,
2163 fee_proportional_millionths: 0,
2164 excess_data: Vec::new()
2167 // A payment above the minimum should pass
2168 let route = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2169 assert_eq!(route.paths[0].len(), 2);
2173 fn htlc_minimum_overpay_test() {
2174 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2175 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2176 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2177 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2179 // A route to node#2 via two paths.
2180 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2181 // Thus, they can't send 60 without overpaying.
2182 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2183 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2184 short_channel_id: 2,
2187 cltv_expiry_delta: 0,
2188 htlc_minimum_msat: 35_000,
2189 htlc_maximum_msat: OptionalField::Present(40_000),
2191 fee_proportional_millionths: 0,
2192 excess_data: Vec::new()
2194 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2195 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2196 short_channel_id: 12,
2199 cltv_expiry_delta: 0,
2200 htlc_minimum_msat: 35_000,
2201 htlc_maximum_msat: OptionalField::Present(40_000),
2203 fee_proportional_millionths: 0,
2204 excess_data: Vec::new()
2208 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210 short_channel_id: 13,
2213 cltv_expiry_delta: 0,
2214 htlc_minimum_msat: 0,
2215 htlc_maximum_msat: OptionalField::Absent,
2217 fee_proportional_millionths: 0,
2218 excess_data: Vec::new()
2220 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2222 short_channel_id: 4,
2225 cltv_expiry_delta: 0,
2226 htlc_minimum_msat: 0,
2227 htlc_maximum_msat: OptionalField::Absent,
2229 fee_proportional_millionths: 0,
2230 excess_data: Vec::new()
2233 // Disable other paths
2234 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2236 short_channel_id: 1,
2238 flags: 2, // to disable
2239 cltv_expiry_delta: 0,
2240 htlc_minimum_msat: 0,
2241 htlc_maximum_msat: OptionalField::Absent,
2243 fee_proportional_millionths: 0,
2244 excess_data: Vec::new()
2247 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2248 // Overpay fees to hit htlc_minimum_msat.
2249 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2250 // TODO: this could be better balanced to overpay 10k and not 15k.
2251 assert_eq!(overpaid_fees, 15_000);
2253 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2254 // while taking even more fee to match htlc_minimum_msat.
2255 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2256 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2257 short_channel_id: 12,
2260 cltv_expiry_delta: 0,
2261 htlc_minimum_msat: 65_000,
2262 htlc_maximum_msat: OptionalField::Present(80_000),
2264 fee_proportional_millionths: 0,
2265 excess_data: Vec::new()
2267 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2268 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2269 short_channel_id: 2,
2272 cltv_expiry_delta: 0,
2273 htlc_minimum_msat: 0,
2274 htlc_maximum_msat: OptionalField::Absent,
2276 fee_proportional_millionths: 0,
2277 excess_data: Vec::new()
2279 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2280 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2281 short_channel_id: 4,
2284 cltv_expiry_delta: 0,
2285 htlc_minimum_msat: 0,
2286 htlc_maximum_msat: OptionalField::Absent,
2288 fee_proportional_millionths: 100_000,
2289 excess_data: Vec::new()
2292 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2293 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2294 assert_eq!(route.paths.len(), 1);
2295 assert_eq!(route.paths[0][0].short_channel_id, 12);
2296 let fees = route.paths[0][0].fee_msat;
2297 assert_eq!(fees, 5_000);
2299 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2300 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2301 // the other channel.
2302 assert_eq!(route.paths.len(), 1);
2303 assert_eq!(route.paths[0][0].short_channel_id, 2);
2304 let fees = route.paths[0][0].fee_msat;
2305 assert_eq!(fees, 5_000);
2309 fn disable_channels_test() {
2310 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2311 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2312 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2313 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2315 // // Disable channels 4 and 12 by flags=2
2316 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2317 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2318 short_channel_id: 4,
2320 flags: 2, // to disable
2321 cltv_expiry_delta: 0,
2322 htlc_minimum_msat: 0,
2323 htlc_maximum_msat: OptionalField::Absent,
2325 fee_proportional_millionths: 0,
2326 excess_data: Vec::new()
2328 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2329 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2330 short_channel_id: 12,
2332 flags: 2, // to disable
2333 cltv_expiry_delta: 0,
2334 htlc_minimum_msat: 0,
2335 htlc_maximum_msat: OptionalField::Absent,
2337 fee_proportional_millionths: 0,
2338 excess_data: Vec::new()
2341 // If all the channels require some features we don't understand, route should fail
2342 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2343 assert_eq!(err, "Failed to find a path to the given destination");
2344 } else { panic!(); }
2346 // If we specify a channel to node7, that overrides our local channel view and that gets used
2347 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2348 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2349 assert_eq!(route.paths[0].len(), 2);
2351 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2352 assert_eq!(route.paths[0][0].short_channel_id, 42);
2353 assert_eq!(route.paths[0][0].fee_msat, 200);
2354 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2355 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2356 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2358 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2359 assert_eq!(route.paths[0][1].short_channel_id, 13);
2360 assert_eq!(route.paths[0][1].fee_msat, 100);
2361 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2362 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2363 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2367 fn disable_node_test() {
2368 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2369 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2370 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2371 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2373 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2374 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2375 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2376 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2377 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2379 // If all nodes require some features we don't understand, route should fail
2380 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2381 assert_eq!(err, "Failed to find a path to the given destination");
2382 } else { panic!(); }
2384 // If we specify a channel to node7, that overrides our local channel view and that gets used
2385 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2386 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2387 assert_eq!(route.paths[0].len(), 2);
2389 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2390 assert_eq!(route.paths[0][0].short_channel_id, 42);
2391 assert_eq!(route.paths[0][0].fee_msat, 200);
2392 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2393 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2394 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2396 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2397 assert_eq!(route.paths[0][1].short_channel_id, 13);
2398 assert_eq!(route.paths[0][1].fee_msat, 100);
2399 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2400 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2401 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2403 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2404 // naively) assume that the user checked the feature bits on the invoice, which override
2405 // the node_announcement.
2409 fn our_chans_test() {
2410 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2411 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2412 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2414 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2415 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2416 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2417 assert_eq!(route.paths[0].len(), 3);
2419 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2420 assert_eq!(route.paths[0][0].short_channel_id, 2);
2421 assert_eq!(route.paths[0][0].fee_msat, 200);
2422 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2423 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2424 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2426 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2427 assert_eq!(route.paths[0][1].short_channel_id, 4);
2428 assert_eq!(route.paths[0][1].fee_msat, 100);
2429 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2430 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2431 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2433 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2434 assert_eq!(route.paths[0][2].short_channel_id, 3);
2435 assert_eq!(route.paths[0][2].fee_msat, 100);
2436 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2437 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2438 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2440 // If we specify a channel to node7, that overrides our local channel view and that gets used
2441 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2442 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2443 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2444 assert_eq!(route.paths[0].len(), 2);
2446 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2447 assert_eq!(route.paths[0][0].short_channel_id, 42);
2448 assert_eq!(route.paths[0][0].fee_msat, 200);
2449 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2450 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2451 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2453 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2454 assert_eq!(route.paths[0][1].short_channel_id, 13);
2455 assert_eq!(route.paths[0][1].fee_msat, 100);
2456 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2457 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2458 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2461 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2462 let zero_fees = RoutingFees {
2464 proportional_millionths: 0,
2466 vec![RouteHint(vec![RouteHintHop {
2467 src_node_id: nodes[3],
2468 short_channel_id: 8,
2470 cltv_expiry_delta: (8 << 4) | 1,
2471 htlc_minimum_msat: None,
2472 htlc_maximum_msat: None,
2474 ]), RouteHint(vec![RouteHintHop {
2475 src_node_id: nodes[4],
2476 short_channel_id: 9,
2479 proportional_millionths: 0,
2481 cltv_expiry_delta: (9 << 4) | 1,
2482 htlc_minimum_msat: None,
2483 htlc_maximum_msat: None,
2484 }]), RouteHint(vec![RouteHintHop {
2485 src_node_id: nodes[5],
2486 short_channel_id: 10,
2488 cltv_expiry_delta: (10 << 4) | 1,
2489 htlc_minimum_msat: None,
2490 htlc_maximum_msat: None,
2494 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2495 let zero_fees = RoutingFees {
2497 proportional_millionths: 0,
2499 vec![RouteHint(vec![RouteHintHop {
2500 src_node_id: nodes[2],
2501 short_channel_id: 5,
2504 proportional_millionths: 0,
2506 cltv_expiry_delta: (5 << 4) | 1,
2507 htlc_minimum_msat: None,
2508 htlc_maximum_msat: None,
2510 src_node_id: nodes[3],
2511 short_channel_id: 8,
2513 cltv_expiry_delta: (8 << 4) | 1,
2514 htlc_minimum_msat: None,
2515 htlc_maximum_msat: None,
2517 ]), RouteHint(vec![RouteHintHop {
2518 src_node_id: nodes[4],
2519 short_channel_id: 9,
2522 proportional_millionths: 0,
2524 cltv_expiry_delta: (9 << 4) | 1,
2525 htlc_minimum_msat: None,
2526 htlc_maximum_msat: None,
2527 }]), RouteHint(vec![RouteHintHop {
2528 src_node_id: nodes[5],
2529 short_channel_id: 10,
2531 cltv_expiry_delta: (10 << 4) | 1,
2532 htlc_minimum_msat: None,
2533 htlc_maximum_msat: None,
2538 fn partial_route_hint_test() {
2539 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2540 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2541 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2543 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2544 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2545 // RouteHint may be partially used by the algo to build the best path.
2547 // First check that last hop can't have its source as the payee.
2548 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2549 src_node_id: nodes[6],
2550 short_channel_id: 8,
2553 proportional_millionths: 0,
2555 cltv_expiry_delta: (8 << 4) | 1,
2556 htlc_minimum_msat: None,
2557 htlc_maximum_msat: None,
2560 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2561 invalid_last_hops.push(invalid_last_hop);
2563 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2564 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2565 assert_eq!(err, "Route hint cannot have the payee as the source.");
2566 } else { panic!(); }
2569 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2570 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2571 assert_eq!(route.paths[0].len(), 5);
2573 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2574 assert_eq!(route.paths[0][0].short_channel_id, 2);
2575 assert_eq!(route.paths[0][0].fee_msat, 100);
2576 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2577 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2578 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2580 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2581 assert_eq!(route.paths[0][1].short_channel_id, 4);
2582 assert_eq!(route.paths[0][1].fee_msat, 0);
2583 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2584 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2585 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2587 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2588 assert_eq!(route.paths[0][2].short_channel_id, 6);
2589 assert_eq!(route.paths[0][2].fee_msat, 0);
2590 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2591 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2592 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2594 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2595 assert_eq!(route.paths[0][3].short_channel_id, 11);
2596 assert_eq!(route.paths[0][3].fee_msat, 0);
2597 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2598 // If we have a peer in the node map, we'll use their features here since we don't have
2599 // a way of figuring out their features from the invoice:
2600 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2601 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2603 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2604 assert_eq!(route.paths[0][4].short_channel_id, 8);
2605 assert_eq!(route.paths[0][4].fee_msat, 100);
2606 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2607 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2608 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2611 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2612 let zero_fees = RoutingFees {
2614 proportional_millionths: 0,
2616 vec![RouteHint(vec![RouteHintHop {
2617 src_node_id: nodes[3],
2618 short_channel_id: 8,
2620 cltv_expiry_delta: (8 << 4) | 1,
2621 htlc_minimum_msat: None,
2622 htlc_maximum_msat: None,
2623 }]), RouteHint(vec![
2625 ]), RouteHint(vec![RouteHintHop {
2626 src_node_id: nodes[5],
2627 short_channel_id: 10,
2629 cltv_expiry_delta: (10 << 4) | 1,
2630 htlc_minimum_msat: None,
2631 htlc_maximum_msat: None,
2636 fn ignores_empty_last_hops_test() {
2637 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2638 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2639 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2640 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2642 // Test handling of an empty RouteHint passed in Invoice.
2644 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2645 assert_eq!(route.paths[0].len(), 5);
2647 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2648 assert_eq!(route.paths[0][0].short_channel_id, 2);
2649 assert_eq!(route.paths[0][0].fee_msat, 100);
2650 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2651 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2652 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2654 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2655 assert_eq!(route.paths[0][1].short_channel_id, 4);
2656 assert_eq!(route.paths[0][1].fee_msat, 0);
2657 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2658 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2659 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2661 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2662 assert_eq!(route.paths[0][2].short_channel_id, 6);
2663 assert_eq!(route.paths[0][2].fee_msat, 0);
2664 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2665 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2666 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2668 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2669 assert_eq!(route.paths[0][3].short_channel_id, 11);
2670 assert_eq!(route.paths[0][3].fee_msat, 0);
2671 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2672 // If we have a peer in the node map, we'll use their features here since we don't have
2673 // a way of figuring out their features from the invoice:
2674 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2675 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2677 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2678 assert_eq!(route.paths[0][4].short_channel_id, 8);
2679 assert_eq!(route.paths[0][4].fee_msat, 100);
2680 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2681 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2682 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2685 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2686 let zero_fees = RoutingFees {
2688 proportional_millionths: 0,
2690 vec![RouteHint(vec![RouteHintHop {
2691 src_node_id: nodes[2],
2692 short_channel_id: 5,
2695 proportional_millionths: 0,
2697 cltv_expiry_delta: (5 << 4) | 1,
2698 htlc_minimum_msat: None,
2699 htlc_maximum_msat: None,
2701 src_node_id: nodes[3],
2702 short_channel_id: 8,
2704 cltv_expiry_delta: (8 << 4) | 1,
2705 htlc_minimum_msat: None,
2706 htlc_maximum_msat: None,
2707 }]), RouteHint(vec![RouteHintHop {
2708 src_node_id: nodes[5],
2709 short_channel_id: 10,
2711 cltv_expiry_delta: (10 << 4) | 1,
2712 htlc_minimum_msat: None,
2713 htlc_maximum_msat: None,
2718 fn multi_hint_last_hops_test() {
2719 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2720 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2721 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2722 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2723 // Test through channels 2, 3, 5, 8.
2724 // Test shows that multiple hop hints are considered.
2726 // Disabling channels 6 & 7 by flags=2
2727 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2728 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2729 short_channel_id: 6,
2731 flags: 2, // to disable
2732 cltv_expiry_delta: 0,
2733 htlc_minimum_msat: 0,
2734 htlc_maximum_msat: OptionalField::Absent,
2736 fee_proportional_millionths: 0,
2737 excess_data: Vec::new()
2739 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2740 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2741 short_channel_id: 7,
2743 flags: 2, // to disable
2744 cltv_expiry_delta: 0,
2745 htlc_minimum_msat: 0,
2746 htlc_maximum_msat: OptionalField::Absent,
2748 fee_proportional_millionths: 0,
2749 excess_data: Vec::new()
2752 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2753 assert_eq!(route.paths[0].len(), 4);
2755 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2756 assert_eq!(route.paths[0][0].short_channel_id, 2);
2757 assert_eq!(route.paths[0][0].fee_msat, 200);
2758 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2759 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2760 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2762 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2763 assert_eq!(route.paths[0][1].short_channel_id, 4);
2764 assert_eq!(route.paths[0][1].fee_msat, 100);
2765 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2766 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2767 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2769 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2770 assert_eq!(route.paths[0][2].short_channel_id, 5);
2771 assert_eq!(route.paths[0][2].fee_msat, 0);
2772 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2773 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2774 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2776 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2777 assert_eq!(route.paths[0][3].short_channel_id, 8);
2778 assert_eq!(route.paths[0][3].fee_msat, 100);
2779 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2780 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2781 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2784 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2785 let zero_fees = RoutingFees {
2787 proportional_millionths: 0,
2789 vec![RouteHint(vec![RouteHintHop {
2790 src_node_id: nodes[4],
2791 short_channel_id: 11,
2793 cltv_expiry_delta: (11 << 4) | 1,
2794 htlc_minimum_msat: None,
2795 htlc_maximum_msat: None,
2797 src_node_id: nodes[3],
2798 short_channel_id: 8,
2800 cltv_expiry_delta: (8 << 4) | 1,
2801 htlc_minimum_msat: None,
2802 htlc_maximum_msat: None,
2803 }]), RouteHint(vec![RouteHintHop {
2804 src_node_id: nodes[4],
2805 short_channel_id: 9,
2808 proportional_millionths: 0,
2810 cltv_expiry_delta: (9 << 4) | 1,
2811 htlc_minimum_msat: None,
2812 htlc_maximum_msat: None,
2813 }]), RouteHint(vec![RouteHintHop {
2814 src_node_id: nodes[5],
2815 short_channel_id: 10,
2817 cltv_expiry_delta: (10 << 4) | 1,
2818 htlc_minimum_msat: None,
2819 htlc_maximum_msat: None,
2824 fn last_hops_with_public_channel_test() {
2825 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2826 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2827 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2828 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2829 // This test shows that public routes can be present in the invoice
2830 // which would be handled in the same manner.
2832 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2833 assert_eq!(route.paths[0].len(), 5);
2835 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2836 assert_eq!(route.paths[0][0].short_channel_id, 2);
2837 assert_eq!(route.paths[0][0].fee_msat, 100);
2838 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2839 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2840 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2842 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2843 assert_eq!(route.paths[0][1].short_channel_id, 4);
2844 assert_eq!(route.paths[0][1].fee_msat, 0);
2845 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2846 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2847 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2849 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2850 assert_eq!(route.paths[0][2].short_channel_id, 6);
2851 assert_eq!(route.paths[0][2].fee_msat, 0);
2852 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2853 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2854 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2856 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2857 assert_eq!(route.paths[0][3].short_channel_id, 11);
2858 assert_eq!(route.paths[0][3].fee_msat, 0);
2859 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2860 // If we have a peer in the node map, we'll use their features here since we don't have
2861 // a way of figuring out their features from the invoice:
2862 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2863 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2865 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2866 assert_eq!(route.paths[0][4].short_channel_id, 8);
2867 assert_eq!(route.paths[0][4].fee_msat, 100);
2868 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2869 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2870 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2874 fn our_chans_last_hop_connect_test() {
2875 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2876 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2877 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2879 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2880 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2881 let mut last_hops = last_hops(&nodes);
2882 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2883 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2884 assert_eq!(route.paths[0].len(), 2);
2886 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2887 assert_eq!(route.paths[0][0].short_channel_id, 42);
2888 assert_eq!(route.paths[0][0].fee_msat, 0);
2889 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2890 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2891 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2893 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2894 assert_eq!(route.paths[0][1].short_channel_id, 8);
2895 assert_eq!(route.paths[0][1].fee_msat, 100);
2896 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2897 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2898 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2900 last_hops[0].0[0].fees.base_msat = 1000;
2902 // Revert to via 6 as the fee on 8 goes up
2903 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
2904 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2905 assert_eq!(route.paths[0].len(), 4);
2907 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2908 assert_eq!(route.paths[0][0].short_channel_id, 2);
2909 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2910 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2911 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2912 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2914 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2915 assert_eq!(route.paths[0][1].short_channel_id, 4);
2916 assert_eq!(route.paths[0][1].fee_msat, 100);
2917 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
2918 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2919 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2921 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2922 assert_eq!(route.paths[0][2].short_channel_id, 7);
2923 assert_eq!(route.paths[0][2].fee_msat, 0);
2924 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
2925 // If we have a peer in the node map, we'll use their features here since we don't have
2926 // a way of figuring out their features from the invoice:
2927 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2928 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2930 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2931 assert_eq!(route.paths[0][3].short_channel_id, 10);
2932 assert_eq!(route.paths[0][3].fee_msat, 100);
2933 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2934 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2935 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2937 // ...but still use 8 for larger payments as 6 has a variable feerate
2938 let route = get_route(&our_id, &payment_params, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2939 assert_eq!(route.paths[0].len(), 5);
2941 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2942 assert_eq!(route.paths[0][0].short_channel_id, 2);
2943 assert_eq!(route.paths[0][0].fee_msat, 3000);
2944 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2945 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2946 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2948 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2949 assert_eq!(route.paths[0][1].short_channel_id, 4);
2950 assert_eq!(route.paths[0][1].fee_msat, 0);
2951 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2952 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2953 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2955 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2956 assert_eq!(route.paths[0][2].short_channel_id, 6);
2957 assert_eq!(route.paths[0][2].fee_msat, 0);
2958 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2959 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2960 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2962 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2963 assert_eq!(route.paths[0][3].short_channel_id, 11);
2964 assert_eq!(route.paths[0][3].fee_msat, 1000);
2965 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2966 // If we have a peer in the node map, we'll use their features here since we don't have
2967 // a way of figuring out their features from the invoice:
2968 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2969 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2971 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2972 assert_eq!(route.paths[0][4].short_channel_id, 8);
2973 assert_eq!(route.paths[0][4].fee_msat, 2000);
2974 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2975 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2976 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2979 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> {
2980 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2981 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2982 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2984 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2985 let last_hops = RouteHint(vec![RouteHintHop {
2986 src_node_id: middle_node_id,
2987 short_channel_id: 8,
2990 proportional_millionths: last_hop_fee_prop,
2992 cltv_expiry_delta: (8 << 4) | 1,
2993 htlc_minimum_msat: None,
2994 htlc_maximum_msat: last_hop_htlc_max,
2996 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
2997 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2998 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2999 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)
3003 fn unannounced_path_test() {
3004 // We should be able to send a payment to a destination without any help of a routing graph
3005 // if we have a channel with a common counterparty that appears in the first and last hop
3007 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3009 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3010 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3011 assert_eq!(route.paths[0].len(), 2);
3013 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3014 assert_eq!(route.paths[0][0].short_channel_id, 42);
3015 assert_eq!(route.paths[0][0].fee_msat, 1001);
3016 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3017 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3018 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3020 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3021 assert_eq!(route.paths[0][1].short_channel_id, 8);
3022 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3023 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3024 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3025 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3029 fn overflow_unannounced_path_test_liquidity_underflow() {
3030 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3031 // the last-hop had a fee which overflowed a u64, we'd panic.
3032 // This was due to us adding the first-hop from us unconditionally, causing us to think
3033 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3034 // In this test, we previously hit a subtraction underflow due to having less available
3035 // liquidity at the last hop than 0.
3036 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());
3040 fn overflow_unannounced_path_test_feerate_overflow() {
3041 // This tests for the same case as above, except instead of hitting a subtraction
3042 // underflow, we hit a case where the fee charged at a hop overflowed.
3043 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());
3047 fn available_amount_while_routing_test() {
3048 // Tests whether we choose the correct available channel amount while routing.
3050 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3051 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3052 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3053 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3055 // We will use a simple single-path route from
3056 // our node to node2 via node0: channels {1, 3}.
3058 // First disable all other paths.
3059 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3061 short_channel_id: 2,
3064 cltv_expiry_delta: 0,
3065 htlc_minimum_msat: 0,
3066 htlc_maximum_msat: OptionalField::Present(100_000),
3068 fee_proportional_millionths: 0,
3069 excess_data: Vec::new()
3071 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3073 short_channel_id: 12,
3076 cltv_expiry_delta: 0,
3077 htlc_minimum_msat: 0,
3078 htlc_maximum_msat: OptionalField::Present(100_000),
3080 fee_proportional_millionths: 0,
3081 excess_data: Vec::new()
3084 // Make the first channel (#1) very permissive,
3085 // and we will be testing all limits on the second channel.
3086 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3087 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3088 short_channel_id: 1,
3091 cltv_expiry_delta: 0,
3092 htlc_minimum_msat: 0,
3093 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3095 fee_proportional_millionths: 0,
3096 excess_data: Vec::new()
3099 // First, let's see if routing works if we have absolutely no idea about the available amount.
3100 // In this case, it should be set to 250_000 sats.
3101 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3103 short_channel_id: 3,
3106 cltv_expiry_delta: 0,
3107 htlc_minimum_msat: 0,
3108 htlc_maximum_msat: OptionalField::Absent,
3110 fee_proportional_millionths: 0,
3111 excess_data: Vec::new()
3115 // Attempt to route more than available results in a failure.
3116 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3117 &our_id, &payment_params, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3118 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3119 } else { panic!(); }
3123 // Now, attempt to route an exact amount we have should be fine.
3124 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3125 assert_eq!(route.paths.len(), 1);
3126 let path = route.paths.last().unwrap();
3127 assert_eq!(path.len(), 2);
3128 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3129 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3132 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3133 // Disable channel #1 and use another first hop.
3134 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3135 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3136 short_channel_id: 1,
3139 cltv_expiry_delta: 0,
3140 htlc_minimum_msat: 0,
3141 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3143 fee_proportional_millionths: 0,
3144 excess_data: Vec::new()
3147 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3148 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3151 // Attempt to route more than available results in a failure.
3152 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3153 &our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3154 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3155 } else { panic!(); }
3159 // Now, attempt to route an exact amount we have should be fine.
3160 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();
3161 assert_eq!(route.paths.len(), 1);
3162 let path = route.paths.last().unwrap();
3163 assert_eq!(path.len(), 2);
3164 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3165 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3168 // Enable channel #1 back.
3169 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3170 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3171 short_channel_id: 1,
3174 cltv_expiry_delta: 0,
3175 htlc_minimum_msat: 0,
3176 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3178 fee_proportional_millionths: 0,
3179 excess_data: Vec::new()
3183 // Now let's see if routing works if we know only htlc_maximum_msat.
3184 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3186 short_channel_id: 3,
3189 cltv_expiry_delta: 0,
3190 htlc_minimum_msat: 0,
3191 htlc_maximum_msat: OptionalField::Present(15_000),
3193 fee_proportional_millionths: 0,
3194 excess_data: Vec::new()
3198 // Attempt to route more than available results in a failure.
3199 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3200 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3201 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3202 } else { panic!(); }
3206 // Now, attempt to route an exact amount we have should be fine.
3207 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3208 assert_eq!(route.paths.len(), 1);
3209 let path = route.paths.last().unwrap();
3210 assert_eq!(path.len(), 2);
3211 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3212 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3215 // Now let's see if routing works if we know only capacity from the UTXO.
3217 // We can't change UTXO capacity on the fly, so we'll disable
3218 // the existing channel and add another one with the capacity we need.
3219 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3220 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3221 short_channel_id: 3,
3224 cltv_expiry_delta: 0,
3225 htlc_minimum_msat: 0,
3226 htlc_maximum_msat: OptionalField::Absent,
3228 fee_proportional_millionths: 0,
3229 excess_data: Vec::new()
3232 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3233 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3234 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3235 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3236 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3238 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3239 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3241 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3242 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3244 short_channel_id: 333,
3247 cltv_expiry_delta: (3 << 4) | 1,
3248 htlc_minimum_msat: 0,
3249 htlc_maximum_msat: OptionalField::Absent,
3251 fee_proportional_millionths: 0,
3252 excess_data: Vec::new()
3254 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3256 short_channel_id: 333,
3259 cltv_expiry_delta: (3 << 4) | 2,
3260 htlc_minimum_msat: 0,
3261 htlc_maximum_msat: OptionalField::Absent,
3263 fee_proportional_millionths: 0,
3264 excess_data: Vec::new()
3268 // Attempt to route more than available results in a failure.
3269 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3270 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3271 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3272 } else { panic!(); }
3276 // Now, attempt to route an exact amount we have should be fine.
3277 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3278 assert_eq!(route.paths.len(), 1);
3279 let path = route.paths.last().unwrap();
3280 assert_eq!(path.len(), 2);
3281 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3282 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3285 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3286 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3288 short_channel_id: 333,
3291 cltv_expiry_delta: 0,
3292 htlc_minimum_msat: 0,
3293 htlc_maximum_msat: OptionalField::Present(10_000),
3295 fee_proportional_millionths: 0,
3296 excess_data: Vec::new()
3300 // Attempt to route more than available results in a failure.
3301 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3302 &our_id, &payment_params, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3303 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3304 } else { panic!(); }
3308 // Now, attempt to route an exact amount we have should be fine.
3309 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3310 assert_eq!(route.paths.len(), 1);
3311 let path = route.paths.last().unwrap();
3312 assert_eq!(path.len(), 2);
3313 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3314 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3319 fn available_liquidity_last_hop_test() {
3320 // Check that available liquidity properly limits the path even when only
3321 // one of the latter hops is limited.
3322 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3323 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3324 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3325 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3327 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3328 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3329 // Total capacity: 50 sats.
3331 // Disable other potential paths.
3332 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3334 short_channel_id: 2,
3337 cltv_expiry_delta: 0,
3338 htlc_minimum_msat: 0,
3339 htlc_maximum_msat: OptionalField::Present(100_000),
3341 fee_proportional_millionths: 0,
3342 excess_data: Vec::new()
3344 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3345 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3346 short_channel_id: 7,
3349 cltv_expiry_delta: 0,
3350 htlc_minimum_msat: 0,
3351 htlc_maximum_msat: OptionalField::Present(100_000),
3353 fee_proportional_millionths: 0,
3354 excess_data: Vec::new()
3359 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3360 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3361 short_channel_id: 12,
3364 cltv_expiry_delta: 0,
3365 htlc_minimum_msat: 0,
3366 htlc_maximum_msat: OptionalField::Present(100_000),
3368 fee_proportional_millionths: 0,
3369 excess_data: Vec::new()
3371 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3372 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3373 short_channel_id: 13,
3376 cltv_expiry_delta: 0,
3377 htlc_minimum_msat: 0,
3378 htlc_maximum_msat: OptionalField::Present(100_000),
3380 fee_proportional_millionths: 0,
3381 excess_data: Vec::new()
3384 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3386 short_channel_id: 6,
3389 cltv_expiry_delta: 0,
3390 htlc_minimum_msat: 0,
3391 htlc_maximum_msat: OptionalField::Present(50_000),
3393 fee_proportional_millionths: 0,
3394 excess_data: Vec::new()
3396 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3398 short_channel_id: 11,
3401 cltv_expiry_delta: 0,
3402 htlc_minimum_msat: 0,
3403 htlc_maximum_msat: OptionalField::Present(100_000),
3405 fee_proportional_millionths: 0,
3406 excess_data: Vec::new()
3409 // Attempt to route more than available results in a failure.
3410 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3411 &our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3412 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3413 } else { panic!(); }
3417 // Now, attempt to route 49 sats (just a bit below the capacity).
3418 let route = get_route(&our_id, &payment_params, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3419 assert_eq!(route.paths.len(), 1);
3420 let mut total_amount_paid_msat = 0;
3421 for path in &route.paths {
3422 assert_eq!(path.len(), 4);
3423 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3424 total_amount_paid_msat += path.last().unwrap().fee_msat;
3426 assert_eq!(total_amount_paid_msat, 49_000);
3430 // Attempt to route an exact amount is also fine
3431 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3432 assert_eq!(route.paths.len(), 1);
3433 let mut total_amount_paid_msat = 0;
3434 for path in &route.paths {
3435 assert_eq!(path.len(), 4);
3436 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3437 total_amount_paid_msat += path.last().unwrap().fee_msat;
3439 assert_eq!(total_amount_paid_msat, 50_000);
3444 fn ignore_fee_first_hop_test() {
3445 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3446 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3447 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3448 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3450 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3451 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3453 short_channel_id: 1,
3456 cltv_expiry_delta: 0,
3457 htlc_minimum_msat: 0,
3458 htlc_maximum_msat: OptionalField::Present(100_000),
3459 fee_base_msat: 1_000_000,
3460 fee_proportional_millionths: 0,
3461 excess_data: Vec::new()
3463 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3464 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3465 short_channel_id: 3,
3468 cltv_expiry_delta: 0,
3469 htlc_minimum_msat: 0,
3470 htlc_maximum_msat: OptionalField::Present(50_000),
3472 fee_proportional_millionths: 0,
3473 excess_data: Vec::new()
3477 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3478 assert_eq!(route.paths.len(), 1);
3479 let mut total_amount_paid_msat = 0;
3480 for path in &route.paths {
3481 assert_eq!(path.len(), 2);
3482 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3483 total_amount_paid_msat += path.last().unwrap().fee_msat;
3485 assert_eq!(total_amount_paid_msat, 50_000);
3490 fn simple_mpp_route_test() {
3491 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3492 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3493 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3494 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3496 // We need a route consisting of 3 paths:
3497 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3498 // To achieve this, the amount being transferred should be around
3499 // the total capacity of these 3 paths.
3501 // First, we set limits on these (previously unlimited) channels.
3502 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3504 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3505 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3506 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3507 short_channel_id: 1,
3510 cltv_expiry_delta: 0,
3511 htlc_minimum_msat: 0,
3512 htlc_maximum_msat: OptionalField::Present(100_000),
3514 fee_proportional_millionths: 0,
3515 excess_data: Vec::new()
3517 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3518 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3519 short_channel_id: 3,
3522 cltv_expiry_delta: 0,
3523 htlc_minimum_msat: 0,
3524 htlc_maximum_msat: OptionalField::Present(50_000),
3526 fee_proportional_millionths: 0,
3527 excess_data: Vec::new()
3530 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3531 // (total limit 60).
3532 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3533 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3534 short_channel_id: 12,
3537 cltv_expiry_delta: 0,
3538 htlc_minimum_msat: 0,
3539 htlc_maximum_msat: OptionalField::Present(60_000),
3541 fee_proportional_millionths: 0,
3542 excess_data: Vec::new()
3544 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3545 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3546 short_channel_id: 13,
3549 cltv_expiry_delta: 0,
3550 htlc_minimum_msat: 0,
3551 htlc_maximum_msat: OptionalField::Present(60_000),
3553 fee_proportional_millionths: 0,
3554 excess_data: Vec::new()
3557 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3558 // (total capacity 180 sats).
3559 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3560 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3561 short_channel_id: 2,
3564 cltv_expiry_delta: 0,
3565 htlc_minimum_msat: 0,
3566 htlc_maximum_msat: OptionalField::Present(200_000),
3568 fee_proportional_millionths: 0,
3569 excess_data: Vec::new()
3571 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3573 short_channel_id: 4,
3576 cltv_expiry_delta: 0,
3577 htlc_minimum_msat: 0,
3578 htlc_maximum_msat: OptionalField::Present(180_000),
3580 fee_proportional_millionths: 0,
3581 excess_data: Vec::new()
3585 // Attempt to route more than available results in a failure.
3586 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3587 &our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3588 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3589 } else { panic!(); }
3593 // Now, attempt to route 250 sats (just a bit below the capacity).
3594 // Our algorithm should provide us with these 3 paths.
3595 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3596 assert_eq!(route.paths.len(), 3);
3597 let mut total_amount_paid_msat = 0;
3598 for path in &route.paths {
3599 assert_eq!(path.len(), 2);
3600 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3601 total_amount_paid_msat += path.last().unwrap().fee_msat;
3603 assert_eq!(total_amount_paid_msat, 250_000);
3607 // Attempt to route an exact amount is also fine
3608 let route = get_route(&our_id, &payment_params, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3609 assert_eq!(route.paths.len(), 3);
3610 let mut total_amount_paid_msat = 0;
3611 for path in &route.paths {
3612 assert_eq!(path.len(), 2);
3613 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3614 total_amount_paid_msat += path.last().unwrap().fee_msat;
3616 assert_eq!(total_amount_paid_msat, 290_000);
3621 fn long_mpp_route_test() {
3622 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3623 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3624 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3625 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3627 // We need a route consisting of 3 paths:
3628 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3629 // Note that these paths overlap (channels 5, 12, 13).
3630 // We will route 300 sats.
3631 // Each path will have 100 sats capacity, those channels which
3632 // are used twice will have 200 sats capacity.
3634 // Disable other potential paths.
3635 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3636 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3637 short_channel_id: 2,
3640 cltv_expiry_delta: 0,
3641 htlc_minimum_msat: 0,
3642 htlc_maximum_msat: OptionalField::Present(100_000),
3644 fee_proportional_millionths: 0,
3645 excess_data: Vec::new()
3647 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3648 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3649 short_channel_id: 7,
3652 cltv_expiry_delta: 0,
3653 htlc_minimum_msat: 0,
3654 htlc_maximum_msat: OptionalField::Present(100_000),
3656 fee_proportional_millionths: 0,
3657 excess_data: Vec::new()
3660 // Path via {node0, node2} is channels {1, 3, 5}.
3661 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3662 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3663 short_channel_id: 1,
3666 cltv_expiry_delta: 0,
3667 htlc_minimum_msat: 0,
3668 htlc_maximum_msat: OptionalField::Present(100_000),
3670 fee_proportional_millionths: 0,
3671 excess_data: Vec::new()
3673 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3674 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3675 short_channel_id: 3,
3678 cltv_expiry_delta: 0,
3679 htlc_minimum_msat: 0,
3680 htlc_maximum_msat: OptionalField::Present(100_000),
3682 fee_proportional_millionths: 0,
3683 excess_data: Vec::new()
3686 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3687 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3688 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3689 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3690 short_channel_id: 5,
3693 cltv_expiry_delta: 0,
3694 htlc_minimum_msat: 0,
3695 htlc_maximum_msat: OptionalField::Present(200_000),
3697 fee_proportional_millionths: 0,
3698 excess_data: Vec::new()
3701 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3702 // Add 100 sats to the capacities of {12, 13}, because these channels
3703 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3704 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3705 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3706 short_channel_id: 12,
3709 cltv_expiry_delta: 0,
3710 htlc_minimum_msat: 0,
3711 htlc_maximum_msat: OptionalField::Present(200_000),
3713 fee_proportional_millionths: 0,
3714 excess_data: Vec::new()
3716 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3718 short_channel_id: 13,
3721 cltv_expiry_delta: 0,
3722 htlc_minimum_msat: 0,
3723 htlc_maximum_msat: OptionalField::Present(200_000),
3725 fee_proportional_millionths: 0,
3726 excess_data: Vec::new()
3729 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3731 short_channel_id: 6,
3734 cltv_expiry_delta: 0,
3735 htlc_minimum_msat: 0,
3736 htlc_maximum_msat: OptionalField::Present(100_000),
3738 fee_proportional_millionths: 0,
3739 excess_data: Vec::new()
3741 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3742 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3743 short_channel_id: 11,
3746 cltv_expiry_delta: 0,
3747 htlc_minimum_msat: 0,
3748 htlc_maximum_msat: OptionalField::Present(100_000),
3750 fee_proportional_millionths: 0,
3751 excess_data: Vec::new()
3754 // Path via {node7, node2} is channels {12, 13, 5}.
3755 // We already limited them to 200 sats (they are used twice for 100 sats).
3756 // Nothing to do here.
3759 // Attempt to route more than available results in a failure.
3760 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3761 &our_id, &payment_params, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3762 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3763 } else { panic!(); }
3767 // Now, attempt to route 300 sats (exact amount we can route).
3768 // Our algorithm should provide us with these 3 paths, 100 sats each.
3769 let route = get_route(&our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3770 assert_eq!(route.paths.len(), 3);
3772 let mut total_amount_paid_msat = 0;
3773 for path in &route.paths {
3774 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3775 total_amount_paid_msat += path.last().unwrap().fee_msat;
3777 assert_eq!(total_amount_paid_msat, 300_000);
3783 fn mpp_cheaper_route_test() {
3784 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3785 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3786 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3787 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3789 // This test checks that if we have two cheaper paths and one more expensive path,
3790 // so that liquidity-wise any 2 of 3 combination is sufficient,
3791 // two cheaper paths will be taken.
3792 // These paths have equal available liquidity.
3794 // We need a combination of 3 paths:
3795 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3796 // Note that these paths overlap (channels 5, 12, 13).
3797 // Each path will have 100 sats capacity, those channels which
3798 // are used twice will have 200 sats capacity.
3800 // Disable other potential paths.
3801 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3802 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3803 short_channel_id: 2,
3806 cltv_expiry_delta: 0,
3807 htlc_minimum_msat: 0,
3808 htlc_maximum_msat: OptionalField::Present(100_000),
3810 fee_proportional_millionths: 0,
3811 excess_data: Vec::new()
3813 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3814 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3815 short_channel_id: 7,
3818 cltv_expiry_delta: 0,
3819 htlc_minimum_msat: 0,
3820 htlc_maximum_msat: OptionalField::Present(100_000),
3822 fee_proportional_millionths: 0,
3823 excess_data: Vec::new()
3826 // Path via {node0, node2} is channels {1, 3, 5}.
3827 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3828 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3829 short_channel_id: 1,
3832 cltv_expiry_delta: 0,
3833 htlc_minimum_msat: 0,
3834 htlc_maximum_msat: OptionalField::Present(100_000),
3836 fee_proportional_millionths: 0,
3837 excess_data: Vec::new()
3839 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3840 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3841 short_channel_id: 3,
3844 cltv_expiry_delta: 0,
3845 htlc_minimum_msat: 0,
3846 htlc_maximum_msat: OptionalField::Present(100_000),
3848 fee_proportional_millionths: 0,
3849 excess_data: Vec::new()
3852 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3853 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3854 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3856 short_channel_id: 5,
3859 cltv_expiry_delta: 0,
3860 htlc_minimum_msat: 0,
3861 htlc_maximum_msat: OptionalField::Present(200_000),
3863 fee_proportional_millionths: 0,
3864 excess_data: Vec::new()
3867 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3868 // Add 100 sats to the capacities of {12, 13}, because these channels
3869 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3870 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3871 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3872 short_channel_id: 12,
3875 cltv_expiry_delta: 0,
3876 htlc_minimum_msat: 0,
3877 htlc_maximum_msat: OptionalField::Present(200_000),
3879 fee_proportional_millionths: 0,
3880 excess_data: Vec::new()
3882 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3884 short_channel_id: 13,
3887 cltv_expiry_delta: 0,
3888 htlc_minimum_msat: 0,
3889 htlc_maximum_msat: OptionalField::Present(200_000),
3891 fee_proportional_millionths: 0,
3892 excess_data: Vec::new()
3895 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3897 short_channel_id: 6,
3900 cltv_expiry_delta: 0,
3901 htlc_minimum_msat: 0,
3902 htlc_maximum_msat: OptionalField::Present(100_000),
3903 fee_base_msat: 1_000,
3904 fee_proportional_millionths: 0,
3905 excess_data: Vec::new()
3907 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3908 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3909 short_channel_id: 11,
3912 cltv_expiry_delta: 0,
3913 htlc_minimum_msat: 0,
3914 htlc_maximum_msat: OptionalField::Present(100_000),
3916 fee_proportional_millionths: 0,
3917 excess_data: Vec::new()
3920 // Path via {node7, node2} is channels {12, 13, 5}.
3921 // We already limited them to 200 sats (they are used twice for 100 sats).
3922 // Nothing to do here.
3925 // Now, attempt to route 180 sats.
3926 // Our algorithm should provide us with these 2 paths.
3927 let route = get_route(&our_id, &payment_params, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3928 assert_eq!(route.paths.len(), 2);
3930 let mut total_value_transferred_msat = 0;
3931 let mut total_paid_msat = 0;
3932 for path in &route.paths {
3933 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3934 total_value_transferred_msat += path.last().unwrap().fee_msat;
3936 total_paid_msat += hop.fee_msat;
3939 // If we paid fee, this would be higher.
3940 assert_eq!(total_value_transferred_msat, 180_000);
3941 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3942 assert_eq!(total_fees_paid, 0);
3947 fn fees_on_mpp_route_test() {
3948 // This test makes sure that MPP algorithm properly takes into account
3949 // fees charged on the channels, by making the fees impactful:
3950 // if the fee is not properly accounted for, the behavior is different.
3951 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3952 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3953 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3954 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3956 // We need a route consisting of 2 paths:
3957 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3958 // We will route 200 sats, Each path will have 100 sats capacity.
3960 // This test is not particularly stable: e.g.,
3961 // there's a way to route via {node0, node2, node4}.
3962 // It works while pathfinding is deterministic, but can be broken otherwise.
3963 // It's fine to ignore this concern for now.
3965 // Disable other potential paths.
3966 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3968 short_channel_id: 2,
3971 cltv_expiry_delta: 0,
3972 htlc_minimum_msat: 0,
3973 htlc_maximum_msat: OptionalField::Present(100_000),
3975 fee_proportional_millionths: 0,
3976 excess_data: Vec::new()
3979 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3980 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3981 short_channel_id: 7,
3984 cltv_expiry_delta: 0,
3985 htlc_minimum_msat: 0,
3986 htlc_maximum_msat: OptionalField::Present(100_000),
3988 fee_proportional_millionths: 0,
3989 excess_data: Vec::new()
3992 // Path via {node0, node2} is channels {1, 3, 5}.
3993 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3995 short_channel_id: 1,
3998 cltv_expiry_delta: 0,
3999 htlc_minimum_msat: 0,
4000 htlc_maximum_msat: OptionalField::Present(100_000),
4002 fee_proportional_millionths: 0,
4003 excess_data: Vec::new()
4005 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4007 short_channel_id: 3,
4010 cltv_expiry_delta: 0,
4011 htlc_minimum_msat: 0,
4012 htlc_maximum_msat: OptionalField::Present(100_000),
4014 fee_proportional_millionths: 0,
4015 excess_data: Vec::new()
4018 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4019 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4021 short_channel_id: 5,
4024 cltv_expiry_delta: 0,
4025 htlc_minimum_msat: 0,
4026 htlc_maximum_msat: OptionalField::Present(100_000),
4028 fee_proportional_millionths: 0,
4029 excess_data: Vec::new()
4032 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4033 // All channels should be 100 sats capacity. But for the fee experiment,
4034 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4035 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4036 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4037 // so no matter how large are other channels,
4038 // the whole path will be limited by 100 sats with just these 2 conditions:
4039 // - channel 12 capacity is 250 sats
4040 // - fee for channel 6 is 150 sats
4041 // Let's test this by enforcing these 2 conditions and removing other limits.
4042 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4043 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4044 short_channel_id: 12,
4047 cltv_expiry_delta: 0,
4048 htlc_minimum_msat: 0,
4049 htlc_maximum_msat: OptionalField::Present(250_000),
4051 fee_proportional_millionths: 0,
4052 excess_data: Vec::new()
4054 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4056 short_channel_id: 13,
4059 cltv_expiry_delta: 0,
4060 htlc_minimum_msat: 0,
4061 htlc_maximum_msat: OptionalField::Absent,
4063 fee_proportional_millionths: 0,
4064 excess_data: Vec::new()
4067 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4068 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4069 short_channel_id: 6,
4072 cltv_expiry_delta: 0,
4073 htlc_minimum_msat: 0,
4074 htlc_maximum_msat: OptionalField::Absent,
4075 fee_base_msat: 150_000,
4076 fee_proportional_millionths: 0,
4077 excess_data: Vec::new()
4079 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4080 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4081 short_channel_id: 11,
4084 cltv_expiry_delta: 0,
4085 htlc_minimum_msat: 0,
4086 htlc_maximum_msat: OptionalField::Absent,
4088 fee_proportional_millionths: 0,
4089 excess_data: Vec::new()
4093 // Attempt to route more than available results in a failure.
4094 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4095 &our_id, &payment_params, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4096 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4097 } else { panic!(); }
4101 // Now, attempt to route 200 sats (exact amount we can route).
4102 let route = get_route(&our_id, &payment_params, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4103 assert_eq!(route.paths.len(), 2);
4105 let mut total_amount_paid_msat = 0;
4106 for path in &route.paths {
4107 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4108 total_amount_paid_msat += path.last().unwrap().fee_msat;
4110 assert_eq!(total_amount_paid_msat, 200_000);
4111 assert_eq!(route.get_total_fees(), 150_000);
4116 fn mpp_with_last_hops() {
4117 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4118 // via a single last-hop route hint, we'd fail to route if we first collected routes
4119 // totaling close but not quite enough to fund the full payment.
4121 // This was because we considered last-hop hints to have exactly the sought payment amount
4122 // instead of the amount we were trying to collect, needlessly limiting our path searching
4123 // at the very first hop.
4125 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4126 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4127 // to only have the remaining to-collect amount in available liquidity.
4129 // This bug appeared in production in some specific channel configurations.
4130 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4131 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4132 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4133 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4134 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4135 src_node_id: nodes[2],
4136 short_channel_id: 42,
4137 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4138 cltv_expiry_delta: 42,
4139 htlc_minimum_msat: None,
4140 htlc_maximum_msat: None,
4143 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4144 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4145 // would first use the no-fee route and then fail to find a path along the second route as
4146 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4147 // under 5% of our payment amount.
4148 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4150 short_channel_id: 1,
4153 cltv_expiry_delta: (5 << 4) | 5,
4154 htlc_minimum_msat: 0,
4155 htlc_maximum_msat: OptionalField::Present(99_000),
4156 fee_base_msat: u32::max_value(),
4157 fee_proportional_millionths: u32::max_value(),
4158 excess_data: Vec::new()
4160 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4161 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4162 short_channel_id: 2,
4165 cltv_expiry_delta: (5 << 4) | 3,
4166 htlc_minimum_msat: 0,
4167 htlc_maximum_msat: OptionalField::Present(99_000),
4168 fee_base_msat: u32::max_value(),
4169 fee_proportional_millionths: u32::max_value(),
4170 excess_data: Vec::new()
4172 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4174 short_channel_id: 4,
4177 cltv_expiry_delta: (4 << 4) | 1,
4178 htlc_minimum_msat: 0,
4179 htlc_maximum_msat: OptionalField::Absent,
4181 fee_proportional_millionths: 0,
4182 excess_data: Vec::new()
4184 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4186 short_channel_id: 13,
4188 flags: 0|2, // Channel disabled
4189 cltv_expiry_delta: (13 << 4) | 1,
4190 htlc_minimum_msat: 0,
4191 htlc_maximum_msat: OptionalField::Absent,
4193 fee_proportional_millionths: 2000000,
4194 excess_data: Vec::new()
4197 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4199 let route = get_route(&our_id, &payment_params, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4200 assert_eq!(route.paths.len(), 2);
4201 // Paths are somewhat randomly ordered, but:
4202 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4203 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4204 assert_eq!(route.paths[0][0].short_channel_id, 2);
4205 assert_eq!(route.paths[0][0].fee_msat, 1);
4206 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4207 assert_eq!(route.paths[1][0].short_channel_id, 1);
4208 assert_eq!(route.paths[1][0].fee_msat, 0);
4209 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4210 assert_eq!(route.get_total_fees(), 1);
4211 assert_eq!(route.get_total_amount(), 100_000);
4215 fn drop_lowest_channel_mpp_route_test() {
4216 // This test checks that low-capacity channel is dropped when after
4217 // path finding we realize that we found more capacity than we need.
4218 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4219 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4220 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4221 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4223 // We need a route consisting of 3 paths:
4224 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4226 // The first and the second paths should be sufficient, but the third should be
4227 // cheaper, so that we select it but drop later.
4229 // First, we set limits on these (previously unlimited) channels.
4230 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4232 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4233 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4235 short_channel_id: 1,
4238 cltv_expiry_delta: 0,
4239 htlc_minimum_msat: 0,
4240 htlc_maximum_msat: OptionalField::Present(100_000),
4242 fee_proportional_millionths: 0,
4243 excess_data: Vec::new()
4245 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4247 short_channel_id: 3,
4250 cltv_expiry_delta: 0,
4251 htlc_minimum_msat: 0,
4252 htlc_maximum_msat: OptionalField::Present(50_000),
4254 fee_proportional_millionths: 0,
4255 excess_data: Vec::new()
4258 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4259 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4261 short_channel_id: 12,
4264 cltv_expiry_delta: 0,
4265 htlc_minimum_msat: 0,
4266 htlc_maximum_msat: OptionalField::Present(60_000),
4268 fee_proportional_millionths: 0,
4269 excess_data: Vec::new()
4271 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4273 short_channel_id: 13,
4276 cltv_expiry_delta: 0,
4277 htlc_minimum_msat: 0,
4278 htlc_maximum_msat: OptionalField::Present(60_000),
4280 fee_proportional_millionths: 0,
4281 excess_data: Vec::new()
4284 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4285 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4287 short_channel_id: 2,
4290 cltv_expiry_delta: 0,
4291 htlc_minimum_msat: 0,
4292 htlc_maximum_msat: OptionalField::Present(20_000),
4294 fee_proportional_millionths: 0,
4295 excess_data: Vec::new()
4297 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4298 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4299 short_channel_id: 4,
4302 cltv_expiry_delta: 0,
4303 htlc_minimum_msat: 0,
4304 htlc_maximum_msat: OptionalField::Present(20_000),
4306 fee_proportional_millionths: 0,
4307 excess_data: Vec::new()
4311 // Attempt to route more than available results in a failure.
4312 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4313 &our_id, &payment_params, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4314 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4315 } else { panic!(); }
4319 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4320 // Our algorithm should provide us with these 3 paths.
4321 let route = get_route(&our_id, &payment_params, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4322 assert_eq!(route.paths.len(), 3);
4323 let mut total_amount_paid_msat = 0;
4324 for path in &route.paths {
4325 assert_eq!(path.len(), 2);
4326 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4327 total_amount_paid_msat += path.last().unwrap().fee_msat;
4329 assert_eq!(total_amount_paid_msat, 125_000);
4333 // Attempt to route without the last small cheap channel
4334 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4335 assert_eq!(route.paths.len(), 2);
4336 let mut total_amount_paid_msat = 0;
4337 for path in &route.paths {
4338 assert_eq!(path.len(), 2);
4339 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4340 total_amount_paid_msat += path.last().unwrap().fee_msat;
4342 assert_eq!(total_amount_paid_msat, 90_000);
4347 fn min_criteria_consistency() {
4348 // Test that we don't use an inconsistent metric between updating and walking nodes during
4349 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4350 // was updated with a different criterion from the heap sorting, resulting in loops in
4351 // calculated paths. We test for that specific case here.
4353 // We construct a network that looks like this:
4355 // node2 -1(3)2- node3
4359 // node1 -1(5)2- node4 -1(1)2- node6
4365 // We create a loop on the side of our real path - our destination is node 6, with a
4366 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4367 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4368 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4369 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4370 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4371 // "previous hop" being set to node 3, creating a loop in the path.
4372 let secp_ctx = Secp256k1::new();
4373 let logger = Arc::new(test_utils::TestLogger::new());
4374 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4375 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4376 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4377 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4378 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4380 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4381 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4382 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4383 short_channel_id: 6,
4386 cltv_expiry_delta: (6 << 4) | 0,
4387 htlc_minimum_msat: 0,
4388 htlc_maximum_msat: OptionalField::Absent,
4390 fee_proportional_millionths: 0,
4391 excess_data: Vec::new()
4393 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4395 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4396 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4397 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4398 short_channel_id: 5,
4401 cltv_expiry_delta: (5 << 4) | 0,
4402 htlc_minimum_msat: 0,
4403 htlc_maximum_msat: OptionalField::Absent,
4405 fee_proportional_millionths: 0,
4406 excess_data: Vec::new()
4408 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4410 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4411 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4412 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4413 short_channel_id: 4,
4416 cltv_expiry_delta: (4 << 4) | 0,
4417 htlc_minimum_msat: 0,
4418 htlc_maximum_msat: OptionalField::Absent,
4420 fee_proportional_millionths: 0,
4421 excess_data: Vec::new()
4423 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4425 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4426 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4428 short_channel_id: 3,
4431 cltv_expiry_delta: (3 << 4) | 0,
4432 htlc_minimum_msat: 0,
4433 htlc_maximum_msat: OptionalField::Absent,
4435 fee_proportional_millionths: 0,
4436 excess_data: Vec::new()
4438 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4440 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4441 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4442 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4443 short_channel_id: 2,
4446 cltv_expiry_delta: (2 << 4) | 0,
4447 htlc_minimum_msat: 0,
4448 htlc_maximum_msat: OptionalField::Absent,
4450 fee_proportional_millionths: 0,
4451 excess_data: Vec::new()
4454 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4455 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4456 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4457 short_channel_id: 1,
4460 cltv_expiry_delta: (1 << 4) | 0,
4461 htlc_minimum_msat: 100,
4462 htlc_maximum_msat: OptionalField::Absent,
4464 fee_proportional_millionths: 0,
4465 excess_data: Vec::new()
4467 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4470 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4471 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4472 assert_eq!(route.paths.len(), 1);
4473 assert_eq!(route.paths[0].len(), 3);
4475 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4476 assert_eq!(route.paths[0][0].short_channel_id, 6);
4477 assert_eq!(route.paths[0][0].fee_msat, 100);
4478 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4479 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4480 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4482 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4483 assert_eq!(route.paths[0][1].short_channel_id, 5);
4484 assert_eq!(route.paths[0][1].fee_msat, 0);
4485 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4486 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4487 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4489 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4490 assert_eq!(route.paths[0][2].short_channel_id, 1);
4491 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4492 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4493 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4494 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4500 fn exact_fee_liquidity_limit() {
4501 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4502 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4503 // we calculated fees on a higher value, resulting in us ignoring such paths.
4504 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4505 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4506 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4507 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4509 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4511 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4512 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4513 short_channel_id: 2,
4516 cltv_expiry_delta: 0,
4517 htlc_minimum_msat: 0,
4518 htlc_maximum_msat: OptionalField::Present(85_000),
4520 fee_proportional_millionths: 0,
4521 excess_data: Vec::new()
4524 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4526 short_channel_id: 12,
4529 cltv_expiry_delta: (4 << 4) | 1,
4530 htlc_minimum_msat: 0,
4531 htlc_maximum_msat: OptionalField::Present(270_000),
4533 fee_proportional_millionths: 1000000,
4534 excess_data: Vec::new()
4538 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4539 // 200% fee charged channel 13 in the 1-to-2 direction.
4540 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4541 assert_eq!(route.paths.len(), 1);
4542 assert_eq!(route.paths[0].len(), 2);
4544 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4545 assert_eq!(route.paths[0][0].short_channel_id, 12);
4546 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4547 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4548 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4549 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4551 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4552 assert_eq!(route.paths[0][1].short_channel_id, 13);
4553 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4554 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4555 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4556 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4561 fn htlc_max_reduction_below_min() {
4562 // Test that if, while walking the graph, we reduce the value being sent to meet an
4563 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4564 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4565 // resulting in us thinking there is no possible path, even if other paths exist.
4566 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4567 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4568 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4569 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4571 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4572 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4573 // then try to send 90_000.
4574 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4576 short_channel_id: 2,
4579 cltv_expiry_delta: 0,
4580 htlc_minimum_msat: 0,
4581 htlc_maximum_msat: OptionalField::Present(80_000),
4583 fee_proportional_millionths: 0,
4584 excess_data: Vec::new()
4586 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4588 short_channel_id: 4,
4591 cltv_expiry_delta: (4 << 4) | 1,
4592 htlc_minimum_msat: 90_000,
4593 htlc_maximum_msat: OptionalField::Absent,
4595 fee_proportional_millionths: 0,
4596 excess_data: Vec::new()
4600 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4601 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4602 // expensive) channels 12-13 path.
4603 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4604 assert_eq!(route.paths.len(), 1);
4605 assert_eq!(route.paths[0].len(), 2);
4607 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4608 assert_eq!(route.paths[0][0].short_channel_id, 12);
4609 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4610 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4611 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4612 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4614 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4615 assert_eq!(route.paths[0][1].short_channel_id, 13);
4616 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4617 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4618 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4619 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4624 fn multiple_direct_first_hops() {
4625 // Previously we'd only ever considered one first hop path per counterparty.
4626 // However, as we don't restrict users to one channel per peer, we really need to support
4627 // looking at all first hop paths.
4628 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4629 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4630 // route over multiple channels with the same first hop.
4631 let secp_ctx = Secp256k1::new();
4632 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4633 let logger = Arc::new(test_utils::TestLogger::new());
4634 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4635 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4636 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4639 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4640 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4641 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4642 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4643 assert_eq!(route.paths.len(), 1);
4644 assert_eq!(route.paths[0].len(), 1);
4646 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4647 assert_eq!(route.paths[0][0].short_channel_id, 3);
4648 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4651 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4652 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4653 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4654 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4655 assert_eq!(route.paths.len(), 2);
4656 assert_eq!(route.paths[0].len(), 1);
4657 assert_eq!(route.paths[1].len(), 1);
4659 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4660 assert_eq!(route.paths[0][0].short_channel_id, 3);
4661 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4663 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4664 assert_eq!(route.paths[1][0].short_channel_id, 2);
4665 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4670 fn prefers_shorter_route_with_higher_fees() {
4671 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4672 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4673 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4675 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4676 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4677 let route = get_route(
4678 &our_id, &payment_params, &network_graph, None, 100, 42,
4679 Arc::clone(&logger), &scorer
4681 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4683 assert_eq!(route.get_total_fees(), 100);
4684 assert_eq!(route.get_total_amount(), 100);
4685 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4687 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4688 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4689 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4690 let route = get_route(
4691 &our_id, &payment_params, &network_graph, None, 100, 42,
4692 Arc::clone(&logger), &scorer
4694 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4696 assert_eq!(route.get_total_fees(), 300);
4697 assert_eq!(route.get_total_amount(), 100);
4698 assert_eq!(path, vec![2, 4, 7, 10]);
4701 struct BadChannelScorer {
4702 short_channel_id: u64,
4706 impl Writeable for BadChannelScorer {
4707 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4709 impl Score for BadChannelScorer {
4710 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4711 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4714 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4715 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4718 struct BadNodeScorer {
4723 impl Writeable for BadNodeScorer {
4724 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4727 impl Score for BadNodeScorer {
4728 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4729 if *target == self.node_id { u64::max_value() } else { 0 }
4732 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4733 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4737 fn avoids_routing_through_bad_channels_and_nodes() {
4738 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4739 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4740 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4742 // A path to nodes[6] exists when no penalties are applied to any channel.
4743 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4744 let route = get_route(
4745 &our_id, &payment_params, &network_graph, None, 100, 42,
4746 Arc::clone(&logger), &scorer
4748 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4750 assert_eq!(route.get_total_fees(), 100);
4751 assert_eq!(route.get_total_amount(), 100);
4752 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4754 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4755 let scorer = BadChannelScorer { short_channel_id: 6 };
4756 let route = get_route(
4757 &our_id, &payment_params, &network_graph, None, 100, 42,
4758 Arc::clone(&logger), &scorer
4760 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4762 assert_eq!(route.get_total_fees(), 300);
4763 assert_eq!(route.get_total_amount(), 100);
4764 assert_eq!(path, vec![2, 4, 7, 10]);
4766 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4767 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4769 &our_id, &payment_params, &network_graph, None, 100, 42,
4770 Arc::clone(&logger), &scorer
4772 Err(LightningError { err, .. } ) => {
4773 assert_eq!(err, "Failed to find a path to the given destination");
4775 Ok(_) => panic!("Expected error"),
4780 fn total_fees_single_path() {
4784 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4785 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4786 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4789 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4790 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4791 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4794 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4795 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4796 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4799 payment_params: None,
4802 assert_eq!(route.get_total_fees(), 250);
4803 assert_eq!(route.get_total_amount(), 225);
4807 fn total_fees_multi_path() {
4811 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4812 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4813 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4816 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4817 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4818 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4822 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4823 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4824 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4827 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4828 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4829 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4832 payment_params: None,
4835 assert_eq!(route.get_total_fees(), 200);
4836 assert_eq!(route.get_total_amount(), 300);
4840 fn total_empty_route_no_panic() {
4841 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4842 // would both panic if the route was completely empty. We test to ensure they return 0
4843 // here, even though its somewhat nonsensical as a route.
4844 let route = Route { paths: Vec::new(), payment_params: None };
4846 assert_eq!(route.get_total_fees(), 0);
4847 assert_eq!(route.get_total_amount(), 0);
4851 fn limits_total_cltv_delta() {
4852 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4853 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4855 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4857 // Make sure that generally there is at least one route available
4858 let feasible_max_total_cltv_delta = 1008;
4859 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4860 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
4861 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
4862 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4863 assert_ne!(path.len(), 0);
4865 // But not if we exclude all paths on the basis of their accumulated CLTV delta
4866 let fail_max_total_cltv_delta = 23;
4867 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4868 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
4869 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer)
4871 Err(LightningError { err, .. } ) => {
4872 assert_eq!(err, "Failed to find a path to the given destination");
4874 Ok(_) => panic!("Expected error"),
4878 #[cfg(not(feature = "no-std"))]
4879 pub(super) fn random_init_seed() -> u64 {
4880 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4881 use core::hash::{BuildHasher, Hasher};
4882 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4883 println!("Using seed of {}", seed);
4886 #[cfg(not(feature = "no-std"))]
4887 use util::ser::Readable;
4890 #[cfg(not(feature = "no-std"))]
4891 fn generate_routes() {
4892 let mut d = match super::test_utils::get_route_file() {
4899 let graph = NetworkGraph::read(&mut d).unwrap();
4900 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4902 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4903 let mut seed = random_init_seed() as usize;
4904 let nodes = graph.read_only().nodes().clone();
4905 'load_endpoints: for _ in 0..10 {
4907 seed = seed.overflowing_mul(0xdeadbeef).0;
4908 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4909 seed = seed.overflowing_mul(0xdeadbeef).0;
4910 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4911 let payment_params = PaymentParameters::from_node_id(dst);
4912 let amt = seed as u64 % 200_000_000;
4913 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4914 continue 'load_endpoints;
4921 #[cfg(not(feature = "no-std"))]
4922 fn generate_routes_mpp() {
4923 let mut d = match super::test_utils::get_route_file() {
4930 let graph = NetworkGraph::read(&mut d).unwrap();
4931 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4933 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4934 let mut seed = random_init_seed() as usize;
4935 let nodes = graph.read_only().nodes().clone();
4936 'load_endpoints: for _ in 0..10 {
4938 seed = seed.overflowing_mul(0xdeadbeef).0;
4939 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4940 seed = seed.overflowing_mul(0xdeadbeef).0;
4941 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4942 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
4943 let amt = seed as u64 % 200_000_000;
4944 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4945 continue 'load_endpoints;
4952 #[cfg(all(test, not(feature = "no-std")))]
4953 pub(crate) mod test_utils {
4955 /// Tries to open a network graph file, or panics with a URL to fetch it.
4956 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4957 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4958 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4959 .or_else(|_| { // Fall back to guessing based on the binary location
4960 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4961 let mut path = std::env::current_exe().unwrap();
4962 path.pop(); // lightning-...
4964 path.pop(); // debug
4965 path.pop(); // target
4966 path.push("lightning");
4967 path.push("net_graph-2021-05-31.bin");
4968 eprintln!("{}", path.to_str().unwrap());
4971 .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");
4972 #[cfg(require_route_graph_test)]
4973 return Ok(res.unwrap());
4974 #[cfg(not(require_route_graph_test))]
4979 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4982 use bitcoin::hashes::Hash;
4983 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
4984 use chain::transaction::OutPoint;
4985 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
4986 use ln::features::{InitFeatures, InvoiceFeatures};
4987 use routing::scoring::Scorer;
4988 use util::logger::{Logger, Record};
4992 struct DummyLogger {}
4993 impl Logger for DummyLogger {
4994 fn log(&self, _record: &Record) {}
4997 struct ZeroPenaltyScorer;
4998 impl Score for ZeroPenaltyScorer {
4999 fn channel_penalty_msat(
5000 &self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId
5002 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5003 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5006 fn read_network_graph() -> NetworkGraph {
5007 let mut d = test_utils::get_route_file().unwrap();
5008 NetworkGraph::read(&mut d).unwrap()
5011 fn payer_pubkey() -> PublicKey {
5012 let secp_ctx = Secp256k1::new();
5013 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5017 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5019 channel_id: [0; 32],
5020 counterparty: ChannelCounterparty {
5021 features: InitFeatures::known(),
5023 unspendable_punishment_reserve: 0,
5024 forwarding_info: None,
5026 funding_txo: Some(OutPoint {
5027 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5029 short_channel_id: Some(1),
5030 channel_value_satoshis: 10_000_000,
5032 balance_msat: 10_000_000,
5033 outbound_capacity_msat: 10_000_000,
5034 inbound_capacity_msat: 0,
5035 unspendable_punishment_reserve: None,
5036 confirmations_required: None,
5037 force_close_spend_delay: None,
5039 is_funding_locked: true,
5046 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5047 let network_graph = read_network_graph();
5048 let scorer = ZeroPenaltyScorer;
5049 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5053 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5054 let network_graph = read_network_graph();
5055 let scorer = ZeroPenaltyScorer;
5056 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5060 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5061 let network_graph = read_network_graph();
5062 let scorer = Scorer::default();
5063 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5067 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5068 let network_graph = read_network_graph();
5069 let scorer = Scorer::default();
5070 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5073 fn generate_routes<S: Score>(
5074 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5076 let nodes = graph.read_only().nodes().clone();
5077 let payer = payer_pubkey();
5079 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5080 let mut routes = Vec::new();
5081 let mut route_endpoints = Vec::new();
5082 let mut seed: usize = 0xdeadbeef;
5083 'load_endpoints: for _ in 0..100 {
5086 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5088 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5089 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5090 let first_hop = first_hop(src);
5091 let amt = seed as u64 % 1_000_000;
5092 if let Ok(route) = get_route(&payer, ¶ms, &graph, Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer) {
5094 route_endpoints.push((first_hop, params, amt));
5095 continue 'load_endpoints;
5100 // ...and seed the scorer with success and failure data...
5101 for route in routes {
5102 let amount = route.get_total_amount();
5103 if amount < 250_000 {
5104 for path in route.paths {
5105 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5107 } else if amount > 750_000 {
5108 for path in route.paths {
5109 let short_channel_id = path[path.len() / 2].short_channel_id;
5110 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5115 // ...then benchmark finding paths between the nodes we learned.
5118 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5119 assert!(get_route(&payer, params, &graph, Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer).is_ok());