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 fn features(&self) -> ChannelFeatures {
378 CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
379 CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
380 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
384 fn cltv_expiry_delta(&self) -> u32 {
386 CandidateRouteHop::FirstHop { .. } => 0,
387 CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
388 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
392 fn htlc_minimum_msat(&self) -> u64 {
394 CandidateRouteHop::FirstHop { .. } => 0,
395 CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
396 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
400 fn fees(&self) -> RoutingFees {
402 CandidateRouteHop::FirstHop { .. } => RoutingFees {
403 base_msat: 0, proportional_millionths: 0,
405 CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
406 CandidateRouteHop::PrivateHop { hint } => hint.fees,
410 fn effective_capacity(&self) -> EffectiveCapacity {
412 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
413 liquidity_msat: details.outbound_capacity_msat,
415 CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
416 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
421 /// It's useful to keep track of the hops associated with the fees required to use them,
422 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
423 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
424 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
425 #[derive(Clone, Debug)]
426 struct PathBuildingHop<'a> {
427 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
428 // is a larger refactor and will require careful performance analysis.
430 candidate: CandidateRouteHop<'a>,
433 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
434 src_lowest_inbound_fees: RoutingFees,
435 /// All the fees paid *after* this channel on the way to the destination
436 next_hops_fee_msat: u64,
437 /// Fee paid for the use of the current channel (see candidate.fees()).
438 /// The value will be actually deducted from the counterparty balance on the previous link.
439 hop_use_fee_msat: u64,
440 /// Used to compare channels when choosing the for routing.
441 /// Includes paying for the use of a hop and the following hops, as well as
442 /// an estimated cost of reaching this hop.
443 /// Might get stale when fees are recomputed. Primarily for internal use.
445 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
446 /// walk and may be invalid thereafter.
447 path_htlc_minimum_msat: u64,
448 /// All penalties incurred from this channel on the way to the destination, as calculated using
450 path_penalty_msat: u64,
451 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
452 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
453 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
454 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
455 /// avoid processing them again.
457 #[cfg(any(test, feature = "fuzztarget"))]
458 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
459 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
460 // value_contribution_msat, which requires tracking it here. See comments below where it is
461 // used for more info.
462 value_contribution_msat: u64,
465 // Instantiated with a list of hops with correct data in them collected during path finding,
466 // an instance of this struct should be further modified only via given methods.
468 struct PaymentPath<'a> {
469 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
472 impl<'a> PaymentPath<'a> {
473 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
474 fn get_value_msat(&self) -> u64 {
475 self.hops.last().unwrap().0.fee_msat
478 fn get_total_fee_paid_msat(&self) -> u64 {
479 if self.hops.len() < 1 {
483 // Can't use next_hops_fee_msat because it gets outdated.
484 for (i, (hop, _)) in self.hops.iter().enumerate() {
485 if i != self.hops.len() - 1 {
486 result += hop.fee_msat;
492 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
493 // to change fees may result in an inconsistency.
495 // Sometimes we call this function right after constructing a path which is inconsistent in
496 // that it the value being transferred has decreased while we were doing path finding, leading
497 // to the fees being paid not lining up with the actual limits.
499 // Note that this function is not aware of the available_liquidity limit, and thus does not
500 // support increasing the value being transferred.
501 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
502 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
504 let mut total_fee_paid_msat = 0 as u64;
505 for i in (0..self.hops.len()).rev() {
506 let last_hop = i == self.hops.len() - 1;
508 // For non-last-hop, this value will represent the fees paid on the current hop. It
509 // will consist of the fees for the use of the next hop, and extra fees to match
510 // htlc_minimum_msat of the current channel. Last hop is handled separately.
511 let mut cur_hop_fees_msat = 0;
513 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
516 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
517 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
518 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
519 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
520 // set it too high just to maliciously take more fees by exploiting this
521 // match htlc_minimum_msat logic.
522 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
523 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
524 // Note that there is a risk that *previous hops* (those closer to us, as we go
525 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
527 // This might make us end up with a broken route, although this should be super-rare
528 // in practice, both because of how healthy channels look like, and how we pick
529 // channels in add_entry.
530 // Also, this can't be exploited more heavily than *announce a free path and fail
532 cur_hop_transferred_amount_msat += extra_fees_msat;
533 total_fee_paid_msat += extra_fees_msat;
534 cur_hop_fees_msat += extra_fees_msat;
538 // Final hop is a special case: it usually has just value_msat (by design), but also
539 // it still could overpay for the htlc_minimum_msat.
540 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
542 // Propagate updated fees for the use of the channels to one hop back, where they
543 // will be actually paid (fee_msat). The last hop is handled above separately.
544 cur_hop.fee_msat = cur_hop_fees_msat;
547 // Fee for the use of the current hop which will be deducted on the previous hop.
548 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
549 // this channel is free for us.
551 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
552 cur_hop.hop_use_fee_msat = new_fee;
553 total_fee_paid_msat += new_fee;
555 // It should not be possible because this function is called only to reduce the
556 // value. In that case, compute_fee was already called with the same fees for
557 // larger amount and there was no overflow.
565 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
566 let proportional_fee_millions =
567 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
568 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
569 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
573 // This function may be (indirectly) called without any verification,
574 // with channel_fees provided by a caller. We should handle it gracefully.
579 /// Finds a route from us (payer) to the given target node (payee).
581 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
582 /// Without this, MPP will only be used if the payee's features are available in the network graph.
584 /// Private routing paths between a public node and the target may be included in `params.payee`.
586 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
587 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
588 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
590 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
591 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
592 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
596 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
597 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
602 /// Panics if first_hops contains channels without short_channel_ids;
603 /// [`ChannelManager::list_usable_channels`] will never include such channels.
605 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
606 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
607 pub fn find_route<L: Deref, S: Score>(
608 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
609 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
610 ) -> Result<Route, LightningError>
611 where L::Target: Logger {
613 our_node_pubkey, &route_params.payment_params, network, first_hops, route_params.final_value_msat,
614 route_params.final_cltv_expiry_delta, logger, scorer
618 pub(crate) fn get_route<L: Deref, S: Score>(
619 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network: &NetworkGraph,
620 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
621 logger: L, scorer: &S
622 ) -> Result<Route, LightningError>
623 where L::Target: Logger {
624 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
625 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
627 if payee_node_id == our_node_id {
628 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
631 if final_value_msat > MAX_VALUE_MSAT {
632 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
635 if final_value_msat == 0 {
636 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
639 for route in payment_params.route_hints.iter() {
640 for hop in &route.0 {
641 if hop.src_node_id == payment_params.payee_pubkey {
642 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
647 // The general routing idea is the following:
648 // 1. Fill first/last hops communicated by the caller.
649 // 2. Attempt to construct a path from payer to payee for transferring
650 // any ~sufficient (described later) value.
651 // If succeed, remember which channels were used and how much liquidity they have available,
652 // so that future paths don't rely on the same liquidity.
653 // 3. Proceed to the next step if:
654 // - we hit the recommended target value;
655 // - OR if we could not construct a new path. Any next attempt will fail too.
656 // Otherwise, repeat step 2.
657 // 4. See if we managed to collect paths which aggregately are able to transfer target value
658 // (not recommended value). If yes, proceed. If not, fail routing.
659 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
660 // 6. Of all the found paths, select only those with the lowest total fee.
661 // 7. The last path in every selected route is likely to be more than we need.
662 // Reduce its value-to-transfer and recompute fees.
663 // 8. Choose the best route by the lowest total fee.
665 // As for the actual search algorithm,
666 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
667 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
669 // We are not a faithful Dijkstra's implementation because we can change values which impact
670 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
671 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
672 // the value we are currently attempting to send over a path, we simply reduce the value being
673 // sent along the path for any hops after that channel. This may imply that later fees (which
674 // we've already tabulated) are lower because a smaller value is passing through the channels
675 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
676 // channels which were selected earlier (and which may still be used for other paths without a
677 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
680 // One potentially problematic case for this algorithm would be if there are many
681 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
682 // graph walking), we may never find a path which is not liquidity-limited and has lower
683 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
684 // Because we only consider paths with at least 5% of the total value being sent, the damage
685 // from such a case should be limited, however this could be further reduced in the future by
686 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
687 // limits for the purposes of fee calculation.
689 // Alternatively, we could store more detailed path information in the heap (targets, below)
690 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
691 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
692 // and practically (as we would need to store dynamically-allocated path information in heap
693 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
694 // results of such an algorithm would likely be biased towards lower-value paths.
696 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
697 // outside of our current search value, running a path search more times to gather candidate
698 // paths at different values. While this may be acceptable, further path searches may increase
699 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
700 // graph for candidate paths, calculating the maximum value which can realistically be sent at
701 // the same time, remaining generic across different payment values.
703 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
704 // to use as the A* heuristic beyond just the cost to get one node further than the current
707 let network_graph = network.read_only();
708 let network_channels = network_graph.channels();
709 let network_nodes = network_graph.nodes();
711 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
712 // it. If the payee supports it they're supposed to include it in the invoice, so that should
714 let allow_mpp = if let Some(features) = &payment_params.features {
715 features.supports_basic_mpp()
716 } else if let Some(node) = network_nodes.get(&payee_node_id) {
717 if let Some(node_info) = node.announcement_info.as_ref() {
718 node_info.features.supports_basic_mpp()
721 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
722 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" });
725 // Prepare the data we'll use for payee-to-payer search by
726 // inserting first hops suggested by the caller as targets.
727 // Our search will then attempt to reach them while traversing from the payee node.
728 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
729 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
730 if let Some(hops) = first_hops {
732 if chan.short_channel_id.is_none() {
733 panic!("first_hops should be filled in with usable channels, not pending ones");
735 if chan.counterparty.node_id == *our_node_pubkey {
736 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
739 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
740 .or_insert(Vec::new())
743 if first_hop_targets.is_empty() {
744 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
748 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
749 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
750 // adding duplicate entries when we find a better path to a given node.
751 let mut targets = BinaryHeap::new();
753 // Map from node_id to information about the best current path to that node, including feerate
755 let mut dist = HashMap::with_capacity(network_nodes.len());
757 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
758 // indicating that we may wish to try again with a higher value, potentially paying to meet an
759 // htlc_minimum with extra fees while still finding a cheaper path.
760 let mut hit_minimum_limit;
762 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
763 // We start with a path_value of the exact amount we want, and if that generates a route we may
764 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
765 // amount we want in total across paths, selecting the best subset at the end.
766 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
767 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
768 let mut path_value_msat = final_value_msat;
770 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
771 // This map allows paths to be aware of the channel use by other paths in the same call.
772 // This would help to make a better path finding decisions and not "overbook" channels.
773 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
774 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
776 // Keeping track of how much value we already collected across other paths. Helps to decide:
777 // - how much a new path should be transferring (upper bound);
778 // - whether a channel should be disregarded because
779 // it's available liquidity is too small comparing to how much more we need to collect;
780 // - when we want to stop looking for new paths.
781 let mut already_collected_value_msat = 0;
783 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
785 macro_rules! add_entry {
786 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
787 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
788 // since that value has to be transferred over this channel.
789 // Returns whether this channel caused an update to `targets`.
790 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
791 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
792 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
793 // We "return" whether we updated the path at the end, via this:
794 let mut did_add_update_path_to_src_node = false;
795 // Channels to self should not be used. This is more of belt-and-suspenders, because in
796 // practice these cases should be caught earlier:
797 // - for regular channels at channel announcement (TODO)
798 // - for first and last hops early in get_route
799 if $src_node_id != $dest_node_id {
800 let short_channel_id = $candidate.short_channel_id();
801 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
802 .entry(short_channel_id)
803 .or_insert_with(|| $candidate.effective_capacity().as_msat());
805 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
806 // It may be misleading because we might later choose to reduce the value transferred
807 // over these channels, and the channel which was insufficient might become sufficient.
808 // Worst case: we drop a good channel here because it can't cover the high following
809 // fees caused by one expensive channel, but then this channel could have been used
810 // if the amount being transferred over this path is lower.
811 // We do this for now, but this is a subject for removal.
812 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
814 // Routing Fragmentation Mitigation heuristic:
816 // Routing fragmentation across many payment paths increases the overall routing
817 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
818 // Taking too many smaller paths also increases the chance of payment failure.
819 // Thus to avoid this effect, we require from our collected links to provide
820 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
822 // This requirement is currently 5% of the remaining-to-be-collected value.
823 // This means as we successfully advance in our collection,
824 // the absolute liquidity contribution is lowered,
825 // thus increasing the number of potential channels to be selected.
827 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
828 // or 100% if we're not allowed to do multipath payments.
829 let minimal_value_contribution_msat: u64 = if allow_mpp {
830 (recommended_value_msat - already_collected_value_msat + 19) / 20
834 // Verify the liquidity offered by this channel complies to the minimal contribution.
835 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
837 // Do not consider candidates that exceed the maximum total cltv expiry limit.
838 let max_total_cltv_expiry_delta = payment_params.max_total_cltv_expiry_delta;
839 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
840 .checked_add($candidate.cltv_expiry_delta())
841 .unwrap_or(u32::max_value());
842 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
844 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
845 // Includes paying fees for the use of the following channels.
846 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
847 Some(result) => result,
848 // Can't overflow due to how the values were computed right above.
849 None => unreachable!(),
851 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
852 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
853 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
855 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
856 // bother considering this channel.
857 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
858 // be only reduced later (not increased), so this channel should just be skipped
859 // as not sufficient.
860 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
861 hit_minimum_limit = true;
862 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
863 // Note that low contribution here (limited by available_liquidity_msat)
864 // might violate htlc_minimum_msat on the hops which are next along the
865 // payment path (upstream to the payee). To avoid that, we recompute
866 // path fees knowing the final path contribution after constructing it.
867 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
868 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
869 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
870 .unwrap_or_else(|| u64::max_value());
871 let hm_entry = dist.entry($src_node_id);
872 let old_entry = hm_entry.or_insert_with(|| {
873 // If there was previously no known way to access the source node
874 // (recall it goes payee-to-payer) of short_channel_id, first add a
875 // semi-dummy record just to compute the fees to reach the source node.
876 // This will affect our decision on selecting short_channel_id
877 // as a way to reach the $dest_node_id.
878 let mut fee_base_msat = u32::max_value();
879 let mut fee_proportional_millionths = u32::max_value();
880 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
881 fee_base_msat = fees.base_msat;
882 fee_proportional_millionths = fees.proportional_millionths;
885 node_id: $dest_node_id.clone(),
886 candidate: $candidate.clone(),
888 src_lowest_inbound_fees: RoutingFees {
889 base_msat: fee_base_msat,
890 proportional_millionths: fee_proportional_millionths,
892 next_hops_fee_msat: u64::max_value(),
893 hop_use_fee_msat: u64::max_value(),
894 total_fee_msat: u64::max_value(),
895 path_htlc_minimum_msat,
896 path_penalty_msat: u64::max_value(),
897 was_processed: false,
898 #[cfg(any(test, feature = "fuzztarget"))]
899 value_contribution_msat,
903 #[allow(unused_mut)] // We only use the mut in cfg(test)
904 let mut should_process = !old_entry.was_processed;
905 #[cfg(any(test, feature = "fuzztarget"))]
907 // In test/fuzzing builds, we do extra checks to make sure the skipping
908 // of already-seen nodes only happens in cases we expect (see below).
909 if !should_process { should_process = true; }
913 let mut hop_use_fee_msat = 0;
914 let mut total_fee_msat = $next_hops_fee_msat;
916 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
917 // will have the same effective-fee
918 if $src_node_id != our_node_id {
919 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
920 // max_value means we'll always fail
921 // the old_entry.total_fee_msat > total_fee_msat check
922 None => total_fee_msat = u64::max_value(),
924 hop_use_fee_msat = fee_msat;
925 total_fee_msat += hop_use_fee_msat;
926 // When calculating the lowest inbound fees to a node, we
927 // calculate fees here not based on the actual value we think
928 // will flow over this channel, but on the minimum value that
929 // we'll accept flowing over it. The minimum accepted value
930 // is a constant through each path collection run, ensuring
931 // consistent basis. Otherwise we may later find a
932 // different path to the source node that is more expensive,
933 // but which we consider to be cheaper because we are capacity
934 // constrained and the relative fee becomes lower.
935 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
936 .map(|a| a.checked_add(total_fee_msat)) {
941 total_fee_msat = u64::max_value();
948 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
949 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
950 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
951 let new_graph_node = RouteGraphNode {
952 node_id: $src_node_id,
953 lowest_fee_to_peer_through_node: total_fee_msat,
954 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
955 total_cltv_delta: hop_total_cltv_delta,
956 value_contribution_msat: value_contribution_msat,
957 path_htlc_minimum_msat,
961 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
962 // if this way is cheaper than the already known
963 // (considering the cost to "reach" this channel from the route destination,
964 // the cost of using this channel,
965 // and the cost of routing to the source node of this channel).
966 // Also, consider that htlc_minimum_msat_difference, because we might end up
967 // paying it. Consider the following exploit:
968 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
969 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
970 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
971 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
973 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
974 // but it may require additional tracking - we don't want to double-count
975 // the fees included in $next_hops_path_htlc_minimum_msat, but also
976 // can't use something that may decrease on future hops.
977 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
978 .checked_add(old_entry.path_penalty_msat)
979 .unwrap_or_else(|| u64::max_value());
980 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
981 .checked_add(path_penalty_msat)
982 .unwrap_or_else(|| u64::max_value());
984 if !old_entry.was_processed && new_cost < old_cost {
985 targets.push(new_graph_node);
986 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
987 old_entry.hop_use_fee_msat = hop_use_fee_msat;
988 old_entry.total_fee_msat = total_fee_msat;
989 old_entry.node_id = $dest_node_id.clone();
990 old_entry.candidate = $candidate.clone();
991 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
992 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
993 old_entry.path_penalty_msat = path_penalty_msat;
994 #[cfg(any(test, feature = "fuzztarget"))]
996 old_entry.value_contribution_msat = value_contribution_msat;
998 did_add_update_path_to_src_node = true;
999 } else if old_entry.was_processed && new_cost < old_cost {
1000 #[cfg(any(test, feature = "fuzztarget"))]
1002 // If we're skipping processing a node which was previously
1003 // processed even though we found another path to it with a
1004 // cheaper fee, check that it was because the second path we
1005 // found (which we are processing now) has a lower value
1006 // contribution due to an HTLC minimum limit.
1008 // e.g. take a graph with two paths from node 1 to node 2, one
1009 // through channel A, and one through channel B. Channel A and
1010 // B are both in the to-process heap, with their scores set by
1011 // a higher htlc_minimum than fee.
1012 // Channel A is processed first, and the channels onwards from
1013 // node 1 are added to the to-process heap. Thereafter, we pop
1014 // Channel B off of the heap, note that it has a much more
1015 // restrictive htlc_maximum_msat, and recalculate the fees for
1016 // all of node 1's channels using the new, reduced, amount.
1018 // This would be bogus - we'd be selecting a higher-fee path
1019 // with a lower htlc_maximum_msat instead of the one we'd
1020 // already decided to use.
1021 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1023 value_contribution_msat + path_penalty_msat <
1024 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1032 did_add_update_path_to_src_node
1036 let empty_node_features = NodeFeatures::empty();
1037 // Find ways (channels with destination) to reach a given node and store them
1038 // in the corresponding data structures (routing graph etc).
1039 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1040 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1041 // This data can later be helpful to optimize routing (pay lower fees).
1042 macro_rules! add_entries_to_cheapest_to_target_node {
1043 ( $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 ) => {
1044 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1045 let was_processed = elem.was_processed;
1046 elem.was_processed = true;
1049 // Entries are added to dist in add_entry!() when there is a channel from a node.
1050 // Because there are no channels from payee, it will not have a dist entry at this point.
1051 // If we're processing any other node, it is always be the result of a channel from it.
1052 assert_eq!($node_id, payee_node_id);
1057 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1058 for details in first_channels {
1059 let candidate = CandidateRouteHop::FirstHop { details };
1060 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);
1064 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1067 &empty_node_features
1070 if !features.requires_unknown_bits() {
1071 for chan_id in $node.channels.iter() {
1072 let chan = network_channels.get(chan_id).unwrap();
1073 if !chan.features.requires_unknown_bits() {
1074 let directed_channel =
1075 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1076 let source = directed_channel.source();
1077 let target = directed_channel.target();
1078 if first_hops.is_none() || *source != our_node_id {
1079 if let Some(direction) = directed_channel.direction() {
1080 if direction.enabled {
1081 let candidate = CandidateRouteHop::PublicHop {
1082 info: directed_channel.with_update().unwrap(),
1083 short_channel_id: *chan_id,
1085 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);
1096 let mut payment_paths = Vec::<PaymentPath>::new();
1098 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1099 'paths_collection: loop {
1100 // For every new path, start from scratch, except
1101 // bookkept_channels_liquidity_available_msat, which will improve
1102 // the further iterations of path finding. Also don't erase first_hop_targets.
1105 hit_minimum_limit = false;
1107 // If first hop is a private channel and the only way to reach the payee, this is the only
1108 // place where it could be added.
1109 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1110 for details in first_channels {
1111 let candidate = CandidateRouteHop::FirstHop { details };
1112 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1113 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1117 // Add the payee as a target, so that the payee-to-payer
1118 // search algorithm knows what to start with.
1119 match network_nodes.get(&payee_node_id) {
1120 // The payee is not in our network graph, so nothing to add here.
1121 // There is still a chance of reaching them via last_hops though,
1122 // so don't yet fail the payment here.
1123 // If not, targets.pop() will not even let us enter the loop in step 2.
1126 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1131 // If a caller provided us with last hops, add them to routing targets. Since this happens
1132 // earlier than general path finding, they will be somewhat prioritized, although currently
1133 // it matters only if the fees are exactly the same.
1134 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1135 let first_hop_in_route = &(route.0)[0];
1136 let have_hop_src_in_graph =
1137 // Only add the hops in this route to our candidate set if either
1138 // we have a direct channel to the first hop or the first hop is
1139 // in the regular network graph.
1140 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1141 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1142 if have_hop_src_in_graph {
1143 // We start building the path from reverse, i.e., from payee
1144 // to the first RouteHintHop in the path.
1145 let hop_iter = route.0.iter().rev();
1146 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1147 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1148 let mut hop_used = true;
1149 let mut aggregate_next_hops_fee_msat: u64 = 0;
1150 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1151 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1152 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1154 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1155 let source = NodeId::from_pubkey(&hop.src_node_id);
1156 let target = NodeId::from_pubkey(&prev_hop_id);
1157 let candidate = network_channels
1158 .get(&hop.short_channel_id)
1159 .and_then(|channel| channel.as_directed_to(&target))
1160 .and_then(|channel| channel.with_update())
1161 .map(|info| CandidateRouteHop::PublicHop {
1163 short_channel_id: hop.short_channel_id,
1165 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1166 let capacity_msat = candidate.effective_capacity().as_msat();
1167 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1168 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1169 .unwrap_or_else(|| u64::max_value());
1171 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1172 .checked_add(hop.cltv_expiry_delta as u32)
1173 .unwrap_or_else(|| u32::max_value());
1175 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) {
1176 // If this hop was not used then there is no use checking the preceding hops
1177 // in the RouteHint. We can break by just searching for a direct channel between
1178 // last checked hop and first_hop_targets
1182 // Searching for a direct channel between last checked hop and first_hop_targets
1183 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1184 for details in first_channels {
1185 let candidate = CandidateRouteHop::FirstHop { details };
1186 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);
1194 // In the next values of the iterator, the aggregate fees already reflects
1195 // the sum of value sent from payer (final_value_msat) and routing fees
1196 // for the last node in the RouteHint. We need to just add the fees to
1197 // route through the current node so that the preceeding node (next iteration)
1199 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1200 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1201 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1203 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1204 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1205 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1206 .checked_add(hop_htlc_minimum_msat_inc);
1207 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1209 if idx == route.0.len() - 1 {
1210 // The last hop in this iterator is the first hop in
1211 // overall RouteHint.
1212 // If this hop connects to a node with which we have a direct channel,
1213 // ignore the network graph and, if the last hop was added, add our
1214 // direct channel to the candidate set.
1216 // Note that we *must* check if the last hop was added as `add_entry`
1217 // always assumes that the third argument is a node to which we have a
1219 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1220 for details in first_channels {
1221 let candidate = CandidateRouteHop::FirstHop { details };
1222 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);
1230 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1232 // At this point, targets are filled with the data from first and
1233 // last hops communicated by the caller, and the payment receiver.
1234 let mut found_new_path = false;
1237 // If this loop terminates due the exhaustion of targets, two situations are possible:
1238 // - not enough outgoing liquidity:
1239 // 0 < already_collected_value_msat < final_value_msat
1240 // - enough outgoing liquidity:
1241 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1242 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1243 // paths_collection will be stopped because found_new_path==false.
1244 // This is not necessarily a routing failure.
1245 '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() {
1247 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1248 // traversing the graph and arrange the path out of what we found.
1249 if node_id == our_node_id {
1250 let mut new_entry = dist.remove(&our_node_id).unwrap();
1251 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1254 let mut features_set = false;
1255 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1256 for details in first_channels {
1257 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1258 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1259 features_set = true;
1265 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1266 if let Some(node_info) = node.announcement_info.as_ref() {
1267 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1269 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1272 // We should be able to fill in features for everything except the last
1273 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1274 // should be able to extend it further as BOLT 11 does have feature
1275 // flags for the last hop node itself).
1276 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1280 // Means we succesfully traversed from the payer to the payee, now
1281 // save this path for the payment route. Also, update the liquidity
1282 // remaining on the used hops, so that we take them into account
1283 // while looking for more paths.
1284 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1288 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1289 Some(payment_hop) => payment_hop,
1290 // We can't arrive at None because, if we ever add an entry to targets,
1291 // we also fill in the entry in dist (see add_entry!).
1292 None => unreachable!(),
1294 // We "propagate" the fees one hop backward (topologically) here,
1295 // so that fees paid for a HTLC forwarding on the current channel are
1296 // associated with the previous channel (where they will be subtracted).
1297 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1298 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1300 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1301 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1303 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1304 ordered_hops.len(), value_contribution_msat, ordered_hops);
1306 let mut payment_path = PaymentPath {hops: ordered_hops};
1308 // We could have possibly constructed a slightly inconsistent path: since we reduce
1309 // value being transferred along the way, we could have violated htlc_minimum_msat
1310 // on some channels we already passed (assuming dest->source direction). Here, we
1311 // recompute the fees again, so that if that's the case, we match the currently
1312 // underpaid htlc_minimum_msat with fees.
1313 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1315 // Since a path allows to transfer as much value as
1316 // the smallest channel it has ("bottleneck"), we should recompute
1317 // the fees so sender HTLC don't overpay fees when traversing
1318 // larger channels than the bottleneck. This may happen because
1319 // when we were selecting those channels we were not aware how much value
1320 // this path will transfer, and the relative fee for them
1321 // might have been computed considering a larger value.
1322 // Remember that we used these channels so that we don't rely
1323 // on the same liquidity in future paths.
1324 let mut prevented_redundant_path_selection = false;
1325 for (payment_hop, _) in payment_path.hops.iter() {
1326 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1327 let mut spent_on_hop_msat = value_contribution_msat;
1328 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1329 spent_on_hop_msat += next_hops_fee_msat;
1330 if spent_on_hop_msat == *channel_liquidity_available_msat {
1331 // If this path used all of this channel's available liquidity, we know
1332 // this path will not be selected again in the next loop iteration.
1333 prevented_redundant_path_selection = true;
1335 *channel_liquidity_available_msat -= spent_on_hop_msat;
1337 if !prevented_redundant_path_selection {
1338 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1339 // we'll probably end up picking the same path again on the next iteration.
1340 // Decrease the available liquidity of a hop in the middle of the path.
1341 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1342 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1343 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1344 *victim_liquidity = 0;
1347 // Track the total amount all our collected paths allow to send so that we:
1348 // - know when to stop looking for more paths
1349 // - know which of the hops are useless considering how much more sats we need
1350 // (contributes_sufficient_value)
1351 already_collected_value_msat += value_contribution_msat;
1353 payment_paths.push(payment_path);
1354 found_new_path = true;
1355 break 'path_construction;
1358 // If we found a path back to the payee, we shouldn't try to process it again. This is
1359 // the equivalent of the `elem.was_processed` check in
1360 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1361 if node_id == payee_node_id { continue 'path_construction; }
1363 // Otherwise, since the current target node is not us,
1364 // keep "unrolling" the payment graph from payee to payer by
1365 // finding a way to reach the current target from the payer side.
1366 match network_nodes.get(&node_id) {
1369 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);
1375 // If we don't support MPP, no use trying to gather more value ever.
1376 break 'paths_collection;
1380 // Stop either when the recommended value is reached or if no new path was found in this
1382 // In the latter case, making another path finding attempt won't help,
1383 // because we deterministically terminated the search due to low liquidity.
1384 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1385 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1386 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1387 break 'paths_collection;
1388 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1389 // Further, if this was our first walk of the graph, and we weren't limited by an
1390 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1391 // limited by an htlc_minimum_msat value, find another path with a higher value,
1392 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1393 // still keeping a lower total fee than this path.
1394 if !hit_minimum_limit {
1395 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1396 break 'paths_collection;
1398 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1399 path_value_msat = recommended_value_msat;
1404 if payment_paths.len() == 0 {
1405 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1408 if already_collected_value_msat < final_value_msat {
1409 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1412 // Sort by total fees and take the best paths.
1413 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1414 if payment_paths.len() > 50 {
1415 payment_paths.truncate(50);
1418 // Draw multiple sufficient routes by randomly combining the selected paths.
1419 let mut drawn_routes = Vec::new();
1420 for i in 0..payment_paths.len() {
1421 let mut cur_route = Vec::<PaymentPath>::new();
1422 let mut aggregate_route_value_msat = 0;
1425 // TODO: real random shuffle
1426 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1427 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1430 for payment_path in cur_payment_paths {
1431 cur_route.push(payment_path.clone());
1432 aggregate_route_value_msat += payment_path.get_value_msat();
1433 if aggregate_route_value_msat > final_value_msat {
1434 // Last path likely overpaid. Substract it from the most expensive
1435 // (in terms of proportional fee) path in this route and recompute fees.
1436 // This might be not the most economically efficient way, but fewer paths
1437 // also makes routing more reliable.
1438 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1440 // First, drop some expensive low-value paths entirely if possible.
1441 // Sort by value so that we drop many really-low values first, since
1442 // fewer paths is better: the payment is less likely to fail.
1443 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1444 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1445 cur_route.sort_by_key(|path| path.get_value_msat());
1446 // We should make sure that at least 1 path left.
1447 let mut paths_left = cur_route.len();
1448 cur_route.retain(|path| {
1449 if paths_left == 1 {
1452 let mut keep = true;
1453 let path_value_msat = path.get_value_msat();
1454 if path_value_msat <= overpaid_value_msat {
1456 overpaid_value_msat -= path_value_msat;
1462 if overpaid_value_msat == 0 {
1466 assert!(cur_route.len() > 0);
1469 // Now, substract the overpaid value from the most-expensive path.
1470 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1471 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1472 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1473 let expensive_payment_path = cur_route.first_mut().unwrap();
1474 // We already dropped all the small channels above, meaning all the
1475 // remaining channels are larger than remaining overpaid_value_msat.
1476 // Thus, this can't be negative.
1477 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1478 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1482 drawn_routes.push(cur_route);
1486 // Select the best route by lowest total fee.
1487 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1488 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1489 for payment_path in drawn_routes.first().unwrap() {
1490 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1492 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)})?,
1493 node_features: node_features.clone(),
1494 short_channel_id: payment_hop.candidate.short_channel_id(),
1495 channel_features: payment_hop.candidate.features(),
1496 fee_msat: payment_hop.fee_msat,
1497 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1499 }).collect::<Vec<_>>();
1500 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1501 // applicable for the previous hop.
1502 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1503 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1505 selected_paths.push(path);
1508 if let Some(features) = &payment_params.features {
1509 for path in selected_paths.iter_mut() {
1510 if let Ok(route_hop) = path.last_mut().unwrap() {
1511 route_hop.node_features = features.to_context();
1517 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1518 payment_params: Some(payment_params.clone()),
1520 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1526 use routing::scoring::Score;
1527 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1528 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1529 use chain::transaction::OutPoint;
1530 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1531 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1532 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1533 use ln::channelmanager;
1534 use util::test_utils;
1535 use util::ser::Writeable;
1537 use util::ser::Writer;
1539 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1540 use bitcoin::hashes::Hash;
1541 use bitcoin::network::constants::Network;
1542 use bitcoin::blockdata::constants::genesis_block;
1543 use bitcoin::blockdata::script::Builder;
1544 use bitcoin::blockdata::opcodes;
1545 use bitcoin::blockdata::transaction::TxOut;
1549 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1550 use bitcoin::secp256k1::{Secp256k1, All};
1553 use sync::{self, Arc};
1555 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1556 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1557 channelmanager::ChannelDetails {
1558 channel_id: [0; 32],
1559 counterparty: channelmanager::ChannelCounterparty {
1562 unspendable_punishment_reserve: 0,
1563 forwarding_info: None,
1565 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1567 channel_value_satoshis: 0,
1570 outbound_capacity_msat,
1571 inbound_capacity_msat: 42,
1572 unspendable_punishment_reserve: None,
1573 confirmations_required: None,
1574 force_close_spend_delay: None,
1575 is_outbound: true, is_funding_locked: true,
1576 is_usable: true, is_public: true,
1580 // Using the same keys for LN and BTC ids
1582 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1583 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1585 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1586 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1588 let unsigned_announcement = UnsignedChannelAnnouncement {
1590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1594 bitcoin_key_1: node_id_1,
1595 bitcoin_key_2: node_id_2,
1596 excess_data: Vec::new(),
1599 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1600 let valid_announcement = ChannelAnnouncement {
1601 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1602 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1603 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1604 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1605 contents: unsigned_announcement.clone(),
1607 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1608 Ok(res) => assert!(res),
1614 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1615 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1617 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1618 let valid_channel_update = ChannelUpdate {
1619 signature: secp_ctx.sign(&msghash, node_privkey),
1620 contents: update.clone()
1623 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1624 Ok(res) => assert!(res),
1629 fn add_or_update_node(
1630 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1631 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1633 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1634 let unsigned_announcement = UnsignedNodeAnnouncement {
1640 addresses: Vec::new(),
1641 excess_address_data: Vec::new(),
1642 excess_data: Vec::new(),
1644 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1645 let valid_announcement = NodeAnnouncement {
1646 signature: secp_ctx.sign(&msghash, node_privkey),
1647 contents: unsigned_announcement.clone()
1650 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1656 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1657 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1658 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1661 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1663 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1664 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1666 (our_privkey, our_id, privkeys, pubkeys)
1669 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1670 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1671 // test for it later.
1672 let idx = (id - 1) * 2 + 1;
1674 vec![1 << (idx - 8*3), 0, 0, 0]
1675 } else if idx > 8*2 {
1676 vec![1 << (idx - 8*2), 0, 0]
1677 } else if idx > 8*1 {
1678 vec![1 << (idx - 8*1), 0]
1684 fn build_graph() -> (
1686 sync::Arc<NetworkGraph>,
1687 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1688 sync::Arc<test_utils::TestChainSource>,
1689 sync::Arc<test_utils::TestLogger>,
1691 let secp_ctx = Secp256k1::new();
1692 let logger = Arc::new(test_utils::TestLogger::new());
1693 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1694 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1695 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1696 // Build network from our_id to node6:
1698 // -1(1)2- node0 -1(3)2-
1700 // our_id -1(12)2- node7 -1(13)2--- node2
1702 // -1(2)2- node1 -1(4)2-
1705 // chan1 1-to-2: disabled
1706 // chan1 2-to-1: enabled, 0 fee
1708 // chan2 1-to-2: enabled, ignored fee
1709 // chan2 2-to-1: enabled, 0 fee
1711 // chan3 1-to-2: enabled, 0 fee
1712 // chan3 2-to-1: enabled, 100 msat fee
1714 // chan4 1-to-2: enabled, 100% fee
1715 // chan4 2-to-1: enabled, 0 fee
1717 // chan12 1-to-2: enabled, ignored fee
1718 // chan12 2-to-1: enabled, 0 fee
1720 // chan13 1-to-2: enabled, 200% fee
1721 // chan13 2-to-1: enabled, 0 fee
1724 // -1(5)2- node3 -1(8)2--
1728 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1730 // -1(7)2- node5 -1(10)2-
1732 // Channels 5, 8, 9 and 10 are private channels.
1734 // chan5 1-to-2: enabled, 100 msat fee
1735 // chan5 2-to-1: enabled, 0 fee
1737 // chan6 1-to-2: enabled, 0 fee
1738 // chan6 2-to-1: enabled, 0 fee
1740 // chan7 1-to-2: enabled, 100% fee
1741 // chan7 2-to-1: enabled, 0 fee
1743 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1744 // chan8 2-to-1: enabled, 0 fee
1746 // chan9 1-to-2: enabled, 1001 msat fee
1747 // chan9 2-to-1: enabled, 0 fee
1749 // chan10 1-to-2: enabled, 0 fee
1750 // chan10 2-to-1: enabled, 0 fee
1752 // chan11 1-to-2: enabled, 0 fee
1753 // chan11 2-to-1: enabled, 0 fee
1755 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1757 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1758 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1760 short_channel_id: 1,
1763 cltv_expiry_delta: 0,
1764 htlc_minimum_msat: 0,
1765 htlc_maximum_msat: OptionalField::Absent,
1767 fee_proportional_millionths: 0,
1768 excess_data: Vec::new()
1771 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1773 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1774 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1776 short_channel_id: 2,
1779 cltv_expiry_delta: (5 << 4) | 3,
1780 htlc_minimum_msat: 0,
1781 htlc_maximum_msat: OptionalField::Absent,
1782 fee_base_msat: u32::max_value(),
1783 fee_proportional_millionths: u32::max_value(),
1784 excess_data: Vec::new()
1786 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1787 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1788 short_channel_id: 2,
1791 cltv_expiry_delta: 0,
1792 htlc_minimum_msat: 0,
1793 htlc_maximum_msat: OptionalField::Absent,
1795 fee_proportional_millionths: 0,
1796 excess_data: Vec::new()
1799 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1801 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1802 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1803 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1804 short_channel_id: 12,
1807 cltv_expiry_delta: (5 << 4) | 3,
1808 htlc_minimum_msat: 0,
1809 htlc_maximum_msat: OptionalField::Absent,
1810 fee_base_msat: u32::max_value(),
1811 fee_proportional_millionths: u32::max_value(),
1812 excess_data: Vec::new()
1814 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1815 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1816 short_channel_id: 12,
1819 cltv_expiry_delta: 0,
1820 htlc_minimum_msat: 0,
1821 htlc_maximum_msat: OptionalField::Absent,
1823 fee_proportional_millionths: 0,
1824 excess_data: Vec::new()
1827 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1829 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1830 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1832 short_channel_id: 3,
1835 cltv_expiry_delta: (3 << 4) | 1,
1836 htlc_minimum_msat: 0,
1837 htlc_maximum_msat: OptionalField::Absent,
1839 fee_proportional_millionths: 0,
1840 excess_data: Vec::new()
1842 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1844 short_channel_id: 3,
1847 cltv_expiry_delta: (3 << 4) | 2,
1848 htlc_minimum_msat: 0,
1849 htlc_maximum_msat: OptionalField::Absent,
1851 fee_proportional_millionths: 0,
1852 excess_data: Vec::new()
1855 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1856 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1858 short_channel_id: 4,
1861 cltv_expiry_delta: (4 << 4) | 1,
1862 htlc_minimum_msat: 0,
1863 htlc_maximum_msat: OptionalField::Absent,
1865 fee_proportional_millionths: 1000000,
1866 excess_data: Vec::new()
1868 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1870 short_channel_id: 4,
1873 cltv_expiry_delta: (4 << 4) | 2,
1874 htlc_minimum_msat: 0,
1875 htlc_maximum_msat: OptionalField::Absent,
1877 fee_proportional_millionths: 0,
1878 excess_data: Vec::new()
1881 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1882 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1883 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1884 short_channel_id: 13,
1887 cltv_expiry_delta: (13 << 4) | 1,
1888 htlc_minimum_msat: 0,
1889 htlc_maximum_msat: OptionalField::Absent,
1891 fee_proportional_millionths: 2000000,
1892 excess_data: Vec::new()
1894 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1896 short_channel_id: 13,
1899 cltv_expiry_delta: (13 << 4) | 2,
1900 htlc_minimum_msat: 0,
1901 htlc_maximum_msat: OptionalField::Absent,
1903 fee_proportional_millionths: 0,
1904 excess_data: Vec::new()
1907 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1909 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1910 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1912 short_channel_id: 6,
1915 cltv_expiry_delta: (6 << 4) | 1,
1916 htlc_minimum_msat: 0,
1917 htlc_maximum_msat: OptionalField::Absent,
1919 fee_proportional_millionths: 0,
1920 excess_data: Vec::new()
1922 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1924 short_channel_id: 6,
1927 cltv_expiry_delta: (6 << 4) | 2,
1928 htlc_minimum_msat: 0,
1929 htlc_maximum_msat: OptionalField::Absent,
1931 fee_proportional_millionths: 0,
1932 excess_data: Vec::new(),
1935 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1936 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1938 short_channel_id: 11,
1941 cltv_expiry_delta: (11 << 4) | 1,
1942 htlc_minimum_msat: 0,
1943 htlc_maximum_msat: OptionalField::Absent,
1945 fee_proportional_millionths: 0,
1946 excess_data: Vec::new()
1948 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1949 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1950 short_channel_id: 11,
1953 cltv_expiry_delta: (11 << 4) | 2,
1954 htlc_minimum_msat: 0,
1955 htlc_maximum_msat: OptionalField::Absent,
1957 fee_proportional_millionths: 0,
1958 excess_data: Vec::new()
1961 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1963 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1965 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1966 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1967 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1968 short_channel_id: 7,
1971 cltv_expiry_delta: (7 << 4) | 1,
1972 htlc_minimum_msat: 0,
1973 htlc_maximum_msat: OptionalField::Absent,
1975 fee_proportional_millionths: 1000000,
1976 excess_data: Vec::new()
1978 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1979 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1980 short_channel_id: 7,
1983 cltv_expiry_delta: (7 << 4) | 2,
1984 htlc_minimum_msat: 0,
1985 htlc_maximum_msat: OptionalField::Absent,
1987 fee_proportional_millionths: 0,
1988 excess_data: Vec::new()
1991 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1993 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1997 fn simple_route_test() {
1998 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1999 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2000 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2001 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2003 // Simple route to 2 via 1
2005 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
2006 assert_eq!(err, "Cannot send a payment of 0 msat");
2007 } else { panic!(); }
2009 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2010 assert_eq!(route.paths[0].len(), 2);
2012 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2013 assert_eq!(route.paths[0][0].short_channel_id, 2);
2014 assert_eq!(route.paths[0][0].fee_msat, 100);
2015 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2016 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2017 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2019 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2020 assert_eq!(route.paths[0][1].short_channel_id, 4);
2021 assert_eq!(route.paths[0][1].fee_msat, 100);
2022 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2023 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2024 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2028 fn invalid_first_hop_test() {
2029 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2030 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2031 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2032 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2034 // Simple route to 2 via 1
2036 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2038 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) {
2039 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2040 } else { panic!(); }
2042 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2043 assert_eq!(route.paths[0].len(), 2);
2047 fn htlc_minimum_test() {
2048 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2049 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2050 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2051 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2053 // Simple route to 2 via 1
2055 // Disable other paths
2056 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2058 short_channel_id: 12,
2060 flags: 2, // to disable
2061 cltv_expiry_delta: 0,
2062 htlc_minimum_msat: 0,
2063 htlc_maximum_msat: OptionalField::Absent,
2065 fee_proportional_millionths: 0,
2066 excess_data: Vec::new()
2068 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2069 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2070 short_channel_id: 3,
2072 flags: 2, // to disable
2073 cltv_expiry_delta: 0,
2074 htlc_minimum_msat: 0,
2075 htlc_maximum_msat: OptionalField::Absent,
2077 fee_proportional_millionths: 0,
2078 excess_data: Vec::new()
2080 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2081 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2082 short_channel_id: 13,
2084 flags: 2, // to disable
2085 cltv_expiry_delta: 0,
2086 htlc_minimum_msat: 0,
2087 htlc_maximum_msat: OptionalField::Absent,
2089 fee_proportional_millionths: 0,
2090 excess_data: Vec::new()
2092 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2093 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2094 short_channel_id: 6,
2096 flags: 2, // to disable
2097 cltv_expiry_delta: 0,
2098 htlc_minimum_msat: 0,
2099 htlc_maximum_msat: OptionalField::Absent,
2101 fee_proportional_millionths: 0,
2102 excess_data: Vec::new()
2104 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2106 short_channel_id: 7,
2108 flags: 2, // to disable
2109 cltv_expiry_delta: 0,
2110 htlc_minimum_msat: 0,
2111 htlc_maximum_msat: OptionalField::Absent,
2113 fee_proportional_millionths: 0,
2114 excess_data: Vec::new()
2117 // Check against amount_to_transfer_over_msat.
2118 // Set minimal HTLC of 200_000_000 msat.
2119 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2120 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2121 short_channel_id: 2,
2124 cltv_expiry_delta: 0,
2125 htlc_minimum_msat: 200_000_000,
2126 htlc_maximum_msat: OptionalField::Absent,
2128 fee_proportional_millionths: 0,
2129 excess_data: Vec::new()
2132 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2134 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2135 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2136 short_channel_id: 4,
2139 cltv_expiry_delta: 0,
2140 htlc_minimum_msat: 0,
2141 htlc_maximum_msat: OptionalField::Present(199_999_999),
2143 fee_proportional_millionths: 0,
2144 excess_data: Vec::new()
2147 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2148 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) {
2149 assert_eq!(err, "Failed to find a path to the given destination");
2150 } else { panic!(); }
2152 // Lift the restriction on the first hop.
2153 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2154 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2155 short_channel_id: 2,
2158 cltv_expiry_delta: 0,
2159 htlc_minimum_msat: 0,
2160 htlc_maximum_msat: OptionalField::Absent,
2162 fee_proportional_millionths: 0,
2163 excess_data: Vec::new()
2166 // A payment above the minimum should pass
2167 let route = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2168 assert_eq!(route.paths[0].len(), 2);
2172 fn htlc_minimum_overpay_test() {
2173 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2174 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2175 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2176 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2178 // A route to node#2 via two paths.
2179 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2180 // Thus, they can't send 60 without overpaying.
2181 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2183 short_channel_id: 2,
2186 cltv_expiry_delta: 0,
2187 htlc_minimum_msat: 35_000,
2188 htlc_maximum_msat: OptionalField::Present(40_000),
2190 fee_proportional_millionths: 0,
2191 excess_data: Vec::new()
2193 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2195 short_channel_id: 12,
2198 cltv_expiry_delta: 0,
2199 htlc_minimum_msat: 35_000,
2200 htlc_maximum_msat: OptionalField::Present(40_000),
2202 fee_proportional_millionths: 0,
2203 excess_data: Vec::new()
2207 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2209 short_channel_id: 13,
2212 cltv_expiry_delta: 0,
2213 htlc_minimum_msat: 0,
2214 htlc_maximum_msat: OptionalField::Absent,
2216 fee_proportional_millionths: 0,
2217 excess_data: Vec::new()
2219 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2220 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2221 short_channel_id: 4,
2224 cltv_expiry_delta: 0,
2225 htlc_minimum_msat: 0,
2226 htlc_maximum_msat: OptionalField::Absent,
2228 fee_proportional_millionths: 0,
2229 excess_data: Vec::new()
2232 // Disable other paths
2233 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2235 short_channel_id: 1,
2237 flags: 2, // to disable
2238 cltv_expiry_delta: 0,
2239 htlc_minimum_msat: 0,
2240 htlc_maximum_msat: OptionalField::Absent,
2242 fee_proportional_millionths: 0,
2243 excess_data: Vec::new()
2246 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2247 // Overpay fees to hit htlc_minimum_msat.
2248 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2249 // TODO: this could be better balanced to overpay 10k and not 15k.
2250 assert_eq!(overpaid_fees, 15_000);
2252 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2253 // while taking even more fee to match htlc_minimum_msat.
2254 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2256 short_channel_id: 12,
2259 cltv_expiry_delta: 0,
2260 htlc_minimum_msat: 65_000,
2261 htlc_maximum_msat: OptionalField::Present(80_000),
2263 fee_proportional_millionths: 0,
2264 excess_data: Vec::new()
2266 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2268 short_channel_id: 2,
2271 cltv_expiry_delta: 0,
2272 htlc_minimum_msat: 0,
2273 htlc_maximum_msat: OptionalField::Absent,
2275 fee_proportional_millionths: 0,
2276 excess_data: Vec::new()
2278 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2279 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2280 short_channel_id: 4,
2283 cltv_expiry_delta: 0,
2284 htlc_minimum_msat: 0,
2285 htlc_maximum_msat: OptionalField::Absent,
2287 fee_proportional_millionths: 100_000,
2288 excess_data: Vec::new()
2291 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2292 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2293 assert_eq!(route.paths.len(), 1);
2294 assert_eq!(route.paths[0][0].short_channel_id, 12);
2295 let fees = route.paths[0][0].fee_msat;
2296 assert_eq!(fees, 5_000);
2298 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2299 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2300 // the other channel.
2301 assert_eq!(route.paths.len(), 1);
2302 assert_eq!(route.paths[0][0].short_channel_id, 2);
2303 let fees = route.paths[0][0].fee_msat;
2304 assert_eq!(fees, 5_000);
2308 fn disable_channels_test() {
2309 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2310 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2311 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2312 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2314 // // Disable channels 4 and 12 by flags=2
2315 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2316 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2317 short_channel_id: 4,
2319 flags: 2, // to disable
2320 cltv_expiry_delta: 0,
2321 htlc_minimum_msat: 0,
2322 htlc_maximum_msat: OptionalField::Absent,
2324 fee_proportional_millionths: 0,
2325 excess_data: Vec::new()
2327 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2329 short_channel_id: 12,
2331 flags: 2, // to disable
2332 cltv_expiry_delta: 0,
2333 htlc_minimum_msat: 0,
2334 htlc_maximum_msat: OptionalField::Absent,
2336 fee_proportional_millionths: 0,
2337 excess_data: Vec::new()
2340 // If all the channels require some features we don't understand, route should fail
2341 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2342 assert_eq!(err, "Failed to find a path to the given destination");
2343 } else { panic!(); }
2345 // If we specify a channel to node7, that overrides our local channel view and that gets used
2346 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2347 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2348 assert_eq!(route.paths[0].len(), 2);
2350 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2351 assert_eq!(route.paths[0][0].short_channel_id, 42);
2352 assert_eq!(route.paths[0][0].fee_msat, 200);
2353 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2354 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2355 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2357 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2358 assert_eq!(route.paths[0][1].short_channel_id, 13);
2359 assert_eq!(route.paths[0][1].fee_msat, 100);
2360 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2361 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2362 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2366 fn disable_node_test() {
2367 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2368 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2369 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2370 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2372 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2373 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2374 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2375 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2376 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2378 // If all nodes require some features we don't understand, route should fail
2379 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2380 assert_eq!(err, "Failed to find a path to the given destination");
2381 } else { panic!(); }
2383 // If we specify a channel to node7, that overrides our local channel view and that gets used
2384 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2385 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2386 assert_eq!(route.paths[0].len(), 2);
2388 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2389 assert_eq!(route.paths[0][0].short_channel_id, 42);
2390 assert_eq!(route.paths[0][0].fee_msat, 200);
2391 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2392 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2393 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2395 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2396 assert_eq!(route.paths[0][1].short_channel_id, 13);
2397 assert_eq!(route.paths[0][1].fee_msat, 100);
2398 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2399 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2400 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2402 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2403 // naively) assume that the user checked the feature bits on the invoice, which override
2404 // the node_announcement.
2408 fn our_chans_test() {
2409 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2410 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2411 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2413 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2414 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2415 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2416 assert_eq!(route.paths[0].len(), 3);
2418 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2419 assert_eq!(route.paths[0][0].short_channel_id, 2);
2420 assert_eq!(route.paths[0][0].fee_msat, 200);
2421 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2422 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2423 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2425 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2426 assert_eq!(route.paths[0][1].short_channel_id, 4);
2427 assert_eq!(route.paths[0][1].fee_msat, 100);
2428 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2429 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2430 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2432 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2433 assert_eq!(route.paths[0][2].short_channel_id, 3);
2434 assert_eq!(route.paths[0][2].fee_msat, 100);
2435 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2436 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2437 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2439 // If we specify a channel to node7, that overrides our local channel view and that gets used
2440 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2441 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2442 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2443 assert_eq!(route.paths[0].len(), 2);
2445 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2446 assert_eq!(route.paths[0][0].short_channel_id, 42);
2447 assert_eq!(route.paths[0][0].fee_msat, 200);
2448 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2449 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2450 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2452 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2453 assert_eq!(route.paths[0][1].short_channel_id, 13);
2454 assert_eq!(route.paths[0][1].fee_msat, 100);
2455 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2456 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2457 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2460 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2461 let zero_fees = RoutingFees {
2463 proportional_millionths: 0,
2465 vec![RouteHint(vec![RouteHintHop {
2466 src_node_id: nodes[3],
2467 short_channel_id: 8,
2469 cltv_expiry_delta: (8 << 4) | 1,
2470 htlc_minimum_msat: None,
2471 htlc_maximum_msat: None,
2473 ]), RouteHint(vec![RouteHintHop {
2474 src_node_id: nodes[4],
2475 short_channel_id: 9,
2478 proportional_millionths: 0,
2480 cltv_expiry_delta: (9 << 4) | 1,
2481 htlc_minimum_msat: None,
2482 htlc_maximum_msat: None,
2483 }]), RouteHint(vec![RouteHintHop {
2484 src_node_id: nodes[5],
2485 short_channel_id: 10,
2487 cltv_expiry_delta: (10 << 4) | 1,
2488 htlc_minimum_msat: None,
2489 htlc_maximum_msat: None,
2493 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2494 let zero_fees = RoutingFees {
2496 proportional_millionths: 0,
2498 vec![RouteHint(vec![RouteHintHop {
2499 src_node_id: nodes[2],
2500 short_channel_id: 5,
2503 proportional_millionths: 0,
2505 cltv_expiry_delta: (5 << 4) | 1,
2506 htlc_minimum_msat: None,
2507 htlc_maximum_msat: None,
2509 src_node_id: nodes[3],
2510 short_channel_id: 8,
2512 cltv_expiry_delta: (8 << 4) | 1,
2513 htlc_minimum_msat: None,
2514 htlc_maximum_msat: None,
2516 ]), RouteHint(vec![RouteHintHop {
2517 src_node_id: nodes[4],
2518 short_channel_id: 9,
2521 proportional_millionths: 0,
2523 cltv_expiry_delta: (9 << 4) | 1,
2524 htlc_minimum_msat: None,
2525 htlc_maximum_msat: None,
2526 }]), RouteHint(vec![RouteHintHop {
2527 src_node_id: nodes[5],
2528 short_channel_id: 10,
2530 cltv_expiry_delta: (10 << 4) | 1,
2531 htlc_minimum_msat: None,
2532 htlc_maximum_msat: None,
2537 fn partial_route_hint_test() {
2538 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2539 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2540 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2542 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2543 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2544 // RouteHint may be partially used by the algo to build the best path.
2546 // First check that last hop can't have its source as the payee.
2547 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2548 src_node_id: nodes[6],
2549 short_channel_id: 8,
2552 proportional_millionths: 0,
2554 cltv_expiry_delta: (8 << 4) | 1,
2555 htlc_minimum_msat: None,
2556 htlc_maximum_msat: None,
2559 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2560 invalid_last_hops.push(invalid_last_hop);
2562 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2563 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2564 assert_eq!(err, "Route hint cannot have the payee as the source.");
2565 } else { panic!(); }
2568 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2569 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2570 assert_eq!(route.paths[0].len(), 5);
2572 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2573 assert_eq!(route.paths[0][0].short_channel_id, 2);
2574 assert_eq!(route.paths[0][0].fee_msat, 100);
2575 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2576 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2577 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2579 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2580 assert_eq!(route.paths[0][1].short_channel_id, 4);
2581 assert_eq!(route.paths[0][1].fee_msat, 0);
2582 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2583 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2584 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2586 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2587 assert_eq!(route.paths[0][2].short_channel_id, 6);
2588 assert_eq!(route.paths[0][2].fee_msat, 0);
2589 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2590 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2591 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2593 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2594 assert_eq!(route.paths[0][3].short_channel_id, 11);
2595 assert_eq!(route.paths[0][3].fee_msat, 0);
2596 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2597 // If we have a peer in the node map, we'll use their features here since we don't have
2598 // a way of figuring out their features from the invoice:
2599 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2600 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2602 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2603 assert_eq!(route.paths[0][4].short_channel_id, 8);
2604 assert_eq!(route.paths[0][4].fee_msat, 100);
2605 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2606 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2607 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2610 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2611 let zero_fees = RoutingFees {
2613 proportional_millionths: 0,
2615 vec![RouteHint(vec![RouteHintHop {
2616 src_node_id: nodes[3],
2617 short_channel_id: 8,
2619 cltv_expiry_delta: (8 << 4) | 1,
2620 htlc_minimum_msat: None,
2621 htlc_maximum_msat: None,
2622 }]), RouteHint(vec![
2624 ]), RouteHint(vec![RouteHintHop {
2625 src_node_id: nodes[5],
2626 short_channel_id: 10,
2628 cltv_expiry_delta: (10 << 4) | 1,
2629 htlc_minimum_msat: None,
2630 htlc_maximum_msat: None,
2635 fn ignores_empty_last_hops_test() {
2636 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2637 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2638 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2639 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2641 // Test handling of an empty RouteHint passed in Invoice.
2643 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2644 assert_eq!(route.paths[0].len(), 5);
2646 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2647 assert_eq!(route.paths[0][0].short_channel_id, 2);
2648 assert_eq!(route.paths[0][0].fee_msat, 100);
2649 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2650 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2651 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2653 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2654 assert_eq!(route.paths[0][1].short_channel_id, 4);
2655 assert_eq!(route.paths[0][1].fee_msat, 0);
2656 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2657 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2658 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2660 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2661 assert_eq!(route.paths[0][2].short_channel_id, 6);
2662 assert_eq!(route.paths[0][2].fee_msat, 0);
2663 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2664 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2665 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2667 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2668 assert_eq!(route.paths[0][3].short_channel_id, 11);
2669 assert_eq!(route.paths[0][3].fee_msat, 0);
2670 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2671 // If we have a peer in the node map, we'll use their features here since we don't have
2672 // a way of figuring out their features from the invoice:
2673 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2674 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2676 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2677 assert_eq!(route.paths[0][4].short_channel_id, 8);
2678 assert_eq!(route.paths[0][4].fee_msat, 100);
2679 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2680 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2681 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2684 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2685 let zero_fees = RoutingFees {
2687 proportional_millionths: 0,
2689 vec![RouteHint(vec![RouteHintHop {
2690 src_node_id: nodes[2],
2691 short_channel_id: 5,
2694 proportional_millionths: 0,
2696 cltv_expiry_delta: (5 << 4) | 1,
2697 htlc_minimum_msat: None,
2698 htlc_maximum_msat: None,
2700 src_node_id: nodes[3],
2701 short_channel_id: 8,
2703 cltv_expiry_delta: (8 << 4) | 1,
2704 htlc_minimum_msat: None,
2705 htlc_maximum_msat: None,
2706 }]), RouteHint(vec![RouteHintHop {
2707 src_node_id: nodes[5],
2708 short_channel_id: 10,
2710 cltv_expiry_delta: (10 << 4) | 1,
2711 htlc_minimum_msat: None,
2712 htlc_maximum_msat: None,
2717 fn multi_hint_last_hops_test() {
2718 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2719 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2720 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2721 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2722 // Test through channels 2, 3, 5, 8.
2723 // Test shows that multiple hop hints are considered.
2725 // Disabling channels 6 & 7 by flags=2
2726 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2727 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2728 short_channel_id: 6,
2730 flags: 2, // to disable
2731 cltv_expiry_delta: 0,
2732 htlc_minimum_msat: 0,
2733 htlc_maximum_msat: OptionalField::Absent,
2735 fee_proportional_millionths: 0,
2736 excess_data: Vec::new()
2738 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2740 short_channel_id: 7,
2742 flags: 2, // to disable
2743 cltv_expiry_delta: 0,
2744 htlc_minimum_msat: 0,
2745 htlc_maximum_msat: OptionalField::Absent,
2747 fee_proportional_millionths: 0,
2748 excess_data: Vec::new()
2751 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2752 assert_eq!(route.paths[0].len(), 4);
2754 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2755 assert_eq!(route.paths[0][0].short_channel_id, 2);
2756 assert_eq!(route.paths[0][0].fee_msat, 200);
2757 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2758 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2759 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2761 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2762 assert_eq!(route.paths[0][1].short_channel_id, 4);
2763 assert_eq!(route.paths[0][1].fee_msat, 100);
2764 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2765 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2766 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2768 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2769 assert_eq!(route.paths[0][2].short_channel_id, 5);
2770 assert_eq!(route.paths[0][2].fee_msat, 0);
2771 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2772 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2773 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2775 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2776 assert_eq!(route.paths[0][3].short_channel_id, 8);
2777 assert_eq!(route.paths[0][3].fee_msat, 100);
2778 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2779 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2780 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2783 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2784 let zero_fees = RoutingFees {
2786 proportional_millionths: 0,
2788 vec![RouteHint(vec![RouteHintHop {
2789 src_node_id: nodes[4],
2790 short_channel_id: 11,
2792 cltv_expiry_delta: (11 << 4) | 1,
2793 htlc_minimum_msat: None,
2794 htlc_maximum_msat: None,
2796 src_node_id: nodes[3],
2797 short_channel_id: 8,
2799 cltv_expiry_delta: (8 << 4) | 1,
2800 htlc_minimum_msat: None,
2801 htlc_maximum_msat: None,
2802 }]), RouteHint(vec![RouteHintHop {
2803 src_node_id: nodes[4],
2804 short_channel_id: 9,
2807 proportional_millionths: 0,
2809 cltv_expiry_delta: (9 << 4) | 1,
2810 htlc_minimum_msat: None,
2811 htlc_maximum_msat: None,
2812 }]), RouteHint(vec![RouteHintHop {
2813 src_node_id: nodes[5],
2814 short_channel_id: 10,
2816 cltv_expiry_delta: (10 << 4) | 1,
2817 htlc_minimum_msat: None,
2818 htlc_maximum_msat: None,
2823 fn last_hops_with_public_channel_test() {
2824 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2825 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2826 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2827 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2828 // This test shows that public routes can be present in the invoice
2829 // which would be handled in the same manner.
2831 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2832 assert_eq!(route.paths[0].len(), 5);
2834 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2835 assert_eq!(route.paths[0][0].short_channel_id, 2);
2836 assert_eq!(route.paths[0][0].fee_msat, 100);
2837 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2838 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2839 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2841 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2842 assert_eq!(route.paths[0][1].short_channel_id, 4);
2843 assert_eq!(route.paths[0][1].fee_msat, 0);
2844 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2845 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2846 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2848 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2849 assert_eq!(route.paths[0][2].short_channel_id, 6);
2850 assert_eq!(route.paths[0][2].fee_msat, 0);
2851 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2852 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2853 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2855 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2856 assert_eq!(route.paths[0][3].short_channel_id, 11);
2857 assert_eq!(route.paths[0][3].fee_msat, 0);
2858 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2859 // If we have a peer in the node map, we'll use their features here since we don't have
2860 // a way of figuring out their features from the invoice:
2861 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2862 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2864 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2865 assert_eq!(route.paths[0][4].short_channel_id, 8);
2866 assert_eq!(route.paths[0][4].fee_msat, 100);
2867 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2868 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2869 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2873 fn our_chans_last_hop_connect_test() {
2874 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2875 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2876 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2878 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2879 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2880 let mut last_hops = last_hops(&nodes);
2881 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2882 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2883 assert_eq!(route.paths[0].len(), 2);
2885 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2886 assert_eq!(route.paths[0][0].short_channel_id, 42);
2887 assert_eq!(route.paths[0][0].fee_msat, 0);
2888 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2889 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2890 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2892 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2893 assert_eq!(route.paths[0][1].short_channel_id, 8);
2894 assert_eq!(route.paths[0][1].fee_msat, 100);
2895 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2896 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2897 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2899 last_hops[0].0[0].fees.base_msat = 1000;
2901 // Revert to via 6 as the fee on 8 goes up
2902 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
2903 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2904 assert_eq!(route.paths[0].len(), 4);
2906 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2907 assert_eq!(route.paths[0][0].short_channel_id, 2);
2908 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2909 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2910 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2911 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2913 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2914 assert_eq!(route.paths[0][1].short_channel_id, 4);
2915 assert_eq!(route.paths[0][1].fee_msat, 100);
2916 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
2917 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2918 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2920 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2921 assert_eq!(route.paths[0][2].short_channel_id, 7);
2922 assert_eq!(route.paths[0][2].fee_msat, 0);
2923 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
2924 // If we have a peer in the node map, we'll use their features here since we don't have
2925 // a way of figuring out their features from the invoice:
2926 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2927 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2929 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2930 assert_eq!(route.paths[0][3].short_channel_id, 10);
2931 assert_eq!(route.paths[0][3].fee_msat, 100);
2932 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2933 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2934 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2936 // ...but still use 8 for larger payments as 6 has a variable feerate
2937 let route = get_route(&our_id, &payment_params, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2938 assert_eq!(route.paths[0].len(), 5);
2940 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2941 assert_eq!(route.paths[0][0].short_channel_id, 2);
2942 assert_eq!(route.paths[0][0].fee_msat, 3000);
2943 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2944 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2945 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2947 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2948 assert_eq!(route.paths[0][1].short_channel_id, 4);
2949 assert_eq!(route.paths[0][1].fee_msat, 0);
2950 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2951 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2952 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2954 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2955 assert_eq!(route.paths[0][2].short_channel_id, 6);
2956 assert_eq!(route.paths[0][2].fee_msat, 0);
2957 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2958 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2959 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2961 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2962 assert_eq!(route.paths[0][3].short_channel_id, 11);
2963 assert_eq!(route.paths[0][3].fee_msat, 1000);
2964 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2965 // If we have a peer in the node map, we'll use their features here since we don't have
2966 // a way of figuring out their features from the invoice:
2967 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2968 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2970 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2971 assert_eq!(route.paths[0][4].short_channel_id, 8);
2972 assert_eq!(route.paths[0][4].fee_msat, 2000);
2973 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2974 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2975 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2978 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> {
2979 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2980 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2981 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2983 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2984 let last_hops = RouteHint(vec![RouteHintHop {
2985 src_node_id: middle_node_id,
2986 short_channel_id: 8,
2989 proportional_millionths: last_hop_fee_prop,
2991 cltv_expiry_delta: (8 << 4) | 1,
2992 htlc_minimum_msat: None,
2993 htlc_maximum_msat: last_hop_htlc_max,
2995 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
2996 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2997 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2998 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)
3002 fn unannounced_path_test() {
3003 // We should be able to send a payment to a destination without any help of a routing graph
3004 // if we have a channel with a common counterparty that appears in the first and last hop
3006 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3008 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3009 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3010 assert_eq!(route.paths[0].len(), 2);
3012 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3013 assert_eq!(route.paths[0][0].short_channel_id, 42);
3014 assert_eq!(route.paths[0][0].fee_msat, 1001);
3015 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3016 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3017 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3019 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3020 assert_eq!(route.paths[0][1].short_channel_id, 8);
3021 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3022 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3023 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3024 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3028 fn overflow_unannounced_path_test_liquidity_underflow() {
3029 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3030 // the last-hop had a fee which overflowed a u64, we'd panic.
3031 // This was due to us adding the first-hop from us unconditionally, causing us to think
3032 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3033 // In this test, we previously hit a subtraction underflow due to having less available
3034 // liquidity at the last hop than 0.
3035 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());
3039 fn overflow_unannounced_path_test_feerate_overflow() {
3040 // This tests for the same case as above, except instead of hitting a subtraction
3041 // underflow, we hit a case where the fee charged at a hop overflowed.
3042 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());
3046 fn available_amount_while_routing_test() {
3047 // Tests whether we choose the correct available channel amount while routing.
3049 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3050 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3051 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3052 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3054 // We will use a simple single-path route from
3055 // our node to node2 via node0: channels {1, 3}.
3057 // First disable all other paths.
3058 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3060 short_channel_id: 2,
3063 cltv_expiry_delta: 0,
3064 htlc_minimum_msat: 0,
3065 htlc_maximum_msat: OptionalField::Present(100_000),
3067 fee_proportional_millionths: 0,
3068 excess_data: Vec::new()
3070 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3072 short_channel_id: 12,
3075 cltv_expiry_delta: 0,
3076 htlc_minimum_msat: 0,
3077 htlc_maximum_msat: OptionalField::Present(100_000),
3079 fee_proportional_millionths: 0,
3080 excess_data: Vec::new()
3083 // Make the first channel (#1) very permissive,
3084 // and we will be testing all limits on the second channel.
3085 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3087 short_channel_id: 1,
3090 cltv_expiry_delta: 0,
3091 htlc_minimum_msat: 0,
3092 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3094 fee_proportional_millionths: 0,
3095 excess_data: Vec::new()
3098 // First, let's see if routing works if we have absolutely no idea about the available amount.
3099 // In this case, it should be set to 250_000 sats.
3100 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3101 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3102 short_channel_id: 3,
3105 cltv_expiry_delta: 0,
3106 htlc_minimum_msat: 0,
3107 htlc_maximum_msat: OptionalField::Absent,
3109 fee_proportional_millionths: 0,
3110 excess_data: Vec::new()
3114 // Attempt to route more than available results in a failure.
3115 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3116 &our_id, &payment_params, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3117 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3118 } else { panic!(); }
3122 // Now, attempt to route an exact amount we have should be fine.
3123 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3124 assert_eq!(route.paths.len(), 1);
3125 let path = route.paths.last().unwrap();
3126 assert_eq!(path.len(), 2);
3127 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3128 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3131 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3132 // Disable channel #1 and use another first hop.
3133 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3134 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3135 short_channel_id: 1,
3138 cltv_expiry_delta: 0,
3139 htlc_minimum_msat: 0,
3140 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3142 fee_proportional_millionths: 0,
3143 excess_data: Vec::new()
3146 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3147 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3150 // Attempt to route more than available results in a failure.
3151 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3152 &our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3153 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3154 } else { panic!(); }
3158 // Now, attempt to route an exact amount we have should be fine.
3159 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();
3160 assert_eq!(route.paths.len(), 1);
3161 let path = route.paths.last().unwrap();
3162 assert_eq!(path.len(), 2);
3163 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3164 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3167 // Enable channel #1 back.
3168 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3170 short_channel_id: 1,
3173 cltv_expiry_delta: 0,
3174 htlc_minimum_msat: 0,
3175 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3177 fee_proportional_millionths: 0,
3178 excess_data: Vec::new()
3182 // Now let's see if routing works if we know only htlc_maximum_msat.
3183 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3185 short_channel_id: 3,
3188 cltv_expiry_delta: 0,
3189 htlc_minimum_msat: 0,
3190 htlc_maximum_msat: OptionalField::Present(15_000),
3192 fee_proportional_millionths: 0,
3193 excess_data: Vec::new()
3197 // Attempt to route more than available results in a failure.
3198 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3199 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3200 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3201 } else { panic!(); }
3205 // Now, attempt to route an exact amount we have should be fine.
3206 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3207 assert_eq!(route.paths.len(), 1);
3208 let path = route.paths.last().unwrap();
3209 assert_eq!(path.len(), 2);
3210 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3211 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3214 // Now let's see if routing works if we know only capacity from the UTXO.
3216 // We can't change UTXO capacity on the fly, so we'll disable
3217 // the existing channel and add another one with the capacity we need.
3218 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3220 short_channel_id: 3,
3223 cltv_expiry_delta: 0,
3224 htlc_minimum_msat: 0,
3225 htlc_maximum_msat: OptionalField::Absent,
3227 fee_proportional_millionths: 0,
3228 excess_data: Vec::new()
3231 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3232 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3233 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3234 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3235 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3237 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3238 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3240 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3241 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3242 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3243 short_channel_id: 333,
3246 cltv_expiry_delta: (3 << 4) | 1,
3247 htlc_minimum_msat: 0,
3248 htlc_maximum_msat: OptionalField::Absent,
3250 fee_proportional_millionths: 0,
3251 excess_data: Vec::new()
3253 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3254 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3255 short_channel_id: 333,
3258 cltv_expiry_delta: (3 << 4) | 2,
3259 htlc_minimum_msat: 0,
3260 htlc_maximum_msat: OptionalField::Absent,
3262 fee_proportional_millionths: 0,
3263 excess_data: Vec::new()
3267 // Attempt to route more than available results in a failure.
3268 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3269 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3270 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3271 } else { panic!(); }
3275 // Now, attempt to route an exact amount we have should be fine.
3276 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3277 assert_eq!(route.paths.len(), 1);
3278 let path = route.paths.last().unwrap();
3279 assert_eq!(path.len(), 2);
3280 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3281 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3284 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3285 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3287 short_channel_id: 333,
3290 cltv_expiry_delta: 0,
3291 htlc_minimum_msat: 0,
3292 htlc_maximum_msat: OptionalField::Present(10_000),
3294 fee_proportional_millionths: 0,
3295 excess_data: Vec::new()
3299 // Attempt to route more than available results in a failure.
3300 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3301 &our_id, &payment_params, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3302 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3303 } else { panic!(); }
3307 // Now, attempt to route an exact amount we have should be fine.
3308 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3309 assert_eq!(route.paths.len(), 1);
3310 let path = route.paths.last().unwrap();
3311 assert_eq!(path.len(), 2);
3312 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3313 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3318 fn available_liquidity_last_hop_test() {
3319 // Check that available liquidity properly limits the path even when only
3320 // one of the latter hops is limited.
3321 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3322 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3323 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3324 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3326 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3327 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3328 // Total capacity: 50 sats.
3330 // Disable other potential paths.
3331 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3333 short_channel_id: 2,
3336 cltv_expiry_delta: 0,
3337 htlc_minimum_msat: 0,
3338 htlc_maximum_msat: OptionalField::Present(100_000),
3340 fee_proportional_millionths: 0,
3341 excess_data: Vec::new()
3343 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3344 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3345 short_channel_id: 7,
3348 cltv_expiry_delta: 0,
3349 htlc_minimum_msat: 0,
3350 htlc_maximum_msat: OptionalField::Present(100_000),
3352 fee_proportional_millionths: 0,
3353 excess_data: Vec::new()
3358 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3359 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3360 short_channel_id: 12,
3363 cltv_expiry_delta: 0,
3364 htlc_minimum_msat: 0,
3365 htlc_maximum_msat: OptionalField::Present(100_000),
3367 fee_proportional_millionths: 0,
3368 excess_data: Vec::new()
3370 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3372 short_channel_id: 13,
3375 cltv_expiry_delta: 0,
3376 htlc_minimum_msat: 0,
3377 htlc_maximum_msat: OptionalField::Present(100_000),
3379 fee_proportional_millionths: 0,
3380 excess_data: Vec::new()
3383 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3384 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3385 short_channel_id: 6,
3388 cltv_expiry_delta: 0,
3389 htlc_minimum_msat: 0,
3390 htlc_maximum_msat: OptionalField::Present(50_000),
3392 fee_proportional_millionths: 0,
3393 excess_data: Vec::new()
3395 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3397 short_channel_id: 11,
3400 cltv_expiry_delta: 0,
3401 htlc_minimum_msat: 0,
3402 htlc_maximum_msat: OptionalField::Present(100_000),
3404 fee_proportional_millionths: 0,
3405 excess_data: Vec::new()
3408 // Attempt to route more than available results in a failure.
3409 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3410 &our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3411 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3412 } else { panic!(); }
3416 // Now, attempt to route 49 sats (just a bit below the capacity).
3417 let route = get_route(&our_id, &payment_params, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3418 assert_eq!(route.paths.len(), 1);
3419 let mut total_amount_paid_msat = 0;
3420 for path in &route.paths {
3421 assert_eq!(path.len(), 4);
3422 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3423 total_amount_paid_msat += path.last().unwrap().fee_msat;
3425 assert_eq!(total_amount_paid_msat, 49_000);
3429 // Attempt to route an exact amount is also fine
3430 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3431 assert_eq!(route.paths.len(), 1);
3432 let mut total_amount_paid_msat = 0;
3433 for path in &route.paths {
3434 assert_eq!(path.len(), 4);
3435 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3436 total_amount_paid_msat += path.last().unwrap().fee_msat;
3438 assert_eq!(total_amount_paid_msat, 50_000);
3443 fn ignore_fee_first_hop_test() {
3444 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3445 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3446 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3447 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3449 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3450 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3451 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3452 short_channel_id: 1,
3455 cltv_expiry_delta: 0,
3456 htlc_minimum_msat: 0,
3457 htlc_maximum_msat: OptionalField::Present(100_000),
3458 fee_base_msat: 1_000_000,
3459 fee_proportional_millionths: 0,
3460 excess_data: Vec::new()
3462 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3463 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3464 short_channel_id: 3,
3467 cltv_expiry_delta: 0,
3468 htlc_minimum_msat: 0,
3469 htlc_maximum_msat: OptionalField::Present(50_000),
3471 fee_proportional_millionths: 0,
3472 excess_data: Vec::new()
3476 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3477 assert_eq!(route.paths.len(), 1);
3478 let mut total_amount_paid_msat = 0;
3479 for path in &route.paths {
3480 assert_eq!(path.len(), 2);
3481 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3482 total_amount_paid_msat += path.last().unwrap().fee_msat;
3484 assert_eq!(total_amount_paid_msat, 50_000);
3489 fn simple_mpp_route_test() {
3490 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3491 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3492 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3493 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3495 // We need a route consisting of 3 paths:
3496 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3497 // To achieve this, the amount being transferred should be around
3498 // the total capacity of these 3 paths.
3500 // First, we set limits on these (previously unlimited) channels.
3501 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3503 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3504 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3505 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3506 short_channel_id: 1,
3509 cltv_expiry_delta: 0,
3510 htlc_minimum_msat: 0,
3511 htlc_maximum_msat: OptionalField::Present(100_000),
3513 fee_proportional_millionths: 0,
3514 excess_data: Vec::new()
3516 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3517 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3518 short_channel_id: 3,
3521 cltv_expiry_delta: 0,
3522 htlc_minimum_msat: 0,
3523 htlc_maximum_msat: OptionalField::Present(50_000),
3525 fee_proportional_millionths: 0,
3526 excess_data: Vec::new()
3529 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3530 // (total limit 60).
3531 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3532 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3533 short_channel_id: 12,
3536 cltv_expiry_delta: 0,
3537 htlc_minimum_msat: 0,
3538 htlc_maximum_msat: OptionalField::Present(60_000),
3540 fee_proportional_millionths: 0,
3541 excess_data: Vec::new()
3543 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3545 short_channel_id: 13,
3548 cltv_expiry_delta: 0,
3549 htlc_minimum_msat: 0,
3550 htlc_maximum_msat: OptionalField::Present(60_000),
3552 fee_proportional_millionths: 0,
3553 excess_data: Vec::new()
3556 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3557 // (total capacity 180 sats).
3558 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3560 short_channel_id: 2,
3563 cltv_expiry_delta: 0,
3564 htlc_minimum_msat: 0,
3565 htlc_maximum_msat: OptionalField::Present(200_000),
3567 fee_proportional_millionths: 0,
3568 excess_data: Vec::new()
3570 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3572 short_channel_id: 4,
3575 cltv_expiry_delta: 0,
3576 htlc_minimum_msat: 0,
3577 htlc_maximum_msat: OptionalField::Present(180_000),
3579 fee_proportional_millionths: 0,
3580 excess_data: Vec::new()
3584 // Attempt to route more than available results in a failure.
3585 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3586 &our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3587 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3588 } else { panic!(); }
3592 // Now, attempt to route 250 sats (just a bit below the capacity).
3593 // Our algorithm should provide us with these 3 paths.
3594 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3595 assert_eq!(route.paths.len(), 3);
3596 let mut total_amount_paid_msat = 0;
3597 for path in &route.paths {
3598 assert_eq!(path.len(), 2);
3599 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3600 total_amount_paid_msat += path.last().unwrap().fee_msat;
3602 assert_eq!(total_amount_paid_msat, 250_000);
3606 // Attempt to route an exact amount is also fine
3607 let route = get_route(&our_id, &payment_params, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3608 assert_eq!(route.paths.len(), 3);
3609 let mut total_amount_paid_msat = 0;
3610 for path in &route.paths {
3611 assert_eq!(path.len(), 2);
3612 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3613 total_amount_paid_msat += path.last().unwrap().fee_msat;
3615 assert_eq!(total_amount_paid_msat, 290_000);
3620 fn long_mpp_route_test() {
3621 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3622 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3623 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3624 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3626 // We need a route consisting of 3 paths:
3627 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3628 // Note that these paths overlap (channels 5, 12, 13).
3629 // We will route 300 sats.
3630 // Each path will have 100 sats capacity, those channels which
3631 // are used twice will have 200 sats capacity.
3633 // Disable other potential paths.
3634 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3635 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3636 short_channel_id: 2,
3639 cltv_expiry_delta: 0,
3640 htlc_minimum_msat: 0,
3641 htlc_maximum_msat: OptionalField::Present(100_000),
3643 fee_proportional_millionths: 0,
3644 excess_data: Vec::new()
3646 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3647 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3648 short_channel_id: 7,
3651 cltv_expiry_delta: 0,
3652 htlc_minimum_msat: 0,
3653 htlc_maximum_msat: OptionalField::Present(100_000),
3655 fee_proportional_millionths: 0,
3656 excess_data: Vec::new()
3659 // Path via {node0, node2} is channels {1, 3, 5}.
3660 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3662 short_channel_id: 1,
3665 cltv_expiry_delta: 0,
3666 htlc_minimum_msat: 0,
3667 htlc_maximum_msat: OptionalField::Present(100_000),
3669 fee_proportional_millionths: 0,
3670 excess_data: Vec::new()
3672 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3674 short_channel_id: 3,
3677 cltv_expiry_delta: 0,
3678 htlc_minimum_msat: 0,
3679 htlc_maximum_msat: OptionalField::Present(100_000),
3681 fee_proportional_millionths: 0,
3682 excess_data: Vec::new()
3685 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3686 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3687 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3688 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3689 short_channel_id: 5,
3692 cltv_expiry_delta: 0,
3693 htlc_minimum_msat: 0,
3694 htlc_maximum_msat: OptionalField::Present(200_000),
3696 fee_proportional_millionths: 0,
3697 excess_data: Vec::new()
3700 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3701 // Add 100 sats to the capacities of {12, 13}, because these channels
3702 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3703 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3705 short_channel_id: 12,
3708 cltv_expiry_delta: 0,
3709 htlc_minimum_msat: 0,
3710 htlc_maximum_msat: OptionalField::Present(200_000),
3712 fee_proportional_millionths: 0,
3713 excess_data: Vec::new()
3715 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3716 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3717 short_channel_id: 13,
3720 cltv_expiry_delta: 0,
3721 htlc_minimum_msat: 0,
3722 htlc_maximum_msat: OptionalField::Present(200_000),
3724 fee_proportional_millionths: 0,
3725 excess_data: Vec::new()
3728 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3729 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3730 short_channel_id: 6,
3733 cltv_expiry_delta: 0,
3734 htlc_minimum_msat: 0,
3735 htlc_maximum_msat: OptionalField::Present(100_000),
3737 fee_proportional_millionths: 0,
3738 excess_data: Vec::new()
3740 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3741 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3742 short_channel_id: 11,
3745 cltv_expiry_delta: 0,
3746 htlc_minimum_msat: 0,
3747 htlc_maximum_msat: OptionalField::Present(100_000),
3749 fee_proportional_millionths: 0,
3750 excess_data: Vec::new()
3753 // Path via {node7, node2} is channels {12, 13, 5}.
3754 // We already limited them to 200 sats (they are used twice for 100 sats).
3755 // Nothing to do here.
3758 // Attempt to route more than available results in a failure.
3759 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3760 &our_id, &payment_params, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3761 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3762 } else { panic!(); }
3766 // Now, attempt to route 300 sats (exact amount we can route).
3767 // Our algorithm should provide us with these 3 paths, 100 sats each.
3768 let route = get_route(&our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3769 assert_eq!(route.paths.len(), 3);
3771 let mut total_amount_paid_msat = 0;
3772 for path in &route.paths {
3773 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3774 total_amount_paid_msat += path.last().unwrap().fee_msat;
3776 assert_eq!(total_amount_paid_msat, 300_000);
3782 fn mpp_cheaper_route_test() {
3783 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3784 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3785 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3786 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3788 // This test checks that if we have two cheaper paths and one more expensive path,
3789 // so that liquidity-wise any 2 of 3 combination is sufficient,
3790 // two cheaper paths will be taken.
3791 // These paths have equal available liquidity.
3793 // We need a combination of 3 paths:
3794 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3795 // Note that these paths overlap (channels 5, 12, 13).
3796 // Each path will have 100 sats capacity, those channels which
3797 // are used twice will have 200 sats capacity.
3799 // Disable other potential paths.
3800 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3802 short_channel_id: 2,
3805 cltv_expiry_delta: 0,
3806 htlc_minimum_msat: 0,
3807 htlc_maximum_msat: OptionalField::Present(100_000),
3809 fee_proportional_millionths: 0,
3810 excess_data: Vec::new()
3812 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3814 short_channel_id: 7,
3817 cltv_expiry_delta: 0,
3818 htlc_minimum_msat: 0,
3819 htlc_maximum_msat: OptionalField::Present(100_000),
3821 fee_proportional_millionths: 0,
3822 excess_data: Vec::new()
3825 // Path via {node0, node2} is channels {1, 3, 5}.
3826 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3828 short_channel_id: 1,
3831 cltv_expiry_delta: 0,
3832 htlc_minimum_msat: 0,
3833 htlc_maximum_msat: OptionalField::Present(100_000),
3835 fee_proportional_millionths: 0,
3836 excess_data: Vec::new()
3838 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3840 short_channel_id: 3,
3843 cltv_expiry_delta: 0,
3844 htlc_minimum_msat: 0,
3845 htlc_maximum_msat: OptionalField::Present(100_000),
3847 fee_proportional_millionths: 0,
3848 excess_data: Vec::new()
3851 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3852 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3853 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3854 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3855 short_channel_id: 5,
3858 cltv_expiry_delta: 0,
3859 htlc_minimum_msat: 0,
3860 htlc_maximum_msat: OptionalField::Present(200_000),
3862 fee_proportional_millionths: 0,
3863 excess_data: Vec::new()
3866 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3867 // Add 100 sats to the capacities of {12, 13}, because these channels
3868 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3869 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3870 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3871 short_channel_id: 12,
3874 cltv_expiry_delta: 0,
3875 htlc_minimum_msat: 0,
3876 htlc_maximum_msat: OptionalField::Present(200_000),
3878 fee_proportional_millionths: 0,
3879 excess_data: Vec::new()
3881 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3882 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3883 short_channel_id: 13,
3886 cltv_expiry_delta: 0,
3887 htlc_minimum_msat: 0,
3888 htlc_maximum_msat: OptionalField::Present(200_000),
3890 fee_proportional_millionths: 0,
3891 excess_data: Vec::new()
3894 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3895 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3896 short_channel_id: 6,
3899 cltv_expiry_delta: 0,
3900 htlc_minimum_msat: 0,
3901 htlc_maximum_msat: OptionalField::Present(100_000),
3902 fee_base_msat: 1_000,
3903 fee_proportional_millionths: 0,
3904 excess_data: Vec::new()
3906 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3907 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3908 short_channel_id: 11,
3911 cltv_expiry_delta: 0,
3912 htlc_minimum_msat: 0,
3913 htlc_maximum_msat: OptionalField::Present(100_000),
3915 fee_proportional_millionths: 0,
3916 excess_data: Vec::new()
3919 // Path via {node7, node2} is channels {12, 13, 5}.
3920 // We already limited them to 200 sats (they are used twice for 100 sats).
3921 // Nothing to do here.
3924 // Now, attempt to route 180 sats.
3925 // Our algorithm should provide us with these 2 paths.
3926 let route = get_route(&our_id, &payment_params, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3927 assert_eq!(route.paths.len(), 2);
3929 let mut total_value_transferred_msat = 0;
3930 let mut total_paid_msat = 0;
3931 for path in &route.paths {
3932 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3933 total_value_transferred_msat += path.last().unwrap().fee_msat;
3935 total_paid_msat += hop.fee_msat;
3938 // If we paid fee, this would be higher.
3939 assert_eq!(total_value_transferred_msat, 180_000);
3940 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3941 assert_eq!(total_fees_paid, 0);
3946 fn fees_on_mpp_route_test() {
3947 // This test makes sure that MPP algorithm properly takes into account
3948 // fees charged on the channels, by making the fees impactful:
3949 // if the fee is not properly accounted for, the behavior is different.
3950 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3951 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3952 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3953 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3955 // We need a route consisting of 2 paths:
3956 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3957 // We will route 200 sats, Each path will have 100 sats capacity.
3959 // This test is not particularly stable: e.g.,
3960 // there's a way to route via {node0, node2, node4}.
3961 // It works while pathfinding is deterministic, but can be broken otherwise.
3962 // It's fine to ignore this concern for now.
3964 // Disable other potential paths.
3965 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3967 short_channel_id: 2,
3970 cltv_expiry_delta: 0,
3971 htlc_minimum_msat: 0,
3972 htlc_maximum_msat: OptionalField::Present(100_000),
3974 fee_proportional_millionths: 0,
3975 excess_data: Vec::new()
3978 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3979 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3980 short_channel_id: 7,
3983 cltv_expiry_delta: 0,
3984 htlc_minimum_msat: 0,
3985 htlc_maximum_msat: OptionalField::Present(100_000),
3987 fee_proportional_millionths: 0,
3988 excess_data: Vec::new()
3991 // Path via {node0, node2} is channels {1, 3, 5}.
3992 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3993 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3994 short_channel_id: 1,
3997 cltv_expiry_delta: 0,
3998 htlc_minimum_msat: 0,
3999 htlc_maximum_msat: OptionalField::Present(100_000),
4001 fee_proportional_millionths: 0,
4002 excess_data: Vec::new()
4004 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4006 short_channel_id: 3,
4009 cltv_expiry_delta: 0,
4010 htlc_minimum_msat: 0,
4011 htlc_maximum_msat: OptionalField::Present(100_000),
4013 fee_proportional_millionths: 0,
4014 excess_data: Vec::new()
4017 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4018 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4020 short_channel_id: 5,
4023 cltv_expiry_delta: 0,
4024 htlc_minimum_msat: 0,
4025 htlc_maximum_msat: OptionalField::Present(100_000),
4027 fee_proportional_millionths: 0,
4028 excess_data: Vec::new()
4031 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4032 // All channels should be 100 sats capacity. But for the fee experiment,
4033 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4034 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4035 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4036 // so no matter how large are other channels,
4037 // the whole path will be limited by 100 sats with just these 2 conditions:
4038 // - channel 12 capacity is 250 sats
4039 // - fee for channel 6 is 150 sats
4040 // Let's test this by enforcing these 2 conditions and removing other limits.
4041 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4042 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4043 short_channel_id: 12,
4046 cltv_expiry_delta: 0,
4047 htlc_minimum_msat: 0,
4048 htlc_maximum_msat: OptionalField::Present(250_000),
4050 fee_proportional_millionths: 0,
4051 excess_data: Vec::new()
4053 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4054 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4055 short_channel_id: 13,
4058 cltv_expiry_delta: 0,
4059 htlc_minimum_msat: 0,
4060 htlc_maximum_msat: OptionalField::Absent,
4062 fee_proportional_millionths: 0,
4063 excess_data: Vec::new()
4066 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4067 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4068 short_channel_id: 6,
4071 cltv_expiry_delta: 0,
4072 htlc_minimum_msat: 0,
4073 htlc_maximum_msat: OptionalField::Absent,
4074 fee_base_msat: 150_000,
4075 fee_proportional_millionths: 0,
4076 excess_data: Vec::new()
4078 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080 short_channel_id: 11,
4083 cltv_expiry_delta: 0,
4084 htlc_minimum_msat: 0,
4085 htlc_maximum_msat: OptionalField::Absent,
4087 fee_proportional_millionths: 0,
4088 excess_data: Vec::new()
4092 // Attempt to route more than available results in a failure.
4093 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4094 &our_id, &payment_params, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4095 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4096 } else { panic!(); }
4100 // Now, attempt to route 200 sats (exact amount we can route).
4101 let route = get_route(&our_id, &payment_params, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4102 assert_eq!(route.paths.len(), 2);
4104 let mut total_amount_paid_msat = 0;
4105 for path in &route.paths {
4106 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4107 total_amount_paid_msat += path.last().unwrap().fee_msat;
4109 assert_eq!(total_amount_paid_msat, 200_000);
4110 assert_eq!(route.get_total_fees(), 150_000);
4115 fn mpp_with_last_hops() {
4116 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4117 // via a single last-hop route hint, we'd fail to route if we first collected routes
4118 // totaling close but not quite enough to fund the full payment.
4120 // This was because we considered last-hop hints to have exactly the sought payment amount
4121 // instead of the amount we were trying to collect, needlessly limiting our path searching
4122 // at the very first hop.
4124 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4125 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4126 // to only have the remaining to-collect amount in available liquidity.
4128 // This bug appeared in production in some specific channel configurations.
4129 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4130 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4131 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4132 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4133 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4134 src_node_id: nodes[2],
4135 short_channel_id: 42,
4136 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4137 cltv_expiry_delta: 42,
4138 htlc_minimum_msat: None,
4139 htlc_maximum_msat: None,
4142 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4143 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4144 // would first use the no-fee route and then fail to find a path along the second route as
4145 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4146 // under 5% of our payment amount.
4147 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4148 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4149 short_channel_id: 1,
4152 cltv_expiry_delta: (5 << 4) | 5,
4153 htlc_minimum_msat: 0,
4154 htlc_maximum_msat: OptionalField::Present(99_000),
4155 fee_base_msat: u32::max_value(),
4156 fee_proportional_millionths: u32::max_value(),
4157 excess_data: Vec::new()
4159 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4160 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4161 short_channel_id: 2,
4164 cltv_expiry_delta: (5 << 4) | 3,
4165 htlc_minimum_msat: 0,
4166 htlc_maximum_msat: OptionalField::Present(99_000),
4167 fee_base_msat: u32::max_value(),
4168 fee_proportional_millionths: u32::max_value(),
4169 excess_data: Vec::new()
4171 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4173 short_channel_id: 4,
4176 cltv_expiry_delta: (4 << 4) | 1,
4177 htlc_minimum_msat: 0,
4178 htlc_maximum_msat: OptionalField::Absent,
4180 fee_proportional_millionths: 0,
4181 excess_data: Vec::new()
4183 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4185 short_channel_id: 13,
4187 flags: 0|2, // Channel disabled
4188 cltv_expiry_delta: (13 << 4) | 1,
4189 htlc_minimum_msat: 0,
4190 htlc_maximum_msat: OptionalField::Absent,
4192 fee_proportional_millionths: 2000000,
4193 excess_data: Vec::new()
4196 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4198 let route = get_route(&our_id, &payment_params, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4199 assert_eq!(route.paths.len(), 2);
4200 // Paths are somewhat randomly ordered, but:
4201 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4202 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4203 assert_eq!(route.paths[0][0].short_channel_id, 2);
4204 assert_eq!(route.paths[0][0].fee_msat, 1);
4205 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4206 assert_eq!(route.paths[1][0].short_channel_id, 1);
4207 assert_eq!(route.paths[1][0].fee_msat, 0);
4208 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4209 assert_eq!(route.get_total_fees(), 1);
4210 assert_eq!(route.get_total_amount(), 100_000);
4214 fn drop_lowest_channel_mpp_route_test() {
4215 // This test checks that low-capacity channel is dropped when after
4216 // path finding we realize that we found more capacity than we need.
4217 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4218 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4219 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4220 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4222 // We need a route consisting of 3 paths:
4223 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4225 // The first and the second paths should be sufficient, but the third should be
4226 // cheaper, so that we select it but drop later.
4228 // First, we set limits on these (previously unlimited) channels.
4229 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4231 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4232 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4234 short_channel_id: 1,
4237 cltv_expiry_delta: 0,
4238 htlc_minimum_msat: 0,
4239 htlc_maximum_msat: OptionalField::Present(100_000),
4241 fee_proportional_millionths: 0,
4242 excess_data: Vec::new()
4244 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4245 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4246 short_channel_id: 3,
4249 cltv_expiry_delta: 0,
4250 htlc_minimum_msat: 0,
4251 htlc_maximum_msat: OptionalField::Present(50_000),
4253 fee_proportional_millionths: 0,
4254 excess_data: Vec::new()
4257 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4258 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260 short_channel_id: 12,
4263 cltv_expiry_delta: 0,
4264 htlc_minimum_msat: 0,
4265 htlc_maximum_msat: OptionalField::Present(60_000),
4267 fee_proportional_millionths: 0,
4268 excess_data: Vec::new()
4270 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4272 short_channel_id: 13,
4275 cltv_expiry_delta: 0,
4276 htlc_minimum_msat: 0,
4277 htlc_maximum_msat: OptionalField::Present(60_000),
4279 fee_proportional_millionths: 0,
4280 excess_data: Vec::new()
4283 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4284 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4286 short_channel_id: 2,
4289 cltv_expiry_delta: 0,
4290 htlc_minimum_msat: 0,
4291 htlc_maximum_msat: OptionalField::Present(20_000),
4293 fee_proportional_millionths: 0,
4294 excess_data: Vec::new()
4296 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4297 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4298 short_channel_id: 4,
4301 cltv_expiry_delta: 0,
4302 htlc_minimum_msat: 0,
4303 htlc_maximum_msat: OptionalField::Present(20_000),
4305 fee_proportional_millionths: 0,
4306 excess_data: Vec::new()
4310 // Attempt to route more than available results in a failure.
4311 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4312 &our_id, &payment_params, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4313 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4314 } else { panic!(); }
4318 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4319 // Our algorithm should provide us with these 3 paths.
4320 let route = get_route(&our_id, &payment_params, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4321 assert_eq!(route.paths.len(), 3);
4322 let mut total_amount_paid_msat = 0;
4323 for path in &route.paths {
4324 assert_eq!(path.len(), 2);
4325 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4326 total_amount_paid_msat += path.last().unwrap().fee_msat;
4328 assert_eq!(total_amount_paid_msat, 125_000);
4332 // Attempt to route without the last small cheap channel
4333 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4334 assert_eq!(route.paths.len(), 2);
4335 let mut total_amount_paid_msat = 0;
4336 for path in &route.paths {
4337 assert_eq!(path.len(), 2);
4338 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4339 total_amount_paid_msat += path.last().unwrap().fee_msat;
4341 assert_eq!(total_amount_paid_msat, 90_000);
4346 fn min_criteria_consistency() {
4347 // Test that we don't use an inconsistent metric between updating and walking nodes during
4348 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4349 // was updated with a different criterion from the heap sorting, resulting in loops in
4350 // calculated paths. We test for that specific case here.
4352 // We construct a network that looks like this:
4354 // node2 -1(3)2- node3
4358 // node1 -1(5)2- node4 -1(1)2- node6
4364 // We create a loop on the side of our real path - our destination is node 6, with a
4365 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4366 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4367 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4368 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4369 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4370 // "previous hop" being set to node 3, creating a loop in the path.
4371 let secp_ctx = Secp256k1::new();
4372 let logger = Arc::new(test_utils::TestLogger::new());
4373 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4374 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4375 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4376 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4377 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4379 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4380 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4382 short_channel_id: 6,
4385 cltv_expiry_delta: (6 << 4) | 0,
4386 htlc_minimum_msat: 0,
4387 htlc_maximum_msat: OptionalField::Absent,
4389 fee_proportional_millionths: 0,
4390 excess_data: Vec::new()
4392 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4394 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4395 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4397 short_channel_id: 5,
4400 cltv_expiry_delta: (5 << 4) | 0,
4401 htlc_minimum_msat: 0,
4402 htlc_maximum_msat: OptionalField::Absent,
4404 fee_proportional_millionths: 0,
4405 excess_data: Vec::new()
4407 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4409 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4412 short_channel_id: 4,
4415 cltv_expiry_delta: (4 << 4) | 0,
4416 htlc_minimum_msat: 0,
4417 htlc_maximum_msat: OptionalField::Absent,
4419 fee_proportional_millionths: 0,
4420 excess_data: Vec::new()
4422 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4424 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4425 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4426 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4427 short_channel_id: 3,
4430 cltv_expiry_delta: (3 << 4) | 0,
4431 htlc_minimum_msat: 0,
4432 htlc_maximum_msat: OptionalField::Absent,
4434 fee_proportional_millionths: 0,
4435 excess_data: Vec::new()
4437 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4439 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4440 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4441 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4442 short_channel_id: 2,
4445 cltv_expiry_delta: (2 << 4) | 0,
4446 htlc_minimum_msat: 0,
4447 htlc_maximum_msat: OptionalField::Absent,
4449 fee_proportional_millionths: 0,
4450 excess_data: Vec::new()
4453 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4454 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4455 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4456 short_channel_id: 1,
4459 cltv_expiry_delta: (1 << 4) | 0,
4460 htlc_minimum_msat: 100,
4461 htlc_maximum_msat: OptionalField::Absent,
4463 fee_proportional_millionths: 0,
4464 excess_data: Vec::new()
4466 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4469 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4470 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4471 assert_eq!(route.paths.len(), 1);
4472 assert_eq!(route.paths[0].len(), 3);
4474 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4475 assert_eq!(route.paths[0][0].short_channel_id, 6);
4476 assert_eq!(route.paths[0][0].fee_msat, 100);
4477 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4478 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4479 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4481 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4482 assert_eq!(route.paths[0][1].short_channel_id, 5);
4483 assert_eq!(route.paths[0][1].fee_msat, 0);
4484 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4485 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4486 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4488 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4489 assert_eq!(route.paths[0][2].short_channel_id, 1);
4490 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4491 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4492 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4493 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4499 fn exact_fee_liquidity_limit() {
4500 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4501 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4502 // we calculated fees on a higher value, resulting in us ignoring such paths.
4503 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4504 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4505 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4506 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4508 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4510 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4512 short_channel_id: 2,
4515 cltv_expiry_delta: 0,
4516 htlc_minimum_msat: 0,
4517 htlc_maximum_msat: OptionalField::Present(85_000),
4519 fee_proportional_millionths: 0,
4520 excess_data: Vec::new()
4523 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4524 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4525 short_channel_id: 12,
4528 cltv_expiry_delta: (4 << 4) | 1,
4529 htlc_minimum_msat: 0,
4530 htlc_maximum_msat: OptionalField::Present(270_000),
4532 fee_proportional_millionths: 1000000,
4533 excess_data: Vec::new()
4537 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4538 // 200% fee charged channel 13 in the 1-to-2 direction.
4539 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4540 assert_eq!(route.paths.len(), 1);
4541 assert_eq!(route.paths[0].len(), 2);
4543 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4544 assert_eq!(route.paths[0][0].short_channel_id, 12);
4545 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4546 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4547 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4548 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4550 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4551 assert_eq!(route.paths[0][1].short_channel_id, 13);
4552 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4553 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4554 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4555 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4560 fn htlc_max_reduction_below_min() {
4561 // Test that if, while walking the graph, we reduce the value being sent to meet an
4562 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4563 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4564 // resulting in us thinking there is no possible path, even if other paths exist.
4565 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4566 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4567 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4568 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4570 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4571 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4572 // then try to send 90_000.
4573 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4574 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4575 short_channel_id: 2,
4578 cltv_expiry_delta: 0,
4579 htlc_minimum_msat: 0,
4580 htlc_maximum_msat: OptionalField::Present(80_000),
4582 fee_proportional_millionths: 0,
4583 excess_data: Vec::new()
4585 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4586 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4587 short_channel_id: 4,
4590 cltv_expiry_delta: (4 << 4) | 1,
4591 htlc_minimum_msat: 90_000,
4592 htlc_maximum_msat: OptionalField::Absent,
4594 fee_proportional_millionths: 0,
4595 excess_data: Vec::new()
4599 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4600 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4601 // expensive) channels 12-13 path.
4602 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4603 assert_eq!(route.paths.len(), 1);
4604 assert_eq!(route.paths[0].len(), 2);
4606 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4607 assert_eq!(route.paths[0][0].short_channel_id, 12);
4608 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4609 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4610 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4611 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4613 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4614 assert_eq!(route.paths[0][1].short_channel_id, 13);
4615 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4616 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4617 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4618 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4623 fn multiple_direct_first_hops() {
4624 // Previously we'd only ever considered one first hop path per counterparty.
4625 // However, as we don't restrict users to one channel per peer, we really need to support
4626 // looking at all first hop paths.
4627 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4628 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4629 // route over multiple channels with the same first hop.
4630 let secp_ctx = Secp256k1::new();
4631 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4632 let logger = Arc::new(test_utils::TestLogger::new());
4633 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4634 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4635 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4638 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4639 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4640 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4641 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4642 assert_eq!(route.paths.len(), 1);
4643 assert_eq!(route.paths[0].len(), 1);
4645 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4646 assert_eq!(route.paths[0][0].short_channel_id, 3);
4647 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4650 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4651 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4652 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4653 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4654 assert_eq!(route.paths.len(), 2);
4655 assert_eq!(route.paths[0].len(), 1);
4656 assert_eq!(route.paths[1].len(), 1);
4658 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4659 assert_eq!(route.paths[0][0].short_channel_id, 3);
4660 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4662 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4663 assert_eq!(route.paths[1][0].short_channel_id, 2);
4664 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4669 fn prefers_shorter_route_with_higher_fees() {
4670 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4671 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4672 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4674 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4675 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4676 let route = get_route(
4677 &our_id, &payment_params, &network_graph, None, 100, 42,
4678 Arc::clone(&logger), &scorer
4680 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4682 assert_eq!(route.get_total_fees(), 100);
4683 assert_eq!(route.get_total_amount(), 100);
4684 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4686 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4687 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4688 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4689 let route = get_route(
4690 &our_id, &payment_params, &network_graph, None, 100, 42,
4691 Arc::clone(&logger), &scorer
4693 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4695 assert_eq!(route.get_total_fees(), 300);
4696 assert_eq!(route.get_total_amount(), 100);
4697 assert_eq!(path, vec![2, 4, 7, 10]);
4700 struct BadChannelScorer {
4701 short_channel_id: u64,
4705 impl Writeable for BadChannelScorer {
4706 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4708 impl Score for BadChannelScorer {
4709 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4710 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4713 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4714 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4717 struct BadNodeScorer {
4722 impl Writeable for BadNodeScorer {
4723 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4726 impl Score for BadNodeScorer {
4727 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4728 if *target == self.node_id { u64::max_value() } else { 0 }
4731 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4732 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4736 fn avoids_routing_through_bad_channels_and_nodes() {
4737 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4738 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4739 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4741 // A path to nodes[6] exists when no penalties are applied to any channel.
4742 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4743 let route = get_route(
4744 &our_id, &payment_params, &network_graph, None, 100, 42,
4745 Arc::clone(&logger), &scorer
4747 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4749 assert_eq!(route.get_total_fees(), 100);
4750 assert_eq!(route.get_total_amount(), 100);
4751 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4753 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4754 let scorer = BadChannelScorer { short_channel_id: 6 };
4755 let route = get_route(
4756 &our_id, &payment_params, &network_graph, None, 100, 42,
4757 Arc::clone(&logger), &scorer
4759 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4761 assert_eq!(route.get_total_fees(), 300);
4762 assert_eq!(route.get_total_amount(), 100);
4763 assert_eq!(path, vec![2, 4, 7, 10]);
4765 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4766 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4768 &our_id, &payment_params, &network_graph, None, 100, 42,
4769 Arc::clone(&logger), &scorer
4771 Err(LightningError { err, .. } ) => {
4772 assert_eq!(err, "Failed to find a path to the given destination");
4774 Ok(_) => panic!("Expected error"),
4779 fn total_fees_single_path() {
4783 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4784 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4785 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4788 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4789 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4790 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4793 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4794 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4795 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4798 payment_params: None,
4801 assert_eq!(route.get_total_fees(), 250);
4802 assert_eq!(route.get_total_amount(), 225);
4806 fn total_fees_multi_path() {
4810 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4811 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4812 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4815 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4816 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4817 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4821 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4822 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4823 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4826 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4827 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4828 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4831 payment_params: None,
4834 assert_eq!(route.get_total_fees(), 200);
4835 assert_eq!(route.get_total_amount(), 300);
4839 fn total_empty_route_no_panic() {
4840 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4841 // would both panic if the route was completely empty. We test to ensure they return 0
4842 // here, even though its somewhat nonsensical as a route.
4843 let route = Route { paths: Vec::new(), payment_params: None };
4845 assert_eq!(route.get_total_fees(), 0);
4846 assert_eq!(route.get_total_amount(), 0);
4850 fn limits_total_cltv_delta() {
4851 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4852 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4854 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4856 // Make sure that generally there is at least one route available
4857 let feasible_max_total_cltv_delta = 1008;
4858 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4859 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
4860 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
4861 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4862 assert_ne!(path.len(), 0);
4864 // But not if we exclude all paths on the basis of their accumulated CLTV delta
4865 let fail_max_total_cltv_delta = 23;
4866 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4867 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
4868 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer)
4870 Err(LightningError { err, .. } ) => {
4871 assert_eq!(err, "Failed to find a path to the given destination");
4873 Ok(_) => panic!("Expected error"),
4877 #[cfg(not(feature = "no-std"))]
4878 pub(super) fn random_init_seed() -> u64 {
4879 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4880 use core::hash::{BuildHasher, Hasher};
4881 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4882 println!("Using seed of {}", seed);
4885 #[cfg(not(feature = "no-std"))]
4886 use util::ser::Readable;
4889 #[cfg(not(feature = "no-std"))]
4890 fn generate_routes() {
4891 let mut d = match super::test_utils::get_route_file() {
4898 let graph = NetworkGraph::read(&mut d).unwrap();
4899 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4901 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4902 let mut seed = random_init_seed() as usize;
4903 let nodes = graph.read_only().nodes().clone();
4904 'load_endpoints: for _ in 0..10 {
4906 seed = seed.overflowing_mul(0xdeadbeef).0;
4907 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4908 seed = seed.overflowing_mul(0xdeadbeef).0;
4909 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4910 let payment_params = PaymentParameters::from_node_id(dst);
4911 let amt = seed as u64 % 200_000_000;
4912 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4913 continue 'load_endpoints;
4920 #[cfg(not(feature = "no-std"))]
4921 fn generate_routes_mpp() {
4922 let mut d = match super::test_utils::get_route_file() {
4929 let graph = NetworkGraph::read(&mut d).unwrap();
4930 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4932 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4933 let mut seed = random_init_seed() as usize;
4934 let nodes = graph.read_only().nodes().clone();
4935 'load_endpoints: for _ in 0..10 {
4937 seed = seed.overflowing_mul(0xdeadbeef).0;
4938 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4939 seed = seed.overflowing_mul(0xdeadbeef).0;
4940 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4941 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
4942 let amt = seed as u64 % 200_000_000;
4943 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4944 continue 'load_endpoints;
4951 #[cfg(all(test, not(feature = "no-std")))]
4952 pub(crate) mod test_utils {
4954 /// Tries to open a network graph file, or panics with a URL to fetch it.
4955 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4956 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4957 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4958 .or_else(|_| { // Fall back to guessing based on the binary location
4959 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4960 let mut path = std::env::current_exe().unwrap();
4961 path.pop(); // lightning-...
4963 path.pop(); // debug
4964 path.pop(); // target
4965 path.push("lightning");
4966 path.push("net_graph-2021-05-31.bin");
4967 eprintln!("{}", path.to_str().unwrap());
4970 .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");
4971 #[cfg(require_route_graph_test)]
4972 return Ok(res.unwrap());
4973 #[cfg(not(require_route_graph_test))]
4978 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4981 use bitcoin::hashes::Hash;
4982 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
4983 use chain::transaction::OutPoint;
4984 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
4985 use ln::features::{InitFeatures, InvoiceFeatures};
4986 use routing::scoring::Scorer;
4987 use util::logger::{Logger, Record};
4991 struct DummyLogger {}
4992 impl Logger for DummyLogger {
4993 fn log(&self, _record: &Record) {}
4996 struct ZeroPenaltyScorer;
4997 impl Score for ZeroPenaltyScorer {
4998 fn channel_penalty_msat(
4999 &self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId
5001 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5002 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5005 fn read_network_graph() -> NetworkGraph {
5006 let mut d = test_utils::get_route_file().unwrap();
5007 NetworkGraph::read(&mut d).unwrap()
5010 fn payer_pubkey() -> PublicKey {
5011 let secp_ctx = Secp256k1::new();
5012 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5016 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5018 channel_id: [0; 32],
5019 counterparty: ChannelCounterparty {
5020 features: InitFeatures::known(),
5022 unspendable_punishment_reserve: 0,
5023 forwarding_info: None,
5025 funding_txo: Some(OutPoint {
5026 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5028 short_channel_id: Some(1),
5029 channel_value_satoshis: 10_000_000,
5031 balance_msat: 10_000_000,
5032 outbound_capacity_msat: 10_000_000,
5033 inbound_capacity_msat: 0,
5034 unspendable_punishment_reserve: None,
5035 confirmations_required: None,
5036 force_close_spend_delay: None,
5038 is_funding_locked: true,
5045 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5046 let network_graph = read_network_graph();
5047 let scorer = ZeroPenaltyScorer;
5048 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5052 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5053 let network_graph = read_network_graph();
5054 let scorer = ZeroPenaltyScorer;
5055 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5059 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5060 let network_graph = read_network_graph();
5061 let scorer = Scorer::default();
5062 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5066 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5067 let network_graph = read_network_graph();
5068 let scorer = Scorer::default();
5069 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5072 fn generate_routes<S: Score>(
5073 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5075 let nodes = graph.read_only().nodes().clone();
5076 let payer = payer_pubkey();
5078 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5079 let mut routes = Vec::new();
5080 let mut route_endpoints = Vec::new();
5081 let mut seed: usize = 0xdeadbeef;
5082 'load_endpoints: for _ in 0..100 {
5085 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5087 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5088 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5089 let first_hop = first_hop(src);
5090 let amt = seed as u64 % 1_000_000;
5091 if let Ok(route) = get_route(&payer, ¶ms, &graph, Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer) {
5093 route_endpoints.push((first_hop, params, amt));
5094 continue 'load_endpoints;
5099 // ...and seed the scorer with success and failure data...
5100 for route in routes {
5101 let amount = route.get_total_amount();
5102 if amount < 250_000 {
5103 for path in route.paths {
5104 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5106 } else if amount > 750_000 {
5107 for path in route.paths {
5108 let short_channel_id = path[path.len() / 2].short_channel_id;
5109 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5114 // ...then benchmark finding paths between the nodes we learned.
5117 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5118 assert!(get_route(&payer, params, &graph, Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer).is_ok());