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, '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.inner().channel().features.clone(),
380 CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
384 fn cltv_expiry_delta(&self) -> u32 {
386 CandidateRouteHop::FirstHop { .. } => 0,
387 CandidateRouteHop::PublicHop { info, .. } => {
388 info.inner().direction().unwrap().cltv_expiry_delta as u32
390 CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
394 fn htlc_minimum_msat(&self) -> u64 {
396 CandidateRouteHop::FirstHop { .. } => 0,
397 CandidateRouteHop::PublicHop { info, .. } => {
398 info.inner().direction().unwrap().htlc_minimum_msat
400 CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
404 fn fees(&self) -> RoutingFees {
406 CandidateRouteHop::FirstHop { .. } => RoutingFees {
407 base_msat: 0, proportional_millionths: 0,
409 CandidateRouteHop::PublicHop { info, .. } => info.inner().direction().unwrap().fees,
410 CandidateRouteHop::PrivateHop { hint } => hint.fees,
414 fn effective_capacity(&self) -> EffectiveCapacity {
416 CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
417 liquidity_msat: details.outbound_capacity_msat,
419 CandidateRouteHop::PublicHop { info, .. } => info.inner().effective_capacity(),
420 CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
425 /// It's useful to keep track of the hops associated with the fees required to use them,
426 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
427 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
428 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
429 #[derive(Clone, Debug)]
430 struct PathBuildingHop<'a> {
431 // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
432 // is a larger refactor and will require careful performance analysis.
434 candidate: CandidateRouteHop<'a>,
437 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
438 src_lowest_inbound_fees: RoutingFees,
439 /// All the fees paid *after* this channel on the way to the destination
440 next_hops_fee_msat: u64,
441 /// Fee paid for the use of the current channel (see candidate.fees()).
442 /// The value will be actually deducted from the counterparty balance on the previous link.
443 hop_use_fee_msat: u64,
444 /// Used to compare channels when choosing the for routing.
445 /// Includes paying for the use of a hop and the following hops, as well as
446 /// an estimated cost of reaching this hop.
447 /// Might get stale when fees are recomputed. Primarily for internal use.
449 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
450 /// walk and may be invalid thereafter.
451 path_htlc_minimum_msat: u64,
452 /// All penalties incurred from this channel on the way to the destination, as calculated using
454 path_penalty_msat: u64,
455 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
456 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
457 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
458 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
459 /// avoid processing them again.
461 #[cfg(any(test, feature = "fuzztarget"))]
462 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
463 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
464 // value_contribution_msat, which requires tracking it here. See comments below where it is
465 // used for more info.
466 value_contribution_msat: u64,
469 // Instantiated with a list of hops with correct data in them collected during path finding,
470 // an instance of this struct should be further modified only via given methods.
472 struct PaymentPath<'a> {
473 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
476 impl<'a> PaymentPath<'a> {
477 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
478 fn get_value_msat(&self) -> u64 {
479 self.hops.last().unwrap().0.fee_msat
482 fn get_total_fee_paid_msat(&self) -> u64 {
483 if self.hops.len() < 1 {
487 // Can't use next_hops_fee_msat because it gets outdated.
488 for (i, (hop, _)) in self.hops.iter().enumerate() {
489 if i != self.hops.len() - 1 {
490 result += hop.fee_msat;
496 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
497 // to change fees may result in an inconsistency.
499 // Sometimes we call this function right after constructing a path which is inconsistent in
500 // that it the value being transferred has decreased while we were doing path finding, leading
501 // to the fees being paid not lining up with the actual limits.
503 // Note that this function is not aware of the available_liquidity limit, and thus does not
504 // support increasing the value being transferred.
505 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
506 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
508 let mut total_fee_paid_msat = 0 as u64;
509 for i in (0..self.hops.len()).rev() {
510 let last_hop = i == self.hops.len() - 1;
512 // For non-last-hop, this value will represent the fees paid on the current hop. It
513 // will consist of the fees for the use of the next hop, and extra fees to match
514 // htlc_minimum_msat of the current channel. Last hop is handled separately.
515 let mut cur_hop_fees_msat = 0;
517 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
520 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
521 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
522 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
523 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
524 // set it too high just to maliciously take more fees by exploiting this
525 // match htlc_minimum_msat logic.
526 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
527 if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
528 // Note that there is a risk that *previous hops* (those closer to us, as we go
529 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
531 // This might make us end up with a broken route, although this should be super-rare
532 // in practice, both because of how healthy channels look like, and how we pick
533 // channels in add_entry.
534 // Also, this can't be exploited more heavily than *announce a free path and fail
536 cur_hop_transferred_amount_msat += extra_fees_msat;
537 total_fee_paid_msat += extra_fees_msat;
538 cur_hop_fees_msat += extra_fees_msat;
542 // Final hop is a special case: it usually has just value_msat (by design), but also
543 // it still could overpay for the htlc_minimum_msat.
544 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
546 // Propagate updated fees for the use of the channels to one hop back, where they
547 // will be actually paid (fee_msat). The last hop is handled above separately.
548 cur_hop.fee_msat = cur_hop_fees_msat;
551 // Fee for the use of the current hop which will be deducted on the previous hop.
552 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
553 // this channel is free for us.
555 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
556 cur_hop.hop_use_fee_msat = new_fee;
557 total_fee_paid_msat += new_fee;
559 // It should not be possible because this function is called only to reduce the
560 // value. In that case, compute_fee was already called with the same fees for
561 // larger amount and there was no overflow.
569 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
570 let proportional_fee_millions =
571 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
572 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
573 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
577 // This function may be (indirectly) called without any verification,
578 // with channel_fees provided by a caller. We should handle it gracefully.
583 /// Finds a route from us (payer) to the given target node (payee).
585 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
586 /// Without this, MPP will only be used if the payee's features are available in the network graph.
588 /// Private routing paths between a public node and the target may be included in `params.payee`.
590 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
591 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
592 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
594 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
595 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
596 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
600 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
601 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
606 /// Panics if first_hops contains channels without short_channel_ids;
607 /// [`ChannelManager::list_usable_channels`] will never include such channels.
609 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
610 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
611 pub fn find_route<L: Deref, S: Score>(
612 our_node_pubkey: &PublicKey, route_params: &RouteParameters, network: &NetworkGraph,
613 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
614 ) -> Result<Route, LightningError>
615 where L::Target: Logger {
617 our_node_pubkey, &route_params.payment_params, network, first_hops, route_params.final_value_msat,
618 route_params.final_cltv_expiry_delta, logger, scorer
622 pub(crate) fn get_route<L: Deref, S: Score>(
623 our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network: &NetworkGraph,
624 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
625 logger: L, scorer: &S
626 ) -> Result<Route, LightningError>
627 where L::Target: Logger {
628 let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
629 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
631 if payee_node_id == our_node_id {
632 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
635 if final_value_msat > MAX_VALUE_MSAT {
636 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
639 if final_value_msat == 0 {
640 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
643 for route in payment_params.route_hints.iter() {
644 for hop in &route.0 {
645 if hop.src_node_id == payment_params.payee_pubkey {
646 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
651 // The general routing idea is the following:
652 // 1. Fill first/last hops communicated by the caller.
653 // 2. Attempt to construct a path from payer to payee for transferring
654 // any ~sufficient (described later) value.
655 // If succeed, remember which channels were used and how much liquidity they have available,
656 // so that future paths don't rely on the same liquidity.
657 // 3. Proceed to the next step if:
658 // - we hit the recommended target value;
659 // - OR if we could not construct a new path. Any next attempt will fail too.
660 // Otherwise, repeat step 2.
661 // 4. See if we managed to collect paths which aggregately are able to transfer target value
662 // (not recommended value). If yes, proceed. If not, fail routing.
663 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
664 // 6. Of all the found paths, select only those with the lowest total fee.
665 // 7. The last path in every selected route is likely to be more than we need.
666 // Reduce its value-to-transfer and recompute fees.
667 // 8. Choose the best route by the lowest total fee.
669 // As for the actual search algorithm,
670 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
671 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
673 // We are not a faithful Dijkstra's implementation because we can change values which impact
674 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
675 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
676 // the value we are currently attempting to send over a path, we simply reduce the value being
677 // sent along the path for any hops after that channel. This may imply that later fees (which
678 // we've already tabulated) are lower because a smaller value is passing through the channels
679 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
680 // channels which were selected earlier (and which may still be used for other paths without a
681 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
684 // One potentially problematic case for this algorithm would be if there are many
685 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
686 // graph walking), we may never find a path which is not liquidity-limited and has lower
687 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
688 // Because we only consider paths with at least 5% of the total value being sent, the damage
689 // from such a case should be limited, however this could be further reduced in the future by
690 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
691 // limits for the purposes of fee calculation.
693 // Alternatively, we could store more detailed path information in the heap (targets, below)
694 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
695 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
696 // and practically (as we would need to store dynamically-allocated path information in heap
697 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
698 // results of such an algorithm would likely be biased towards lower-value paths.
700 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
701 // outside of our current search value, running a path search more times to gather candidate
702 // paths at different values. While this may be acceptable, further path searches may increase
703 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
704 // graph for candidate paths, calculating the maximum value which can realistically be sent at
705 // the same time, remaining generic across different payment values.
707 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
708 // to use as the A* heuristic beyond just the cost to get one node further than the current
711 let network_graph = network.read_only();
712 let network_channels = network_graph.channels();
713 let network_nodes = network_graph.nodes();
715 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
716 // it. If the payee supports it they're supposed to include it in the invoice, so that should
718 let allow_mpp = if let Some(features) = &payment_params.features {
719 features.supports_basic_mpp()
720 } else if let Some(node) = network_nodes.get(&payee_node_id) {
721 if let Some(node_info) = node.announcement_info.as_ref() {
722 node_info.features.supports_basic_mpp()
725 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
726 payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" });
729 // Prepare the data we'll use for payee-to-payer search by
730 // inserting first hops suggested by the caller as targets.
731 // Our search will then attempt to reach them while traversing from the payee node.
732 let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
733 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
734 if let Some(hops) = first_hops {
736 if chan.short_channel_id.is_none() {
737 panic!("first_hops should be filled in with usable channels, not pending ones");
739 if chan.counterparty.node_id == *our_node_pubkey {
740 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
743 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
744 .or_insert(Vec::new())
747 if first_hop_targets.is_empty() {
748 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
752 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
753 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
754 // adding duplicate entries when we find a better path to a given node.
755 let mut targets = BinaryHeap::new();
757 // Map from node_id to information about the best current path to that node, including feerate
759 let mut dist = HashMap::with_capacity(network_nodes.len());
761 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
762 // indicating that we may wish to try again with a higher value, potentially paying to meet an
763 // htlc_minimum with extra fees while still finding a cheaper path.
764 let mut hit_minimum_limit;
766 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
767 // We start with a path_value of the exact amount we want, and if that generates a route we may
768 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
769 // amount we want in total across paths, selecting the best subset at the end.
770 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
771 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
772 let mut path_value_msat = final_value_msat;
774 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
775 // This map allows paths to be aware of the channel use by other paths in the same call.
776 // This would help to make a better path finding decisions and not "overbook" channels.
777 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
778 let mut bookkept_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
780 // Keeping track of how much value we already collected across other paths. Helps to decide:
781 // - how much a new path should be transferring (upper bound);
782 // - whether a channel should be disregarded because
783 // it's available liquidity is too small comparing to how much more we need to collect;
784 // - when we want to stop looking for new paths.
785 let mut already_collected_value_msat = 0;
787 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payment_params.payee_pubkey, our_node_pubkey, final_value_msat);
789 macro_rules! add_entry {
790 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
791 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
792 // since that value has to be transferred over this channel.
793 // Returns whether this channel caused an update to `targets`.
794 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
795 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
796 $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr ) => { {
797 // We "return" whether we updated the path at the end, via this:
798 let mut did_add_update_path_to_src_node = false;
799 // Channels to self should not be used. This is more of belt-and-suspenders, because in
800 // practice these cases should be caught earlier:
801 // - for regular channels at channel announcement (TODO)
802 // - for first and last hops early in get_route
803 if $src_node_id != $dest_node_id {
804 let short_channel_id = $candidate.short_channel_id();
805 let available_liquidity_msat = bookkept_channels_liquidity_available_msat
806 .entry(short_channel_id)
807 .or_insert_with(|| $candidate.effective_capacity().as_msat());
809 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
810 // It may be misleading because we might later choose to reduce the value transferred
811 // over these channels, and the channel which was insufficient might become sufficient.
812 // Worst case: we drop a good channel here because it can't cover the high following
813 // fees caused by one expensive channel, but then this channel could have been used
814 // if the amount being transferred over this path is lower.
815 // We do this for now, but this is a subject for removal.
816 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
818 // Routing Fragmentation Mitigation heuristic:
820 // Routing fragmentation across many payment paths increases the overall routing
821 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
822 // Taking too many smaller paths also increases the chance of payment failure.
823 // Thus to avoid this effect, we require from our collected links to provide
824 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
826 // This requirement is currently 5% of the remaining-to-be-collected value.
827 // This means as we successfully advance in our collection,
828 // the absolute liquidity contribution is lowered,
829 // thus increasing the number of potential channels to be selected.
831 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
832 // or 100% if we're not allowed to do multipath payments.
833 let minimal_value_contribution_msat: u64 = if allow_mpp {
834 (recommended_value_msat - already_collected_value_msat + 19) / 20
838 // Verify the liquidity offered by this channel complies to the minimal contribution.
839 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
841 // Do not consider candidates that exceed the maximum total cltv expiry limit.
842 let max_total_cltv_expiry_delta = payment_params.max_total_cltv_expiry_delta;
843 let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
844 .checked_add($candidate.cltv_expiry_delta())
845 .unwrap_or(u32::max_value());
846 let doesnt_exceed_cltv_delta_limit = hop_total_cltv_delta <= max_total_cltv_expiry_delta;
848 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
849 // Includes paying fees for the use of the following channels.
850 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
851 Some(result) => result,
852 // Can't overflow due to how the values were computed right above.
853 None => unreachable!(),
855 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
856 let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
857 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
859 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
860 // bother considering this channel.
861 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
862 // be only reduced later (not increased), so this channel should just be skipped
863 // as not sufficient.
864 if !over_path_minimum_msat && doesnt_exceed_cltv_delta_limit {
865 hit_minimum_limit = true;
866 } else if contributes_sufficient_value && doesnt_exceed_cltv_delta_limit {
867 // Note that low contribution here (limited by available_liquidity_msat)
868 // might violate htlc_minimum_msat on the hops which are next along the
869 // payment path (upstream to the payee). To avoid that, we recompute
870 // path fees knowing the final path contribution after constructing it.
871 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $candidate.fees())
872 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
873 .map(|fee_msat| cmp::max(fee_msat, $candidate.htlc_minimum_msat()))
874 .unwrap_or_else(|| u64::max_value());
875 let hm_entry = dist.entry($src_node_id);
876 let old_entry = hm_entry.or_insert_with(|| {
877 // If there was previously no known way to access the source node
878 // (recall it goes payee-to-payer) of short_channel_id, first add a
879 // semi-dummy record just to compute the fees to reach the source node.
880 // This will affect our decision on selecting short_channel_id
881 // as a way to reach the $dest_node_id.
882 let mut fee_base_msat = u32::max_value();
883 let mut fee_proportional_millionths = u32::max_value();
884 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
885 fee_base_msat = fees.base_msat;
886 fee_proportional_millionths = fees.proportional_millionths;
889 node_id: $dest_node_id.clone(),
890 candidate: $candidate.clone(),
892 src_lowest_inbound_fees: RoutingFees {
893 base_msat: fee_base_msat,
894 proportional_millionths: fee_proportional_millionths,
896 next_hops_fee_msat: u64::max_value(),
897 hop_use_fee_msat: u64::max_value(),
898 total_fee_msat: u64::max_value(),
899 path_htlc_minimum_msat,
900 path_penalty_msat: u64::max_value(),
901 was_processed: false,
902 #[cfg(any(test, feature = "fuzztarget"))]
903 value_contribution_msat,
907 #[allow(unused_mut)] // We only use the mut in cfg(test)
908 let mut should_process = !old_entry.was_processed;
909 #[cfg(any(test, feature = "fuzztarget"))]
911 // In test/fuzzing builds, we do extra checks to make sure the skipping
912 // of already-seen nodes only happens in cases we expect (see below).
913 if !should_process { should_process = true; }
917 let mut hop_use_fee_msat = 0;
918 let mut total_fee_msat = $next_hops_fee_msat;
920 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
921 // will have the same effective-fee
922 if $src_node_id != our_node_id {
923 match compute_fees(amount_to_transfer_over_msat, $candidate.fees()) {
924 // max_value means we'll always fail
925 // the old_entry.total_fee_msat > total_fee_msat check
926 None => total_fee_msat = u64::max_value(),
928 hop_use_fee_msat = fee_msat;
929 total_fee_msat += hop_use_fee_msat;
930 // When calculating the lowest inbound fees to a node, we
931 // calculate fees here not based on the actual value we think
932 // will flow over this channel, but on the minimum value that
933 // we'll accept flowing over it. The minimum accepted value
934 // is a constant through each path collection run, ensuring
935 // consistent basis. Otherwise we may later find a
936 // different path to the source node that is more expensive,
937 // but which we consider to be cheaper because we are capacity
938 // constrained and the relative fee becomes lower.
939 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
940 .map(|a| a.checked_add(total_fee_msat)) {
945 total_fee_msat = u64::max_value();
952 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
953 scorer.channel_penalty_msat(short_channel_id, amount_to_transfer_over_msat, *available_liquidity_msat,
954 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
955 let new_graph_node = RouteGraphNode {
956 node_id: $src_node_id,
957 lowest_fee_to_peer_through_node: total_fee_msat,
958 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
959 total_cltv_delta: hop_total_cltv_delta,
960 value_contribution_msat: value_contribution_msat,
961 path_htlc_minimum_msat,
965 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
966 // if this way is cheaper than the already known
967 // (considering the cost to "reach" this channel from the route destination,
968 // the cost of using this channel,
969 // and the cost of routing to the source node of this channel).
970 // Also, consider that htlc_minimum_msat_difference, because we might end up
971 // paying it. Consider the following exploit:
972 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
973 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
974 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
975 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
977 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
978 // but it may require additional tracking - we don't want to double-count
979 // the fees included in $next_hops_path_htlc_minimum_msat, but also
980 // can't use something that may decrease on future hops.
981 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
982 .checked_add(old_entry.path_penalty_msat)
983 .unwrap_or_else(|| u64::max_value());
984 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
985 .checked_add(path_penalty_msat)
986 .unwrap_or_else(|| u64::max_value());
988 if !old_entry.was_processed && new_cost < old_cost {
989 targets.push(new_graph_node);
990 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
991 old_entry.hop_use_fee_msat = hop_use_fee_msat;
992 old_entry.total_fee_msat = total_fee_msat;
993 old_entry.node_id = $dest_node_id.clone();
994 old_entry.candidate = $candidate.clone();
995 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
996 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
997 old_entry.path_penalty_msat = path_penalty_msat;
998 #[cfg(any(test, feature = "fuzztarget"))]
1000 old_entry.value_contribution_msat = value_contribution_msat;
1002 did_add_update_path_to_src_node = true;
1003 } else if old_entry.was_processed && new_cost < old_cost {
1004 #[cfg(any(test, feature = "fuzztarget"))]
1006 // If we're skipping processing a node which was previously
1007 // processed even though we found another path to it with a
1008 // cheaper fee, check that it was because the second path we
1009 // found (which we are processing now) has a lower value
1010 // contribution due to an HTLC minimum limit.
1012 // e.g. take a graph with two paths from node 1 to node 2, one
1013 // through channel A, and one through channel B. Channel A and
1014 // B are both in the to-process heap, with their scores set by
1015 // a higher htlc_minimum than fee.
1016 // Channel A is processed first, and the channels onwards from
1017 // node 1 are added to the to-process heap. Thereafter, we pop
1018 // Channel B off of the heap, note that it has a much more
1019 // restrictive htlc_maximum_msat, and recalculate the fees for
1020 // all of node 1's channels using the new, reduced, amount.
1022 // This would be bogus - we'd be selecting a higher-fee path
1023 // with a lower htlc_maximum_msat instead of the one we'd
1024 // already decided to use.
1025 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1027 value_contribution_msat + path_penalty_msat <
1028 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1036 did_add_update_path_to_src_node
1040 let empty_node_features = NodeFeatures::empty();
1041 // Find ways (channels with destination) to reach a given node and store them
1042 // in the corresponding data structures (routing graph etc).
1043 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1044 // meaning how much will be paid in fees after this node (to the best of our knowledge).
1045 // This data can later be helpful to optimize routing (pay lower fees).
1046 macro_rules! add_entries_to_cheapest_to_target_node {
1047 ( $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 ) => {
1048 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1049 let was_processed = elem.was_processed;
1050 elem.was_processed = true;
1053 // Entries are added to dist in add_entry!() when there is a channel from a node.
1054 // Because there are no channels from payee, it will not have a dist entry at this point.
1055 // If we're processing any other node, it is always be the result of a channel from it.
1056 assert_eq!($node_id, payee_node_id);
1061 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1062 for details in first_channels {
1063 let candidate = CandidateRouteHop::FirstHop { details };
1064 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);
1068 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1071 &empty_node_features
1074 if !features.requires_unknown_bits() {
1075 for chan_id in $node.channels.iter() {
1076 let chan = network_channels.get(chan_id).unwrap();
1077 if !chan.features.requires_unknown_bits() {
1078 let directed_channel =
1079 chan.as_directed_to(&$node_id).expect("inconsistent NetworkGraph");
1080 let source = directed_channel.source();
1081 let target = directed_channel.target();
1082 if first_hops.is_none() || *source != our_node_id {
1083 if let Some(direction) = directed_channel.direction() {
1084 if direction.enabled {
1085 let candidate = CandidateRouteHop::PublicHop {
1086 info: directed_channel.with_update().unwrap(),
1087 short_channel_id: *chan_id,
1089 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);
1100 let mut payment_paths = Vec::<PaymentPath>::new();
1102 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1103 'paths_collection: loop {
1104 // For every new path, start from scratch, except
1105 // bookkept_channels_liquidity_available_msat, which will improve
1106 // the further iterations of path finding. Also don't erase first_hop_targets.
1109 hit_minimum_limit = false;
1111 // If first hop is a private channel and the only way to reach the payee, this is the only
1112 // place where it could be added.
1113 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1114 for details in first_channels {
1115 let candidate = CandidateRouteHop::FirstHop { details };
1116 let added = add_entry!(candidate, our_node_id, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1117 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, candidate.short_channel_id());
1121 // Add the payee as a target, so that the payee-to-payer
1122 // search algorithm knows what to start with.
1123 match network_nodes.get(&payee_node_id) {
1124 // The payee is not in our network graph, so nothing to add here.
1125 // There is still a chance of reaching them via last_hops though,
1126 // so don't yet fail the payment here.
1127 // If not, targets.pop() will not even let us enter the loop in step 2.
1130 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64, 0);
1135 // If a caller provided us with last hops, add them to routing targets. Since this happens
1136 // earlier than general path finding, they will be somewhat prioritized, although currently
1137 // it matters only if the fees are exactly the same.
1138 for route in payment_params.route_hints.iter().filter(|route| !route.0.is_empty()) {
1139 let first_hop_in_route = &(route.0)[0];
1140 let have_hop_src_in_graph =
1141 // Only add the hops in this route to our candidate set if either
1142 // we have a direct channel to the first hop or the first hop is
1143 // in the regular network graph.
1144 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1145 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1146 if have_hop_src_in_graph {
1147 // We start building the path from reverse, i.e., from payee
1148 // to the first RouteHintHop in the path.
1149 let hop_iter = route.0.iter().rev();
1150 let prev_hop_iter = core::iter::once(&payment_params.payee_pubkey).chain(
1151 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1152 let mut hop_used = true;
1153 let mut aggregate_next_hops_fee_msat: u64 = 0;
1154 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1155 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1156 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1158 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1159 let source = NodeId::from_pubkey(&hop.src_node_id);
1160 let target = NodeId::from_pubkey(&prev_hop_id);
1161 let candidate = network_channels
1162 .get(&hop.short_channel_id)
1163 .and_then(|channel| channel.as_directed_to(&target))
1164 .and_then(|channel| channel.with_update())
1165 .map(|info| CandidateRouteHop::PublicHop {
1167 short_channel_id: hop.short_channel_id,
1169 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1170 let capacity_msat = candidate.effective_capacity().as_msat();
1171 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1172 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, capacity_msat, &source, &target))
1173 .unwrap_or_else(|| u64::max_value());
1175 aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
1176 .checked_add(hop.cltv_expiry_delta as u32)
1177 .unwrap_or_else(|| u32::max_value());
1179 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) {
1180 // If this hop was not used then there is no use checking the preceding hops
1181 // in the RouteHint. We can break by just searching for a direct channel between
1182 // last checked hop and first_hop_targets
1186 // Searching for a direct channel between last checked hop and first_hop_targets
1187 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1188 for details in first_channels {
1189 let candidate = CandidateRouteHop::FirstHop { details };
1190 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);
1198 // In the next values of the iterator, the aggregate fees already reflects
1199 // the sum of value sent from payer (final_value_msat) and routing fees
1200 // for the last node in the RouteHint. We need to just add the fees to
1201 // route through the current node so that the preceeding node (next iteration)
1203 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1204 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1205 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1207 let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
1208 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1209 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1210 .checked_add(hop_htlc_minimum_msat_inc);
1211 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1213 if idx == route.0.len() - 1 {
1214 // The last hop in this iterator is the first hop in
1215 // overall RouteHint.
1216 // If this hop connects to a node with which we have a direct channel,
1217 // ignore the network graph and, if the last hop was added, add our
1218 // direct channel to the candidate set.
1220 // Note that we *must* check if the last hop was added as `add_entry`
1221 // always assumes that the third argument is a node to which we have a
1223 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1224 for details in first_channels {
1225 let candidate = CandidateRouteHop::FirstHop { details };
1226 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);
1234 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1236 // At this point, targets are filled with the data from first and
1237 // last hops communicated by the caller, and the payment receiver.
1238 let mut found_new_path = false;
1241 // If this loop terminates due the exhaustion of targets, two situations are possible:
1242 // - not enough outgoing liquidity:
1243 // 0 < already_collected_value_msat < final_value_msat
1244 // - enough outgoing liquidity:
1245 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1246 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1247 // paths_collection will be stopped because found_new_path==false.
1248 // This is not necessarily a routing failure.
1249 '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() {
1251 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1252 // traversing the graph and arrange the path out of what we found.
1253 if node_id == our_node_id {
1254 let mut new_entry = dist.remove(&our_node_id).unwrap();
1255 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1258 let mut features_set = false;
1259 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1260 for details in first_channels {
1261 if details.short_channel_id.unwrap() == ordered_hops.last().unwrap().0.candidate.short_channel_id() {
1262 ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
1263 features_set = true;
1269 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1270 if let Some(node_info) = node.announcement_info.as_ref() {
1271 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1273 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1276 // We should be able to fill in features for everything except the last
1277 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1278 // should be able to extend it further as BOLT 11 does have feature
1279 // flags for the last hop node itself).
1280 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1284 // Means we succesfully traversed from the payer to the payee, now
1285 // save this path for the payment route. Also, update the liquidity
1286 // remaining on the used hops, so that we take them into account
1287 // while looking for more paths.
1288 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1292 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1293 Some(payment_hop) => payment_hop,
1294 // We can't arrive at None because, if we ever add an entry to targets,
1295 // we also fill in the entry in dist (see add_entry!).
1296 None => unreachable!(),
1298 // We "propagate" the fees one hop backward (topologically) here,
1299 // so that fees paid for a HTLC forwarding on the current channel are
1300 // associated with the previous channel (where they will be subtracted).
1301 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1302 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1304 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1305 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1307 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1308 ordered_hops.len(), value_contribution_msat, ordered_hops);
1310 let mut payment_path = PaymentPath {hops: ordered_hops};
1312 // We could have possibly constructed a slightly inconsistent path: since we reduce
1313 // value being transferred along the way, we could have violated htlc_minimum_msat
1314 // on some channels we already passed (assuming dest->source direction). Here, we
1315 // recompute the fees again, so that if that's the case, we match the currently
1316 // underpaid htlc_minimum_msat with fees.
1317 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1319 // Since a path allows to transfer as much value as
1320 // the smallest channel it has ("bottleneck"), we should recompute
1321 // the fees so sender HTLC don't overpay fees when traversing
1322 // larger channels than the bottleneck. This may happen because
1323 // when we were selecting those channels we were not aware how much value
1324 // this path will transfer, and the relative fee for them
1325 // might have been computed considering a larger value.
1326 // Remember that we used these channels so that we don't rely
1327 // on the same liquidity in future paths.
1328 let mut prevented_redundant_path_selection = false;
1329 for (payment_hop, _) in payment_path.hops.iter() {
1330 let channel_liquidity_available_msat = bookkept_channels_liquidity_available_msat.get_mut(&payment_hop.candidate.short_channel_id()).unwrap();
1331 let mut spent_on_hop_msat = value_contribution_msat;
1332 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1333 spent_on_hop_msat += next_hops_fee_msat;
1334 if spent_on_hop_msat == *channel_liquidity_available_msat {
1335 // If this path used all of this channel's available liquidity, we know
1336 // this path will not be selected again in the next loop iteration.
1337 prevented_redundant_path_selection = true;
1339 *channel_liquidity_available_msat -= spent_on_hop_msat;
1341 if !prevented_redundant_path_selection {
1342 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1343 // we'll probably end up picking the same path again on the next iteration.
1344 // Decrease the available liquidity of a hop in the middle of the path.
1345 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.candidate.short_channel_id();
1346 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1347 let victim_liquidity = bookkept_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1348 *victim_liquidity = 0;
1351 // Track the total amount all our collected paths allow to send so that we:
1352 // - know when to stop looking for more paths
1353 // - know which of the hops are useless considering how much more sats we need
1354 // (contributes_sufficient_value)
1355 already_collected_value_msat += value_contribution_msat;
1357 payment_paths.push(payment_path);
1358 found_new_path = true;
1359 break 'path_construction;
1362 // If we found a path back to the payee, we shouldn't try to process it again. This is
1363 // the equivalent of the `elem.was_processed` check in
1364 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1365 if node_id == payee_node_id { continue 'path_construction; }
1367 // Otherwise, since the current target node is not us,
1368 // keep "unrolling" the payment graph from payee to payer by
1369 // finding a way to reach the current target from the payer side.
1370 match network_nodes.get(&node_id) {
1373 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);
1379 // If we don't support MPP, no use trying to gather more value ever.
1380 break 'paths_collection;
1384 // Stop either when the recommended value is reached or if no new path was found in this
1386 // In the latter case, making another path finding attempt won't help,
1387 // because we deterministically terminated the search due to low liquidity.
1388 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1389 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1390 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1391 break 'paths_collection;
1392 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1393 // Further, if this was our first walk of the graph, and we weren't limited by an
1394 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1395 // limited by an htlc_minimum_msat value, find another path with a higher value,
1396 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1397 // still keeping a lower total fee than this path.
1398 if !hit_minimum_limit {
1399 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1400 break 'paths_collection;
1402 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1403 path_value_msat = recommended_value_msat;
1408 if payment_paths.len() == 0 {
1409 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1412 if already_collected_value_msat < final_value_msat {
1413 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1416 // Sort by total fees and take the best paths.
1417 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1418 if payment_paths.len() > 50 {
1419 payment_paths.truncate(50);
1422 // Draw multiple sufficient routes by randomly combining the selected paths.
1423 let mut drawn_routes = Vec::new();
1424 for i in 0..payment_paths.len() {
1425 let mut cur_route = Vec::<PaymentPath>::new();
1426 let mut aggregate_route_value_msat = 0;
1429 // TODO: real random shuffle
1430 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1431 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1434 for payment_path in cur_payment_paths {
1435 cur_route.push(payment_path.clone());
1436 aggregate_route_value_msat += payment_path.get_value_msat();
1437 if aggregate_route_value_msat > final_value_msat {
1438 // Last path likely overpaid. Substract it from the most expensive
1439 // (in terms of proportional fee) path in this route and recompute fees.
1440 // This might be not the most economically efficient way, but fewer paths
1441 // also makes routing more reliable.
1442 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1444 // First, drop some expensive low-value paths entirely if possible.
1445 // Sort by value so that we drop many really-low values first, since
1446 // fewer paths is better: the payment is less likely to fail.
1447 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1448 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1449 cur_route.sort_by_key(|path| path.get_value_msat());
1450 // We should make sure that at least 1 path left.
1451 let mut paths_left = cur_route.len();
1452 cur_route.retain(|path| {
1453 if paths_left == 1 {
1456 let mut keep = true;
1457 let path_value_msat = path.get_value_msat();
1458 if path_value_msat <= overpaid_value_msat {
1460 overpaid_value_msat -= path_value_msat;
1466 if overpaid_value_msat == 0 {
1470 assert!(cur_route.len() > 0);
1473 // Now, substract the overpaid value from the most-expensive path.
1474 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1475 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1476 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>() });
1477 let expensive_payment_path = cur_route.first_mut().unwrap();
1478 // We already dropped all the small channels above, meaning all the
1479 // remaining channels are larger than remaining overpaid_value_msat.
1480 // Thus, this can't be negative.
1481 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1482 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1486 drawn_routes.push(cur_route);
1490 // Select the best route by lowest total fee.
1491 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1492 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1493 for payment_path in drawn_routes.first().unwrap() {
1494 let mut path = payment_path.hops.iter().map(|(payment_hop, node_features)| {
1496 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)})?,
1497 node_features: node_features.clone(),
1498 short_channel_id: payment_hop.candidate.short_channel_id(),
1499 channel_features: payment_hop.candidate.features(),
1500 fee_msat: payment_hop.fee_msat,
1501 cltv_expiry_delta: payment_hop.candidate.cltv_expiry_delta(),
1503 }).collect::<Vec<_>>();
1504 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
1505 // applicable for the previous hop.
1506 path.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
1507 core::mem::replace(&mut hop.as_mut().unwrap().cltv_expiry_delta, prev_cltv_expiry_delta)
1509 selected_paths.push(path);
1512 if let Some(features) = &payment_params.features {
1513 for path in selected_paths.iter_mut() {
1514 if let Ok(route_hop) = path.last_mut().unwrap() {
1515 route_hop.node_features = features.to_context();
1521 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1522 payment_params: Some(payment_params.clone()),
1524 log_info!(logger, "Got route to {}: {}", payment_params.payee_pubkey, log_route!(route));
1530 use routing::scoring::Score;
1531 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1532 use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1533 use chain::transaction::OutPoint;
1534 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1535 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1536 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1537 use ln::channelmanager;
1538 use util::test_utils;
1539 use util::ser::Writeable;
1541 use util::ser::Writer;
1543 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1544 use bitcoin::hashes::Hash;
1545 use bitcoin::network::constants::Network;
1546 use bitcoin::blockdata::constants::genesis_block;
1547 use bitcoin::blockdata::script::Builder;
1548 use bitcoin::blockdata::opcodes;
1549 use bitcoin::blockdata::transaction::TxOut;
1553 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1554 use bitcoin::secp256k1::{Secp256k1, All};
1557 use sync::{self, Arc};
1559 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1560 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1561 channelmanager::ChannelDetails {
1562 channel_id: [0; 32],
1563 counterparty: channelmanager::ChannelCounterparty {
1566 unspendable_punishment_reserve: 0,
1567 forwarding_info: None,
1569 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1571 channel_value_satoshis: 0,
1574 outbound_capacity_msat,
1575 inbound_capacity_msat: 42,
1576 unspendable_punishment_reserve: None,
1577 confirmations_required: None,
1578 force_close_spend_delay: None,
1579 is_outbound: true, is_funding_locked: true,
1580 is_usable: true, is_public: true,
1584 // Using the same keys for LN and BTC ids
1586 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1587 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1589 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1590 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1592 let unsigned_announcement = UnsignedChannelAnnouncement {
1594 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1598 bitcoin_key_1: node_id_1,
1599 bitcoin_key_2: node_id_2,
1600 excess_data: Vec::new(),
1603 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1604 let valid_announcement = ChannelAnnouncement {
1605 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1606 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1607 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1608 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1609 contents: unsigned_announcement.clone(),
1611 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1612 Ok(res) => assert!(res),
1618 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1619 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1621 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1622 let valid_channel_update = ChannelUpdate {
1623 signature: secp_ctx.sign(&msghash, node_privkey),
1624 contents: update.clone()
1627 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1628 Ok(res) => assert!(res),
1633 fn add_or_update_node(
1634 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1635 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1637 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1638 let unsigned_announcement = UnsignedNodeAnnouncement {
1644 addresses: Vec::new(),
1645 excess_address_data: Vec::new(),
1646 excess_data: Vec::new(),
1648 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1649 let valid_announcement = NodeAnnouncement {
1650 signature: secp_ctx.sign(&msghash, node_privkey),
1651 contents: unsigned_announcement.clone()
1654 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1660 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1661 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1662 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1665 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1667 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1668 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1670 (our_privkey, our_id, privkeys, pubkeys)
1673 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1674 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1675 // test for it later.
1676 let idx = (id - 1) * 2 + 1;
1678 vec![1 << (idx - 8*3), 0, 0, 0]
1679 } else if idx > 8*2 {
1680 vec![1 << (idx - 8*2), 0, 0]
1681 } else if idx > 8*1 {
1682 vec![1 << (idx - 8*1), 0]
1688 fn build_graph() -> (
1690 sync::Arc<NetworkGraph>,
1691 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1692 sync::Arc<test_utils::TestChainSource>,
1693 sync::Arc<test_utils::TestLogger>,
1695 let secp_ctx = Secp256k1::new();
1696 let logger = Arc::new(test_utils::TestLogger::new());
1697 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1698 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1699 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1700 // Build network from our_id to node6:
1702 // -1(1)2- node0 -1(3)2-
1704 // our_id -1(12)2- node7 -1(13)2--- node2
1706 // -1(2)2- node1 -1(4)2-
1709 // chan1 1-to-2: disabled
1710 // chan1 2-to-1: enabled, 0 fee
1712 // chan2 1-to-2: enabled, ignored fee
1713 // chan2 2-to-1: enabled, 0 fee
1715 // chan3 1-to-2: enabled, 0 fee
1716 // chan3 2-to-1: enabled, 100 msat fee
1718 // chan4 1-to-2: enabled, 100% fee
1719 // chan4 2-to-1: enabled, 0 fee
1721 // chan12 1-to-2: enabled, ignored fee
1722 // chan12 2-to-1: enabled, 0 fee
1724 // chan13 1-to-2: enabled, 200% fee
1725 // chan13 2-to-1: enabled, 0 fee
1728 // -1(5)2- node3 -1(8)2--
1732 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1734 // -1(7)2- node5 -1(10)2-
1736 // Channels 5, 8, 9 and 10 are private channels.
1738 // chan5 1-to-2: enabled, 100 msat fee
1739 // chan5 2-to-1: enabled, 0 fee
1741 // chan6 1-to-2: enabled, 0 fee
1742 // chan6 2-to-1: enabled, 0 fee
1744 // chan7 1-to-2: enabled, 100% fee
1745 // chan7 2-to-1: enabled, 0 fee
1747 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1748 // chan8 2-to-1: enabled, 0 fee
1750 // chan9 1-to-2: enabled, 1001 msat fee
1751 // chan9 2-to-1: enabled, 0 fee
1753 // chan10 1-to-2: enabled, 0 fee
1754 // chan10 2-to-1: enabled, 0 fee
1756 // chan11 1-to-2: enabled, 0 fee
1757 // chan11 2-to-1: enabled, 0 fee
1759 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1761 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1762 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1764 short_channel_id: 1,
1767 cltv_expiry_delta: 0,
1768 htlc_minimum_msat: 0,
1769 htlc_maximum_msat: OptionalField::Absent,
1771 fee_proportional_millionths: 0,
1772 excess_data: Vec::new()
1775 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1777 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1778 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1780 short_channel_id: 2,
1783 cltv_expiry_delta: (5 << 4) | 3,
1784 htlc_minimum_msat: 0,
1785 htlc_maximum_msat: OptionalField::Absent,
1786 fee_base_msat: u32::max_value(),
1787 fee_proportional_millionths: u32::max_value(),
1788 excess_data: Vec::new()
1790 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1792 short_channel_id: 2,
1795 cltv_expiry_delta: 0,
1796 htlc_minimum_msat: 0,
1797 htlc_maximum_msat: OptionalField::Absent,
1799 fee_proportional_millionths: 0,
1800 excess_data: Vec::new()
1803 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1805 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1806 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1808 short_channel_id: 12,
1811 cltv_expiry_delta: (5 << 4) | 3,
1812 htlc_minimum_msat: 0,
1813 htlc_maximum_msat: OptionalField::Absent,
1814 fee_base_msat: u32::max_value(),
1815 fee_proportional_millionths: u32::max_value(),
1816 excess_data: Vec::new()
1818 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1820 short_channel_id: 12,
1823 cltv_expiry_delta: 0,
1824 htlc_minimum_msat: 0,
1825 htlc_maximum_msat: OptionalField::Absent,
1827 fee_proportional_millionths: 0,
1828 excess_data: Vec::new()
1831 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1833 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1834 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1836 short_channel_id: 3,
1839 cltv_expiry_delta: (3 << 4) | 1,
1840 htlc_minimum_msat: 0,
1841 htlc_maximum_msat: OptionalField::Absent,
1843 fee_proportional_millionths: 0,
1844 excess_data: Vec::new()
1846 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1848 short_channel_id: 3,
1851 cltv_expiry_delta: (3 << 4) | 2,
1852 htlc_minimum_msat: 0,
1853 htlc_maximum_msat: OptionalField::Absent,
1855 fee_proportional_millionths: 0,
1856 excess_data: Vec::new()
1859 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1860 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1862 short_channel_id: 4,
1865 cltv_expiry_delta: (4 << 4) | 1,
1866 htlc_minimum_msat: 0,
1867 htlc_maximum_msat: OptionalField::Absent,
1869 fee_proportional_millionths: 1000000,
1870 excess_data: Vec::new()
1872 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1873 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1874 short_channel_id: 4,
1877 cltv_expiry_delta: (4 << 4) | 2,
1878 htlc_minimum_msat: 0,
1879 htlc_maximum_msat: OptionalField::Absent,
1881 fee_proportional_millionths: 0,
1882 excess_data: Vec::new()
1885 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1886 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1887 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1888 short_channel_id: 13,
1891 cltv_expiry_delta: (13 << 4) | 1,
1892 htlc_minimum_msat: 0,
1893 htlc_maximum_msat: OptionalField::Absent,
1895 fee_proportional_millionths: 2000000,
1896 excess_data: Vec::new()
1898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1900 short_channel_id: 13,
1903 cltv_expiry_delta: (13 << 4) | 2,
1904 htlc_minimum_msat: 0,
1905 htlc_maximum_msat: OptionalField::Absent,
1907 fee_proportional_millionths: 0,
1908 excess_data: Vec::new()
1911 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1913 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1914 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1916 short_channel_id: 6,
1919 cltv_expiry_delta: (6 << 4) | 1,
1920 htlc_minimum_msat: 0,
1921 htlc_maximum_msat: OptionalField::Absent,
1923 fee_proportional_millionths: 0,
1924 excess_data: Vec::new()
1926 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1928 short_channel_id: 6,
1931 cltv_expiry_delta: (6 << 4) | 2,
1932 htlc_minimum_msat: 0,
1933 htlc_maximum_msat: OptionalField::Absent,
1935 fee_proportional_millionths: 0,
1936 excess_data: Vec::new(),
1939 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1940 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1941 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1942 short_channel_id: 11,
1945 cltv_expiry_delta: (11 << 4) | 1,
1946 htlc_minimum_msat: 0,
1947 htlc_maximum_msat: OptionalField::Absent,
1949 fee_proportional_millionths: 0,
1950 excess_data: Vec::new()
1952 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1953 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1954 short_channel_id: 11,
1957 cltv_expiry_delta: (11 << 4) | 2,
1958 htlc_minimum_msat: 0,
1959 htlc_maximum_msat: OptionalField::Absent,
1961 fee_proportional_millionths: 0,
1962 excess_data: Vec::new()
1965 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1967 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1969 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1970 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1971 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1972 short_channel_id: 7,
1975 cltv_expiry_delta: (7 << 4) | 1,
1976 htlc_minimum_msat: 0,
1977 htlc_maximum_msat: OptionalField::Absent,
1979 fee_proportional_millionths: 1000000,
1980 excess_data: Vec::new()
1982 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1984 short_channel_id: 7,
1987 cltv_expiry_delta: (7 << 4) | 2,
1988 htlc_minimum_msat: 0,
1989 htlc_maximum_msat: OptionalField::Absent,
1991 fee_proportional_millionths: 0,
1992 excess_data: Vec::new()
1995 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1997 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2001 fn simple_route_test() {
2002 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2003 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2004 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2005 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2007 // Simple route to 2 via 1
2009 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
2010 assert_eq!(err, "Cannot send a payment of 0 msat");
2011 } else { panic!(); }
2013 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2014 assert_eq!(route.paths[0].len(), 2);
2016 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2017 assert_eq!(route.paths[0][0].short_channel_id, 2);
2018 assert_eq!(route.paths[0][0].fee_msat, 100);
2019 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2020 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2021 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2023 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2024 assert_eq!(route.paths[0][1].short_channel_id, 4);
2025 assert_eq!(route.paths[0][1].fee_msat, 100);
2026 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2027 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2028 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2032 fn invalid_first_hop_test() {
2033 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2034 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2035 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2036 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2038 // Simple route to 2 via 1
2040 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2042 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) {
2043 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2044 } else { panic!(); }
2046 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2047 assert_eq!(route.paths[0].len(), 2);
2051 fn htlc_minimum_test() {
2052 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2053 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2054 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2055 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2057 // Simple route to 2 via 1
2059 // Disable other paths
2060 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2061 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2062 short_channel_id: 12,
2064 flags: 2, // to disable
2065 cltv_expiry_delta: 0,
2066 htlc_minimum_msat: 0,
2067 htlc_maximum_msat: OptionalField::Absent,
2069 fee_proportional_millionths: 0,
2070 excess_data: Vec::new()
2072 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2074 short_channel_id: 3,
2076 flags: 2, // to disable
2077 cltv_expiry_delta: 0,
2078 htlc_minimum_msat: 0,
2079 htlc_maximum_msat: OptionalField::Absent,
2081 fee_proportional_millionths: 0,
2082 excess_data: Vec::new()
2084 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2085 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2086 short_channel_id: 13,
2088 flags: 2, // to disable
2089 cltv_expiry_delta: 0,
2090 htlc_minimum_msat: 0,
2091 htlc_maximum_msat: OptionalField::Absent,
2093 fee_proportional_millionths: 0,
2094 excess_data: Vec::new()
2096 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2097 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2098 short_channel_id: 6,
2100 flags: 2, // to disable
2101 cltv_expiry_delta: 0,
2102 htlc_minimum_msat: 0,
2103 htlc_maximum_msat: OptionalField::Absent,
2105 fee_proportional_millionths: 0,
2106 excess_data: Vec::new()
2108 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2109 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2110 short_channel_id: 7,
2112 flags: 2, // to disable
2113 cltv_expiry_delta: 0,
2114 htlc_minimum_msat: 0,
2115 htlc_maximum_msat: OptionalField::Absent,
2117 fee_proportional_millionths: 0,
2118 excess_data: Vec::new()
2121 // Check against amount_to_transfer_over_msat.
2122 // Set minimal HTLC of 200_000_000 msat.
2123 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2125 short_channel_id: 2,
2128 cltv_expiry_delta: 0,
2129 htlc_minimum_msat: 200_000_000,
2130 htlc_maximum_msat: OptionalField::Absent,
2132 fee_proportional_millionths: 0,
2133 excess_data: Vec::new()
2136 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2138 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2139 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2140 short_channel_id: 4,
2143 cltv_expiry_delta: 0,
2144 htlc_minimum_msat: 0,
2145 htlc_maximum_msat: OptionalField::Present(199_999_999),
2147 fee_proportional_millionths: 0,
2148 excess_data: Vec::new()
2151 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2152 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) {
2153 assert_eq!(err, "Failed to find a path to the given destination");
2154 } else { panic!(); }
2156 // Lift the restriction on the first hop.
2157 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2158 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2159 short_channel_id: 2,
2162 cltv_expiry_delta: 0,
2163 htlc_minimum_msat: 0,
2164 htlc_maximum_msat: OptionalField::Absent,
2166 fee_proportional_millionths: 0,
2167 excess_data: Vec::new()
2170 // A payment above the minimum should pass
2171 let route = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2172 assert_eq!(route.paths[0].len(), 2);
2176 fn htlc_minimum_overpay_test() {
2177 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2178 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2179 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2180 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2182 // A route to node#2 via two paths.
2183 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2184 // Thus, they can't send 60 without overpaying.
2185 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2186 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2187 short_channel_id: 2,
2190 cltv_expiry_delta: 0,
2191 htlc_minimum_msat: 35_000,
2192 htlc_maximum_msat: OptionalField::Present(40_000),
2194 fee_proportional_millionths: 0,
2195 excess_data: Vec::new()
2197 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2199 short_channel_id: 12,
2202 cltv_expiry_delta: 0,
2203 htlc_minimum_msat: 35_000,
2204 htlc_maximum_msat: OptionalField::Present(40_000),
2206 fee_proportional_millionths: 0,
2207 excess_data: Vec::new()
2211 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2212 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2213 short_channel_id: 13,
2216 cltv_expiry_delta: 0,
2217 htlc_minimum_msat: 0,
2218 htlc_maximum_msat: OptionalField::Absent,
2220 fee_proportional_millionths: 0,
2221 excess_data: Vec::new()
2223 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2224 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2225 short_channel_id: 4,
2228 cltv_expiry_delta: 0,
2229 htlc_minimum_msat: 0,
2230 htlc_maximum_msat: OptionalField::Absent,
2232 fee_proportional_millionths: 0,
2233 excess_data: Vec::new()
2236 // Disable other paths
2237 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2239 short_channel_id: 1,
2241 flags: 2, // to disable
2242 cltv_expiry_delta: 0,
2243 htlc_minimum_msat: 0,
2244 htlc_maximum_msat: OptionalField::Absent,
2246 fee_proportional_millionths: 0,
2247 excess_data: Vec::new()
2250 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2251 // Overpay fees to hit htlc_minimum_msat.
2252 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2253 // TODO: this could be better balanced to overpay 10k and not 15k.
2254 assert_eq!(overpaid_fees, 15_000);
2256 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2257 // while taking even more fee to match htlc_minimum_msat.
2258 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2260 short_channel_id: 12,
2263 cltv_expiry_delta: 0,
2264 htlc_minimum_msat: 65_000,
2265 htlc_maximum_msat: OptionalField::Present(80_000),
2267 fee_proportional_millionths: 0,
2268 excess_data: Vec::new()
2270 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2271 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2272 short_channel_id: 2,
2275 cltv_expiry_delta: 0,
2276 htlc_minimum_msat: 0,
2277 htlc_maximum_msat: OptionalField::Absent,
2279 fee_proportional_millionths: 0,
2280 excess_data: Vec::new()
2282 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2283 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2284 short_channel_id: 4,
2287 cltv_expiry_delta: 0,
2288 htlc_minimum_msat: 0,
2289 htlc_maximum_msat: OptionalField::Absent,
2291 fee_proportional_millionths: 100_000,
2292 excess_data: Vec::new()
2295 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2296 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2297 assert_eq!(route.paths.len(), 1);
2298 assert_eq!(route.paths[0][0].short_channel_id, 12);
2299 let fees = route.paths[0][0].fee_msat;
2300 assert_eq!(fees, 5_000);
2302 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2303 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2304 // the other channel.
2305 assert_eq!(route.paths.len(), 1);
2306 assert_eq!(route.paths[0][0].short_channel_id, 2);
2307 let fees = route.paths[0][0].fee_msat;
2308 assert_eq!(fees, 5_000);
2312 fn disable_channels_test() {
2313 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2314 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2315 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2316 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2318 // // Disable channels 4 and 12 by flags=2
2319 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2320 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2321 short_channel_id: 4,
2323 flags: 2, // to disable
2324 cltv_expiry_delta: 0,
2325 htlc_minimum_msat: 0,
2326 htlc_maximum_msat: OptionalField::Absent,
2328 fee_proportional_millionths: 0,
2329 excess_data: Vec::new()
2331 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2332 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2333 short_channel_id: 12,
2335 flags: 2, // to disable
2336 cltv_expiry_delta: 0,
2337 htlc_minimum_msat: 0,
2338 htlc_maximum_msat: OptionalField::Absent,
2340 fee_proportional_millionths: 0,
2341 excess_data: Vec::new()
2344 // If all the channels require some features we don't understand, route should fail
2345 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2346 assert_eq!(err, "Failed to find a path to the given destination");
2347 } else { panic!(); }
2349 // If we specify a channel to node7, that overrides our local channel view and that gets used
2350 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2351 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2352 assert_eq!(route.paths[0].len(), 2);
2354 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2355 assert_eq!(route.paths[0][0].short_channel_id, 42);
2356 assert_eq!(route.paths[0][0].fee_msat, 200);
2357 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2358 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2359 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2361 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2362 assert_eq!(route.paths[0][1].short_channel_id, 13);
2363 assert_eq!(route.paths[0][1].fee_msat, 100);
2364 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2365 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2366 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2370 fn disable_node_test() {
2371 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2372 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2373 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2374 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2376 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2377 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2378 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2379 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2380 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2382 // If all nodes require some features we don't understand, route should fail
2383 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2384 assert_eq!(err, "Failed to find a path to the given destination");
2385 } else { panic!(); }
2387 // If we specify a channel to node7, that overrides our local channel view and that gets used
2388 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2389 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2390 assert_eq!(route.paths[0].len(), 2);
2392 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2393 assert_eq!(route.paths[0][0].short_channel_id, 42);
2394 assert_eq!(route.paths[0][0].fee_msat, 200);
2395 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2396 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2397 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2399 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2400 assert_eq!(route.paths[0][1].short_channel_id, 13);
2401 assert_eq!(route.paths[0][1].fee_msat, 100);
2402 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2403 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2404 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2406 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2407 // naively) assume that the user checked the feature bits on the invoice, which override
2408 // the node_announcement.
2412 fn our_chans_test() {
2413 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2414 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2415 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2417 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2418 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2419 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2420 assert_eq!(route.paths[0].len(), 3);
2422 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2423 assert_eq!(route.paths[0][0].short_channel_id, 2);
2424 assert_eq!(route.paths[0][0].fee_msat, 200);
2425 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2426 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2427 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2429 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2430 assert_eq!(route.paths[0][1].short_channel_id, 4);
2431 assert_eq!(route.paths[0][1].fee_msat, 100);
2432 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2433 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2434 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2436 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2437 assert_eq!(route.paths[0][2].short_channel_id, 3);
2438 assert_eq!(route.paths[0][2].fee_msat, 100);
2439 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2440 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2441 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2443 // If we specify a channel to node7, that overrides our local channel view and that gets used
2444 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2445 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2446 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2447 assert_eq!(route.paths[0].len(), 2);
2449 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2450 assert_eq!(route.paths[0][0].short_channel_id, 42);
2451 assert_eq!(route.paths[0][0].fee_msat, 200);
2452 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2453 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2454 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2456 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2457 assert_eq!(route.paths[0][1].short_channel_id, 13);
2458 assert_eq!(route.paths[0][1].fee_msat, 100);
2459 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2460 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2461 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2464 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2465 let zero_fees = RoutingFees {
2467 proportional_millionths: 0,
2469 vec![RouteHint(vec![RouteHintHop {
2470 src_node_id: nodes[3],
2471 short_channel_id: 8,
2473 cltv_expiry_delta: (8 << 4) | 1,
2474 htlc_minimum_msat: None,
2475 htlc_maximum_msat: None,
2477 ]), RouteHint(vec![RouteHintHop {
2478 src_node_id: nodes[4],
2479 short_channel_id: 9,
2482 proportional_millionths: 0,
2484 cltv_expiry_delta: (9 << 4) | 1,
2485 htlc_minimum_msat: None,
2486 htlc_maximum_msat: None,
2487 }]), RouteHint(vec![RouteHintHop {
2488 src_node_id: nodes[5],
2489 short_channel_id: 10,
2491 cltv_expiry_delta: (10 << 4) | 1,
2492 htlc_minimum_msat: None,
2493 htlc_maximum_msat: None,
2497 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2498 let zero_fees = RoutingFees {
2500 proportional_millionths: 0,
2502 vec![RouteHint(vec![RouteHintHop {
2503 src_node_id: nodes[2],
2504 short_channel_id: 5,
2507 proportional_millionths: 0,
2509 cltv_expiry_delta: (5 << 4) | 1,
2510 htlc_minimum_msat: None,
2511 htlc_maximum_msat: None,
2513 src_node_id: nodes[3],
2514 short_channel_id: 8,
2516 cltv_expiry_delta: (8 << 4) | 1,
2517 htlc_minimum_msat: None,
2518 htlc_maximum_msat: None,
2520 ]), RouteHint(vec![RouteHintHop {
2521 src_node_id: nodes[4],
2522 short_channel_id: 9,
2525 proportional_millionths: 0,
2527 cltv_expiry_delta: (9 << 4) | 1,
2528 htlc_minimum_msat: None,
2529 htlc_maximum_msat: None,
2530 }]), RouteHint(vec![RouteHintHop {
2531 src_node_id: nodes[5],
2532 short_channel_id: 10,
2534 cltv_expiry_delta: (10 << 4) | 1,
2535 htlc_minimum_msat: None,
2536 htlc_maximum_msat: None,
2541 fn partial_route_hint_test() {
2542 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2543 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2544 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2546 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2547 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2548 // RouteHint may be partially used by the algo to build the best path.
2550 // First check that last hop can't have its source as the payee.
2551 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2552 src_node_id: nodes[6],
2553 short_channel_id: 8,
2556 proportional_millionths: 0,
2558 cltv_expiry_delta: (8 << 4) | 1,
2559 htlc_minimum_msat: None,
2560 htlc_maximum_msat: None,
2563 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2564 invalid_last_hops.push(invalid_last_hop);
2566 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2567 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2568 assert_eq!(err, "Route hint cannot have the payee as the source.");
2569 } else { panic!(); }
2572 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2573 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2574 assert_eq!(route.paths[0].len(), 5);
2576 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2577 assert_eq!(route.paths[0][0].short_channel_id, 2);
2578 assert_eq!(route.paths[0][0].fee_msat, 100);
2579 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2580 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2581 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2583 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2584 assert_eq!(route.paths[0][1].short_channel_id, 4);
2585 assert_eq!(route.paths[0][1].fee_msat, 0);
2586 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2587 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2588 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2590 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2591 assert_eq!(route.paths[0][2].short_channel_id, 6);
2592 assert_eq!(route.paths[0][2].fee_msat, 0);
2593 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2594 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2595 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2597 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2598 assert_eq!(route.paths[0][3].short_channel_id, 11);
2599 assert_eq!(route.paths[0][3].fee_msat, 0);
2600 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2601 // If we have a peer in the node map, we'll use their features here since we don't have
2602 // a way of figuring out their features from the invoice:
2603 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2604 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2606 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2607 assert_eq!(route.paths[0][4].short_channel_id, 8);
2608 assert_eq!(route.paths[0][4].fee_msat, 100);
2609 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2610 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2611 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2614 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2615 let zero_fees = RoutingFees {
2617 proportional_millionths: 0,
2619 vec![RouteHint(vec![RouteHintHop {
2620 src_node_id: nodes[3],
2621 short_channel_id: 8,
2623 cltv_expiry_delta: (8 << 4) | 1,
2624 htlc_minimum_msat: None,
2625 htlc_maximum_msat: None,
2626 }]), RouteHint(vec![
2628 ]), RouteHint(vec![RouteHintHop {
2629 src_node_id: nodes[5],
2630 short_channel_id: 10,
2632 cltv_expiry_delta: (10 << 4) | 1,
2633 htlc_minimum_msat: None,
2634 htlc_maximum_msat: None,
2639 fn ignores_empty_last_hops_test() {
2640 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2641 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2642 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2643 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2645 // Test handling of an empty RouteHint passed in Invoice.
2647 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2648 assert_eq!(route.paths[0].len(), 5);
2650 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2651 assert_eq!(route.paths[0][0].short_channel_id, 2);
2652 assert_eq!(route.paths[0][0].fee_msat, 100);
2653 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2654 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2655 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2657 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2658 assert_eq!(route.paths[0][1].short_channel_id, 4);
2659 assert_eq!(route.paths[0][1].fee_msat, 0);
2660 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2661 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2662 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2664 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2665 assert_eq!(route.paths[0][2].short_channel_id, 6);
2666 assert_eq!(route.paths[0][2].fee_msat, 0);
2667 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2668 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2669 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2671 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2672 assert_eq!(route.paths[0][3].short_channel_id, 11);
2673 assert_eq!(route.paths[0][3].fee_msat, 0);
2674 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2675 // If we have a peer in the node map, we'll use their features here since we don't have
2676 // a way of figuring out their features from the invoice:
2677 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2678 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2680 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2681 assert_eq!(route.paths[0][4].short_channel_id, 8);
2682 assert_eq!(route.paths[0][4].fee_msat, 100);
2683 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2684 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2685 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2688 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2689 let zero_fees = RoutingFees {
2691 proportional_millionths: 0,
2693 vec![RouteHint(vec![RouteHintHop {
2694 src_node_id: nodes[2],
2695 short_channel_id: 5,
2698 proportional_millionths: 0,
2700 cltv_expiry_delta: (5 << 4) | 1,
2701 htlc_minimum_msat: None,
2702 htlc_maximum_msat: None,
2704 src_node_id: nodes[3],
2705 short_channel_id: 8,
2707 cltv_expiry_delta: (8 << 4) | 1,
2708 htlc_minimum_msat: None,
2709 htlc_maximum_msat: None,
2710 }]), RouteHint(vec![RouteHintHop {
2711 src_node_id: nodes[5],
2712 short_channel_id: 10,
2714 cltv_expiry_delta: (10 << 4) | 1,
2715 htlc_minimum_msat: None,
2716 htlc_maximum_msat: None,
2721 fn multi_hint_last_hops_test() {
2722 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2723 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2724 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2725 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2726 // Test through channels 2, 3, 5, 8.
2727 // Test shows that multiple hop hints are considered.
2729 // Disabling channels 6 & 7 by flags=2
2730 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2731 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2732 short_channel_id: 6,
2734 flags: 2, // to disable
2735 cltv_expiry_delta: 0,
2736 htlc_minimum_msat: 0,
2737 htlc_maximum_msat: OptionalField::Absent,
2739 fee_proportional_millionths: 0,
2740 excess_data: Vec::new()
2742 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2743 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2744 short_channel_id: 7,
2746 flags: 2, // to disable
2747 cltv_expiry_delta: 0,
2748 htlc_minimum_msat: 0,
2749 htlc_maximum_msat: OptionalField::Absent,
2751 fee_proportional_millionths: 0,
2752 excess_data: Vec::new()
2755 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2756 assert_eq!(route.paths[0].len(), 4);
2758 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2759 assert_eq!(route.paths[0][0].short_channel_id, 2);
2760 assert_eq!(route.paths[0][0].fee_msat, 200);
2761 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2762 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2763 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2765 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2766 assert_eq!(route.paths[0][1].short_channel_id, 4);
2767 assert_eq!(route.paths[0][1].fee_msat, 100);
2768 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2769 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2770 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2772 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2773 assert_eq!(route.paths[0][2].short_channel_id, 5);
2774 assert_eq!(route.paths[0][2].fee_msat, 0);
2775 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2776 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2777 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2779 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2780 assert_eq!(route.paths[0][3].short_channel_id, 8);
2781 assert_eq!(route.paths[0][3].fee_msat, 100);
2782 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2783 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2784 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2787 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2788 let zero_fees = RoutingFees {
2790 proportional_millionths: 0,
2792 vec![RouteHint(vec![RouteHintHop {
2793 src_node_id: nodes[4],
2794 short_channel_id: 11,
2796 cltv_expiry_delta: (11 << 4) | 1,
2797 htlc_minimum_msat: None,
2798 htlc_maximum_msat: None,
2800 src_node_id: nodes[3],
2801 short_channel_id: 8,
2803 cltv_expiry_delta: (8 << 4) | 1,
2804 htlc_minimum_msat: None,
2805 htlc_maximum_msat: None,
2806 }]), RouteHint(vec![RouteHintHop {
2807 src_node_id: nodes[4],
2808 short_channel_id: 9,
2811 proportional_millionths: 0,
2813 cltv_expiry_delta: (9 << 4) | 1,
2814 htlc_minimum_msat: None,
2815 htlc_maximum_msat: None,
2816 }]), RouteHint(vec![RouteHintHop {
2817 src_node_id: nodes[5],
2818 short_channel_id: 10,
2820 cltv_expiry_delta: (10 << 4) | 1,
2821 htlc_minimum_msat: None,
2822 htlc_maximum_msat: None,
2827 fn last_hops_with_public_channel_test() {
2828 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2829 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2830 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2831 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2832 // This test shows that public routes can be present in the invoice
2833 // which would be handled in the same manner.
2835 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2836 assert_eq!(route.paths[0].len(), 5);
2838 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2839 assert_eq!(route.paths[0][0].short_channel_id, 2);
2840 assert_eq!(route.paths[0][0].fee_msat, 100);
2841 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2842 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2843 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2845 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2846 assert_eq!(route.paths[0][1].short_channel_id, 4);
2847 assert_eq!(route.paths[0][1].fee_msat, 0);
2848 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2849 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2850 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2852 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2853 assert_eq!(route.paths[0][2].short_channel_id, 6);
2854 assert_eq!(route.paths[0][2].fee_msat, 0);
2855 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2856 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2857 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2859 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2860 assert_eq!(route.paths[0][3].short_channel_id, 11);
2861 assert_eq!(route.paths[0][3].fee_msat, 0);
2862 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2863 // If we have a peer in the node map, we'll use their features here since we don't have
2864 // a way of figuring out their features from the invoice:
2865 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2866 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2868 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2869 assert_eq!(route.paths[0][4].short_channel_id, 8);
2870 assert_eq!(route.paths[0][4].fee_msat, 100);
2871 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2872 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2873 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2877 fn our_chans_last_hop_connect_test() {
2878 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2879 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2880 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2882 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2883 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2884 let mut last_hops = last_hops(&nodes);
2885 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2886 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2887 assert_eq!(route.paths[0].len(), 2);
2889 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2890 assert_eq!(route.paths[0][0].short_channel_id, 42);
2891 assert_eq!(route.paths[0][0].fee_msat, 0);
2892 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2893 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2894 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2896 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2897 assert_eq!(route.paths[0][1].short_channel_id, 8);
2898 assert_eq!(route.paths[0][1].fee_msat, 100);
2899 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2900 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2901 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2903 last_hops[0].0[0].fees.base_msat = 1000;
2905 // Revert to via 6 as the fee on 8 goes up
2906 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
2907 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2908 assert_eq!(route.paths[0].len(), 4);
2910 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2911 assert_eq!(route.paths[0][0].short_channel_id, 2);
2912 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2913 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2914 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2915 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2917 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2918 assert_eq!(route.paths[0][1].short_channel_id, 4);
2919 assert_eq!(route.paths[0][1].fee_msat, 100);
2920 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
2921 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2922 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2924 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2925 assert_eq!(route.paths[0][2].short_channel_id, 7);
2926 assert_eq!(route.paths[0][2].fee_msat, 0);
2927 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
2928 // If we have a peer in the node map, we'll use their features here since we don't have
2929 // a way of figuring out their features from the invoice:
2930 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2931 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2933 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2934 assert_eq!(route.paths[0][3].short_channel_id, 10);
2935 assert_eq!(route.paths[0][3].fee_msat, 100);
2936 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2937 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2938 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2940 // ...but still use 8 for larger payments as 6 has a variable feerate
2941 let route = get_route(&our_id, &payment_params, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2942 assert_eq!(route.paths[0].len(), 5);
2944 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2945 assert_eq!(route.paths[0][0].short_channel_id, 2);
2946 assert_eq!(route.paths[0][0].fee_msat, 3000);
2947 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2948 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2949 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2951 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2952 assert_eq!(route.paths[0][1].short_channel_id, 4);
2953 assert_eq!(route.paths[0][1].fee_msat, 0);
2954 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2955 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2956 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2958 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2959 assert_eq!(route.paths[0][2].short_channel_id, 6);
2960 assert_eq!(route.paths[0][2].fee_msat, 0);
2961 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2962 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2963 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2965 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2966 assert_eq!(route.paths[0][3].short_channel_id, 11);
2967 assert_eq!(route.paths[0][3].fee_msat, 1000);
2968 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2969 // If we have a peer in the node map, we'll use their features here since we don't have
2970 // a way of figuring out their features from the invoice:
2971 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2972 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2974 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2975 assert_eq!(route.paths[0][4].short_channel_id, 8);
2976 assert_eq!(route.paths[0][4].fee_msat, 2000);
2977 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2978 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2979 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2982 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> {
2983 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2984 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2985 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2987 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2988 let last_hops = RouteHint(vec![RouteHintHop {
2989 src_node_id: middle_node_id,
2990 short_channel_id: 8,
2993 proportional_millionths: last_hop_fee_prop,
2995 cltv_expiry_delta: (8 << 4) | 1,
2996 htlc_minimum_msat: None,
2997 htlc_maximum_msat: last_hop_htlc_max,
2999 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3000 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3001 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3002 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)
3006 fn unannounced_path_test() {
3007 // We should be able to send a payment to a destination without any help of a routing graph
3008 // if we have a channel with a common counterparty that appears in the first and last hop
3010 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3012 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3013 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3014 assert_eq!(route.paths[0].len(), 2);
3016 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3017 assert_eq!(route.paths[0][0].short_channel_id, 42);
3018 assert_eq!(route.paths[0][0].fee_msat, 1001);
3019 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3020 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3021 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3023 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3024 assert_eq!(route.paths[0][1].short_channel_id, 8);
3025 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3026 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3027 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3028 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3032 fn overflow_unannounced_path_test_liquidity_underflow() {
3033 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3034 // the last-hop had a fee which overflowed a u64, we'd panic.
3035 // This was due to us adding the first-hop from us unconditionally, causing us to think
3036 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3037 // In this test, we previously hit a subtraction underflow due to having less available
3038 // liquidity at the last hop than 0.
3039 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());
3043 fn overflow_unannounced_path_test_feerate_overflow() {
3044 // This tests for the same case as above, except instead of hitting a subtraction
3045 // underflow, we hit a case where the fee charged at a hop overflowed.
3046 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());
3050 fn available_amount_while_routing_test() {
3051 // Tests whether we choose the correct available channel amount while routing.
3053 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3054 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3055 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3056 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3058 // We will use a simple single-path route from
3059 // our node to node2 via node0: channels {1, 3}.
3061 // First disable all other paths.
3062 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3064 short_channel_id: 2,
3067 cltv_expiry_delta: 0,
3068 htlc_minimum_msat: 0,
3069 htlc_maximum_msat: OptionalField::Present(100_000),
3071 fee_proportional_millionths: 0,
3072 excess_data: Vec::new()
3074 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3076 short_channel_id: 12,
3079 cltv_expiry_delta: 0,
3080 htlc_minimum_msat: 0,
3081 htlc_maximum_msat: OptionalField::Present(100_000),
3083 fee_proportional_millionths: 0,
3084 excess_data: Vec::new()
3087 // Make the first channel (#1) very permissive,
3088 // and we will be testing all limits on the second channel.
3089 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3090 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3091 short_channel_id: 1,
3094 cltv_expiry_delta: 0,
3095 htlc_minimum_msat: 0,
3096 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3098 fee_proportional_millionths: 0,
3099 excess_data: Vec::new()
3102 // First, let's see if routing works if we have absolutely no idea about the available amount.
3103 // In this case, it should be set to 250_000 sats.
3104 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3106 short_channel_id: 3,
3109 cltv_expiry_delta: 0,
3110 htlc_minimum_msat: 0,
3111 htlc_maximum_msat: OptionalField::Absent,
3113 fee_proportional_millionths: 0,
3114 excess_data: Vec::new()
3118 // Attempt to route more than available results in a failure.
3119 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3120 &our_id, &payment_params, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3121 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3122 } else { panic!(); }
3126 // Now, attempt to route an exact amount we have should be fine.
3127 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3128 assert_eq!(route.paths.len(), 1);
3129 let path = route.paths.last().unwrap();
3130 assert_eq!(path.len(), 2);
3131 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3132 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3135 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3136 // Disable channel #1 and use another first hop.
3137 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3139 short_channel_id: 1,
3142 cltv_expiry_delta: 0,
3143 htlc_minimum_msat: 0,
3144 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3146 fee_proportional_millionths: 0,
3147 excess_data: Vec::new()
3150 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3151 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3154 // Attempt to route more than available results in a failure.
3155 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3156 &our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3157 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3158 } else { panic!(); }
3162 // Now, attempt to route an exact amount we have should be fine.
3163 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();
3164 assert_eq!(route.paths.len(), 1);
3165 let path = route.paths.last().unwrap();
3166 assert_eq!(path.len(), 2);
3167 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3168 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3171 // Enable channel #1 back.
3172 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3174 short_channel_id: 1,
3177 cltv_expiry_delta: 0,
3178 htlc_minimum_msat: 0,
3179 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3181 fee_proportional_millionths: 0,
3182 excess_data: Vec::new()
3186 // Now let's see if routing works if we know only htlc_maximum_msat.
3187 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3188 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3189 short_channel_id: 3,
3192 cltv_expiry_delta: 0,
3193 htlc_minimum_msat: 0,
3194 htlc_maximum_msat: OptionalField::Present(15_000),
3196 fee_proportional_millionths: 0,
3197 excess_data: Vec::new()
3201 // Attempt to route more than available results in a failure.
3202 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3203 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3204 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3205 } else { panic!(); }
3209 // Now, attempt to route an exact amount we have should be fine.
3210 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3211 assert_eq!(route.paths.len(), 1);
3212 let path = route.paths.last().unwrap();
3213 assert_eq!(path.len(), 2);
3214 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3215 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3218 // Now let's see if routing works if we know only capacity from the UTXO.
3220 // We can't change UTXO capacity on the fly, so we'll disable
3221 // the existing channel and add another one with the capacity we need.
3222 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3224 short_channel_id: 3,
3227 cltv_expiry_delta: 0,
3228 htlc_minimum_msat: 0,
3229 htlc_maximum_msat: OptionalField::Absent,
3231 fee_proportional_millionths: 0,
3232 excess_data: Vec::new()
3235 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3236 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3237 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3238 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3239 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3241 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3242 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3244 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3245 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3247 short_channel_id: 333,
3250 cltv_expiry_delta: (3 << 4) | 1,
3251 htlc_minimum_msat: 0,
3252 htlc_maximum_msat: OptionalField::Absent,
3254 fee_proportional_millionths: 0,
3255 excess_data: Vec::new()
3257 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3259 short_channel_id: 333,
3262 cltv_expiry_delta: (3 << 4) | 2,
3263 htlc_minimum_msat: 0,
3264 htlc_maximum_msat: OptionalField::Absent,
3266 fee_proportional_millionths: 0,
3267 excess_data: Vec::new()
3271 // Attempt to route more than available results in a failure.
3272 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3273 &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3274 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3275 } else { panic!(); }
3279 // Now, attempt to route an exact amount we have should be fine.
3280 let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3281 assert_eq!(route.paths.len(), 1);
3282 let path = route.paths.last().unwrap();
3283 assert_eq!(path.len(), 2);
3284 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3285 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3288 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3289 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3290 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3291 short_channel_id: 333,
3294 cltv_expiry_delta: 0,
3295 htlc_minimum_msat: 0,
3296 htlc_maximum_msat: OptionalField::Present(10_000),
3298 fee_proportional_millionths: 0,
3299 excess_data: Vec::new()
3303 // Attempt to route more than available results in a failure.
3304 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3305 &our_id, &payment_params, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3306 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3307 } else { panic!(); }
3311 // Now, attempt to route an exact amount we have should be fine.
3312 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3313 assert_eq!(route.paths.len(), 1);
3314 let path = route.paths.last().unwrap();
3315 assert_eq!(path.len(), 2);
3316 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3317 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3322 fn available_liquidity_last_hop_test() {
3323 // Check that available liquidity properly limits the path even when only
3324 // one of the latter hops is limited.
3325 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3326 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3327 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3328 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3330 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3331 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3332 // Total capacity: 50 sats.
3334 // Disable other potential paths.
3335 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3337 short_channel_id: 2,
3340 cltv_expiry_delta: 0,
3341 htlc_minimum_msat: 0,
3342 htlc_maximum_msat: OptionalField::Present(100_000),
3344 fee_proportional_millionths: 0,
3345 excess_data: Vec::new()
3347 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3349 short_channel_id: 7,
3352 cltv_expiry_delta: 0,
3353 htlc_minimum_msat: 0,
3354 htlc_maximum_msat: OptionalField::Present(100_000),
3356 fee_proportional_millionths: 0,
3357 excess_data: Vec::new()
3362 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3364 short_channel_id: 12,
3367 cltv_expiry_delta: 0,
3368 htlc_minimum_msat: 0,
3369 htlc_maximum_msat: OptionalField::Present(100_000),
3371 fee_proportional_millionths: 0,
3372 excess_data: Vec::new()
3374 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3375 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3376 short_channel_id: 13,
3379 cltv_expiry_delta: 0,
3380 htlc_minimum_msat: 0,
3381 htlc_maximum_msat: OptionalField::Present(100_000),
3383 fee_proportional_millionths: 0,
3384 excess_data: Vec::new()
3387 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3389 short_channel_id: 6,
3392 cltv_expiry_delta: 0,
3393 htlc_minimum_msat: 0,
3394 htlc_maximum_msat: OptionalField::Present(50_000),
3396 fee_proportional_millionths: 0,
3397 excess_data: Vec::new()
3399 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3400 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3401 short_channel_id: 11,
3404 cltv_expiry_delta: 0,
3405 htlc_minimum_msat: 0,
3406 htlc_maximum_msat: OptionalField::Present(100_000),
3408 fee_proportional_millionths: 0,
3409 excess_data: Vec::new()
3412 // Attempt to route more than available results in a failure.
3413 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3414 &our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3415 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3416 } else { panic!(); }
3420 // Now, attempt to route 49 sats (just a bit below the capacity).
3421 let route = get_route(&our_id, &payment_params, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3422 assert_eq!(route.paths.len(), 1);
3423 let mut total_amount_paid_msat = 0;
3424 for path in &route.paths {
3425 assert_eq!(path.len(), 4);
3426 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3427 total_amount_paid_msat += path.last().unwrap().fee_msat;
3429 assert_eq!(total_amount_paid_msat, 49_000);
3433 // Attempt to route an exact amount is also fine
3434 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3435 assert_eq!(route.paths.len(), 1);
3436 let mut total_amount_paid_msat = 0;
3437 for path in &route.paths {
3438 assert_eq!(path.len(), 4);
3439 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3440 total_amount_paid_msat += path.last().unwrap().fee_msat;
3442 assert_eq!(total_amount_paid_msat, 50_000);
3447 fn ignore_fee_first_hop_test() {
3448 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3449 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3450 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3451 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3453 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3454 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3455 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3456 short_channel_id: 1,
3459 cltv_expiry_delta: 0,
3460 htlc_minimum_msat: 0,
3461 htlc_maximum_msat: OptionalField::Present(100_000),
3462 fee_base_msat: 1_000_000,
3463 fee_proportional_millionths: 0,
3464 excess_data: Vec::new()
3466 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3467 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3468 short_channel_id: 3,
3471 cltv_expiry_delta: 0,
3472 htlc_minimum_msat: 0,
3473 htlc_maximum_msat: OptionalField::Present(50_000),
3475 fee_proportional_millionths: 0,
3476 excess_data: Vec::new()
3480 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3481 assert_eq!(route.paths.len(), 1);
3482 let mut total_amount_paid_msat = 0;
3483 for path in &route.paths {
3484 assert_eq!(path.len(), 2);
3485 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3486 total_amount_paid_msat += path.last().unwrap().fee_msat;
3488 assert_eq!(total_amount_paid_msat, 50_000);
3493 fn simple_mpp_route_test() {
3494 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3495 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3496 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3497 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3499 // We need a route consisting of 3 paths:
3500 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3501 // To achieve this, the amount being transferred should be around
3502 // the total capacity of these 3 paths.
3504 // First, we set limits on these (previously unlimited) channels.
3505 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3507 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3508 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3509 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3510 short_channel_id: 1,
3513 cltv_expiry_delta: 0,
3514 htlc_minimum_msat: 0,
3515 htlc_maximum_msat: OptionalField::Present(100_000),
3517 fee_proportional_millionths: 0,
3518 excess_data: Vec::new()
3520 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3521 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3522 short_channel_id: 3,
3525 cltv_expiry_delta: 0,
3526 htlc_minimum_msat: 0,
3527 htlc_maximum_msat: OptionalField::Present(50_000),
3529 fee_proportional_millionths: 0,
3530 excess_data: Vec::new()
3533 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3534 // (total limit 60).
3535 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3536 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3537 short_channel_id: 12,
3540 cltv_expiry_delta: 0,
3541 htlc_minimum_msat: 0,
3542 htlc_maximum_msat: OptionalField::Present(60_000),
3544 fee_proportional_millionths: 0,
3545 excess_data: Vec::new()
3547 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3548 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3549 short_channel_id: 13,
3552 cltv_expiry_delta: 0,
3553 htlc_minimum_msat: 0,
3554 htlc_maximum_msat: OptionalField::Present(60_000),
3556 fee_proportional_millionths: 0,
3557 excess_data: Vec::new()
3560 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3561 // (total capacity 180 sats).
3562 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3563 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3564 short_channel_id: 2,
3567 cltv_expiry_delta: 0,
3568 htlc_minimum_msat: 0,
3569 htlc_maximum_msat: OptionalField::Present(200_000),
3571 fee_proportional_millionths: 0,
3572 excess_data: Vec::new()
3574 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3576 short_channel_id: 4,
3579 cltv_expiry_delta: 0,
3580 htlc_minimum_msat: 0,
3581 htlc_maximum_msat: OptionalField::Present(180_000),
3583 fee_proportional_millionths: 0,
3584 excess_data: Vec::new()
3588 // Attempt to route more than available results in a failure.
3589 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3590 &our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3591 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3592 } else { panic!(); }
3596 // Now, attempt to route 250 sats (just a bit below the capacity).
3597 // Our algorithm should provide us with these 3 paths.
3598 let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3599 assert_eq!(route.paths.len(), 3);
3600 let mut total_amount_paid_msat = 0;
3601 for path in &route.paths {
3602 assert_eq!(path.len(), 2);
3603 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3604 total_amount_paid_msat += path.last().unwrap().fee_msat;
3606 assert_eq!(total_amount_paid_msat, 250_000);
3610 // Attempt to route an exact amount is also fine
3611 let route = get_route(&our_id, &payment_params, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3612 assert_eq!(route.paths.len(), 3);
3613 let mut total_amount_paid_msat = 0;
3614 for path in &route.paths {
3615 assert_eq!(path.len(), 2);
3616 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3617 total_amount_paid_msat += path.last().unwrap().fee_msat;
3619 assert_eq!(total_amount_paid_msat, 290_000);
3624 fn long_mpp_route_test() {
3625 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3626 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3627 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3628 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3630 // We need a route consisting of 3 paths:
3631 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3632 // Note that these paths overlap (channels 5, 12, 13).
3633 // We will route 300 sats.
3634 // Each path will have 100 sats capacity, those channels which
3635 // are used twice will have 200 sats capacity.
3637 // Disable other potential paths.
3638 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3640 short_channel_id: 2,
3643 cltv_expiry_delta: 0,
3644 htlc_minimum_msat: 0,
3645 htlc_maximum_msat: OptionalField::Present(100_000),
3647 fee_proportional_millionths: 0,
3648 excess_data: Vec::new()
3650 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3651 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3652 short_channel_id: 7,
3655 cltv_expiry_delta: 0,
3656 htlc_minimum_msat: 0,
3657 htlc_maximum_msat: OptionalField::Present(100_000),
3659 fee_proportional_millionths: 0,
3660 excess_data: Vec::new()
3663 // Path via {node0, node2} is channels {1, 3, 5}.
3664 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3665 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3666 short_channel_id: 1,
3669 cltv_expiry_delta: 0,
3670 htlc_minimum_msat: 0,
3671 htlc_maximum_msat: OptionalField::Present(100_000),
3673 fee_proportional_millionths: 0,
3674 excess_data: Vec::new()
3676 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3677 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3678 short_channel_id: 3,
3681 cltv_expiry_delta: 0,
3682 htlc_minimum_msat: 0,
3683 htlc_maximum_msat: OptionalField::Present(100_000),
3685 fee_proportional_millionths: 0,
3686 excess_data: Vec::new()
3689 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3690 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3691 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3693 short_channel_id: 5,
3696 cltv_expiry_delta: 0,
3697 htlc_minimum_msat: 0,
3698 htlc_maximum_msat: OptionalField::Present(200_000),
3700 fee_proportional_millionths: 0,
3701 excess_data: Vec::new()
3704 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3705 // Add 100 sats to the capacities of {12, 13}, because these channels
3706 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3707 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3708 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3709 short_channel_id: 12,
3712 cltv_expiry_delta: 0,
3713 htlc_minimum_msat: 0,
3714 htlc_maximum_msat: OptionalField::Present(200_000),
3716 fee_proportional_millionths: 0,
3717 excess_data: Vec::new()
3719 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3720 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3721 short_channel_id: 13,
3724 cltv_expiry_delta: 0,
3725 htlc_minimum_msat: 0,
3726 htlc_maximum_msat: OptionalField::Present(200_000),
3728 fee_proportional_millionths: 0,
3729 excess_data: Vec::new()
3732 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3734 short_channel_id: 6,
3737 cltv_expiry_delta: 0,
3738 htlc_minimum_msat: 0,
3739 htlc_maximum_msat: OptionalField::Present(100_000),
3741 fee_proportional_millionths: 0,
3742 excess_data: Vec::new()
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 11,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: OptionalField::Present(100_000),
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3757 // Path via {node7, node2} is channels {12, 13, 5}.
3758 // We already limited them to 200 sats (they are used twice for 100 sats).
3759 // Nothing to do here.
3762 // Attempt to route more than available results in a failure.
3763 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3764 &our_id, &payment_params, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3765 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3766 } else { panic!(); }
3770 // Now, attempt to route 300 sats (exact amount we can route).
3771 // Our algorithm should provide us with these 3 paths, 100 sats each.
3772 let route = get_route(&our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3773 assert_eq!(route.paths.len(), 3);
3775 let mut total_amount_paid_msat = 0;
3776 for path in &route.paths {
3777 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3778 total_amount_paid_msat += path.last().unwrap().fee_msat;
3780 assert_eq!(total_amount_paid_msat, 300_000);
3786 fn mpp_cheaper_route_test() {
3787 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3788 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3789 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3790 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3792 // This test checks that if we have two cheaper paths and one more expensive path,
3793 // so that liquidity-wise any 2 of 3 combination is sufficient,
3794 // two cheaper paths will be taken.
3795 // These paths have equal available liquidity.
3797 // We need a combination of 3 paths:
3798 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3799 // Note that these paths overlap (channels 5, 12, 13).
3800 // Each path will have 100 sats capacity, those channels which
3801 // are used twice will have 200 sats capacity.
3803 // Disable other potential paths.
3804 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3806 short_channel_id: 2,
3809 cltv_expiry_delta: 0,
3810 htlc_minimum_msat: 0,
3811 htlc_maximum_msat: OptionalField::Present(100_000),
3813 fee_proportional_millionths: 0,
3814 excess_data: Vec::new()
3816 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3818 short_channel_id: 7,
3821 cltv_expiry_delta: 0,
3822 htlc_minimum_msat: 0,
3823 htlc_maximum_msat: OptionalField::Present(100_000),
3825 fee_proportional_millionths: 0,
3826 excess_data: Vec::new()
3829 // Path via {node0, node2} is channels {1, 3, 5}.
3830 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3832 short_channel_id: 1,
3835 cltv_expiry_delta: 0,
3836 htlc_minimum_msat: 0,
3837 htlc_maximum_msat: OptionalField::Present(100_000),
3839 fee_proportional_millionths: 0,
3840 excess_data: Vec::new()
3842 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3843 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3844 short_channel_id: 3,
3847 cltv_expiry_delta: 0,
3848 htlc_minimum_msat: 0,
3849 htlc_maximum_msat: OptionalField::Present(100_000),
3851 fee_proportional_millionths: 0,
3852 excess_data: Vec::new()
3855 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3856 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3857 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3858 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3859 short_channel_id: 5,
3862 cltv_expiry_delta: 0,
3863 htlc_minimum_msat: 0,
3864 htlc_maximum_msat: OptionalField::Present(200_000),
3866 fee_proportional_millionths: 0,
3867 excess_data: Vec::new()
3870 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3871 // Add 100 sats to the capacities of {12, 13}, because these channels
3872 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3873 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3874 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3875 short_channel_id: 12,
3878 cltv_expiry_delta: 0,
3879 htlc_minimum_msat: 0,
3880 htlc_maximum_msat: OptionalField::Present(200_000),
3882 fee_proportional_millionths: 0,
3883 excess_data: Vec::new()
3885 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3886 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3887 short_channel_id: 13,
3890 cltv_expiry_delta: 0,
3891 htlc_minimum_msat: 0,
3892 htlc_maximum_msat: OptionalField::Present(200_000),
3894 fee_proportional_millionths: 0,
3895 excess_data: Vec::new()
3898 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3899 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3900 short_channel_id: 6,
3903 cltv_expiry_delta: 0,
3904 htlc_minimum_msat: 0,
3905 htlc_maximum_msat: OptionalField::Present(100_000),
3906 fee_base_msat: 1_000,
3907 fee_proportional_millionths: 0,
3908 excess_data: Vec::new()
3910 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3912 short_channel_id: 11,
3915 cltv_expiry_delta: 0,
3916 htlc_minimum_msat: 0,
3917 htlc_maximum_msat: OptionalField::Present(100_000),
3919 fee_proportional_millionths: 0,
3920 excess_data: Vec::new()
3923 // Path via {node7, node2} is channels {12, 13, 5}.
3924 // We already limited them to 200 sats (they are used twice for 100 sats).
3925 // Nothing to do here.
3928 // Now, attempt to route 180 sats.
3929 // Our algorithm should provide us with these 2 paths.
3930 let route = get_route(&our_id, &payment_params, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3931 assert_eq!(route.paths.len(), 2);
3933 let mut total_value_transferred_msat = 0;
3934 let mut total_paid_msat = 0;
3935 for path in &route.paths {
3936 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3937 total_value_transferred_msat += path.last().unwrap().fee_msat;
3939 total_paid_msat += hop.fee_msat;
3942 // If we paid fee, this would be higher.
3943 assert_eq!(total_value_transferred_msat, 180_000);
3944 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3945 assert_eq!(total_fees_paid, 0);
3950 fn fees_on_mpp_route_test() {
3951 // This test makes sure that MPP algorithm properly takes into account
3952 // fees charged on the channels, by making the fees impactful:
3953 // if the fee is not properly accounted for, the behavior is different.
3954 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3955 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3956 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3957 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3959 // We need a route consisting of 2 paths:
3960 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3961 // We will route 200 sats, Each path will have 100 sats capacity.
3963 // This test is not particularly stable: e.g.,
3964 // there's a way to route via {node0, node2, node4}.
3965 // It works while pathfinding is deterministic, but can be broken otherwise.
3966 // It's fine to ignore this concern for now.
3968 // Disable other potential paths.
3969 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3970 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3971 short_channel_id: 2,
3974 cltv_expiry_delta: 0,
3975 htlc_minimum_msat: 0,
3976 htlc_maximum_msat: OptionalField::Present(100_000),
3978 fee_proportional_millionths: 0,
3979 excess_data: Vec::new()
3982 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3983 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3984 short_channel_id: 7,
3987 cltv_expiry_delta: 0,
3988 htlc_minimum_msat: 0,
3989 htlc_maximum_msat: OptionalField::Present(100_000),
3991 fee_proportional_millionths: 0,
3992 excess_data: Vec::new()
3995 // Path via {node0, node2} is channels {1, 3, 5}.
3996 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3998 short_channel_id: 1,
4001 cltv_expiry_delta: 0,
4002 htlc_minimum_msat: 0,
4003 htlc_maximum_msat: OptionalField::Present(100_000),
4005 fee_proportional_millionths: 0,
4006 excess_data: Vec::new()
4008 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4009 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4010 short_channel_id: 3,
4013 cltv_expiry_delta: 0,
4014 htlc_minimum_msat: 0,
4015 htlc_maximum_msat: OptionalField::Present(100_000),
4017 fee_proportional_millionths: 0,
4018 excess_data: Vec::new()
4021 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4022 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4024 short_channel_id: 5,
4027 cltv_expiry_delta: 0,
4028 htlc_minimum_msat: 0,
4029 htlc_maximum_msat: OptionalField::Present(100_000),
4031 fee_proportional_millionths: 0,
4032 excess_data: Vec::new()
4035 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4036 // All channels should be 100 sats capacity. But for the fee experiment,
4037 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4038 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4039 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4040 // so no matter how large are other channels,
4041 // the whole path will be limited by 100 sats with just these 2 conditions:
4042 // - channel 12 capacity is 250 sats
4043 // - fee for channel 6 is 150 sats
4044 // Let's test this by enforcing these 2 conditions and removing other limits.
4045 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4046 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4047 short_channel_id: 12,
4050 cltv_expiry_delta: 0,
4051 htlc_minimum_msat: 0,
4052 htlc_maximum_msat: OptionalField::Present(250_000),
4054 fee_proportional_millionths: 0,
4055 excess_data: Vec::new()
4057 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4058 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4059 short_channel_id: 13,
4062 cltv_expiry_delta: 0,
4063 htlc_minimum_msat: 0,
4064 htlc_maximum_msat: OptionalField::Absent,
4066 fee_proportional_millionths: 0,
4067 excess_data: Vec::new()
4070 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4071 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4072 short_channel_id: 6,
4075 cltv_expiry_delta: 0,
4076 htlc_minimum_msat: 0,
4077 htlc_maximum_msat: OptionalField::Absent,
4078 fee_base_msat: 150_000,
4079 fee_proportional_millionths: 0,
4080 excess_data: Vec::new()
4082 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4083 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4084 short_channel_id: 11,
4087 cltv_expiry_delta: 0,
4088 htlc_minimum_msat: 0,
4089 htlc_maximum_msat: OptionalField::Absent,
4091 fee_proportional_millionths: 0,
4092 excess_data: Vec::new()
4096 // Attempt to route more than available results in a failure.
4097 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4098 &our_id, &payment_params, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4099 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4100 } else { panic!(); }
4104 // Now, attempt to route 200 sats (exact amount we can route).
4105 let route = get_route(&our_id, &payment_params, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4106 assert_eq!(route.paths.len(), 2);
4108 let mut total_amount_paid_msat = 0;
4109 for path in &route.paths {
4110 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4111 total_amount_paid_msat += path.last().unwrap().fee_msat;
4113 assert_eq!(total_amount_paid_msat, 200_000);
4114 assert_eq!(route.get_total_fees(), 150_000);
4119 fn mpp_with_last_hops() {
4120 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4121 // via a single last-hop route hint, we'd fail to route if we first collected routes
4122 // totaling close but not quite enough to fund the full payment.
4124 // This was because we considered last-hop hints to have exactly the sought payment amount
4125 // instead of the amount we were trying to collect, needlessly limiting our path searching
4126 // at the very first hop.
4128 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4129 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4130 // to only have the remaining to-collect amount in available liquidity.
4132 // This bug appeared in production in some specific channel configurations.
4133 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4134 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4135 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4136 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4137 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4138 src_node_id: nodes[2],
4139 short_channel_id: 42,
4140 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4141 cltv_expiry_delta: 42,
4142 htlc_minimum_msat: None,
4143 htlc_maximum_msat: None,
4146 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4147 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4148 // would first use the no-fee route and then fail to find a path along the second route as
4149 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4150 // under 5% of our payment amount.
4151 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4152 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4153 short_channel_id: 1,
4156 cltv_expiry_delta: (5 << 4) | 5,
4157 htlc_minimum_msat: 0,
4158 htlc_maximum_msat: OptionalField::Present(99_000),
4159 fee_base_msat: u32::max_value(),
4160 fee_proportional_millionths: u32::max_value(),
4161 excess_data: Vec::new()
4163 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4165 short_channel_id: 2,
4168 cltv_expiry_delta: (5 << 4) | 3,
4169 htlc_minimum_msat: 0,
4170 htlc_maximum_msat: OptionalField::Present(99_000),
4171 fee_base_msat: u32::max_value(),
4172 fee_proportional_millionths: u32::max_value(),
4173 excess_data: Vec::new()
4175 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4176 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4177 short_channel_id: 4,
4180 cltv_expiry_delta: (4 << 4) | 1,
4181 htlc_minimum_msat: 0,
4182 htlc_maximum_msat: OptionalField::Absent,
4184 fee_proportional_millionths: 0,
4185 excess_data: Vec::new()
4187 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4188 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4189 short_channel_id: 13,
4191 flags: 0|2, // Channel disabled
4192 cltv_expiry_delta: (13 << 4) | 1,
4193 htlc_minimum_msat: 0,
4194 htlc_maximum_msat: OptionalField::Absent,
4196 fee_proportional_millionths: 2000000,
4197 excess_data: Vec::new()
4200 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4202 let route = get_route(&our_id, &payment_params, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4203 assert_eq!(route.paths.len(), 2);
4204 // Paths are somewhat randomly ordered, but:
4205 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4206 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4207 assert_eq!(route.paths[0][0].short_channel_id, 2);
4208 assert_eq!(route.paths[0][0].fee_msat, 1);
4209 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4210 assert_eq!(route.paths[1][0].short_channel_id, 1);
4211 assert_eq!(route.paths[1][0].fee_msat, 0);
4212 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4213 assert_eq!(route.get_total_fees(), 1);
4214 assert_eq!(route.get_total_amount(), 100_000);
4218 fn drop_lowest_channel_mpp_route_test() {
4219 // This test checks that low-capacity channel is dropped when after
4220 // path finding we realize that we found more capacity than we need.
4221 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4222 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4223 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4224 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4226 // We need a route consisting of 3 paths:
4227 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4229 // The first and the second paths should be sufficient, but the third should be
4230 // cheaper, so that we select it but drop later.
4232 // First, we set limits on these (previously unlimited) channels.
4233 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4235 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4236 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4238 short_channel_id: 1,
4241 cltv_expiry_delta: 0,
4242 htlc_minimum_msat: 0,
4243 htlc_maximum_msat: OptionalField::Present(100_000),
4245 fee_proportional_millionths: 0,
4246 excess_data: Vec::new()
4248 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4250 short_channel_id: 3,
4253 cltv_expiry_delta: 0,
4254 htlc_minimum_msat: 0,
4255 htlc_maximum_msat: OptionalField::Present(50_000),
4257 fee_proportional_millionths: 0,
4258 excess_data: Vec::new()
4261 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4262 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4263 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4264 short_channel_id: 12,
4267 cltv_expiry_delta: 0,
4268 htlc_minimum_msat: 0,
4269 htlc_maximum_msat: OptionalField::Present(60_000),
4271 fee_proportional_millionths: 0,
4272 excess_data: Vec::new()
4274 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4275 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4276 short_channel_id: 13,
4279 cltv_expiry_delta: 0,
4280 htlc_minimum_msat: 0,
4281 htlc_maximum_msat: OptionalField::Present(60_000),
4283 fee_proportional_millionths: 0,
4284 excess_data: Vec::new()
4287 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4288 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4289 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4290 short_channel_id: 2,
4293 cltv_expiry_delta: 0,
4294 htlc_minimum_msat: 0,
4295 htlc_maximum_msat: OptionalField::Present(20_000),
4297 fee_proportional_millionths: 0,
4298 excess_data: Vec::new()
4300 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4302 short_channel_id: 4,
4305 cltv_expiry_delta: 0,
4306 htlc_minimum_msat: 0,
4307 htlc_maximum_msat: OptionalField::Present(20_000),
4309 fee_proportional_millionths: 0,
4310 excess_data: Vec::new()
4314 // Attempt to route more than available results in a failure.
4315 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4316 &our_id, &payment_params, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4317 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4318 } else { panic!(); }
4322 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4323 // Our algorithm should provide us with these 3 paths.
4324 let route = get_route(&our_id, &payment_params, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4325 assert_eq!(route.paths.len(), 3);
4326 let mut total_amount_paid_msat = 0;
4327 for path in &route.paths {
4328 assert_eq!(path.len(), 2);
4329 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4330 total_amount_paid_msat += path.last().unwrap().fee_msat;
4332 assert_eq!(total_amount_paid_msat, 125_000);
4336 // Attempt to route without the last small cheap channel
4337 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4338 assert_eq!(route.paths.len(), 2);
4339 let mut total_amount_paid_msat = 0;
4340 for path in &route.paths {
4341 assert_eq!(path.len(), 2);
4342 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4343 total_amount_paid_msat += path.last().unwrap().fee_msat;
4345 assert_eq!(total_amount_paid_msat, 90_000);
4350 fn min_criteria_consistency() {
4351 // Test that we don't use an inconsistent metric between updating and walking nodes during
4352 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4353 // was updated with a different criterion from the heap sorting, resulting in loops in
4354 // calculated paths. We test for that specific case here.
4356 // We construct a network that looks like this:
4358 // node2 -1(3)2- node3
4362 // node1 -1(5)2- node4 -1(1)2- node6
4368 // We create a loop on the side of our real path - our destination is node 6, with a
4369 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4370 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4371 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4372 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4373 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4374 // "previous hop" being set to node 3, creating a loop in the path.
4375 let secp_ctx = Secp256k1::new();
4376 let logger = Arc::new(test_utils::TestLogger::new());
4377 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4378 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4379 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4380 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4381 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4383 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4384 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4385 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4386 short_channel_id: 6,
4389 cltv_expiry_delta: (6 << 4) | 0,
4390 htlc_minimum_msat: 0,
4391 htlc_maximum_msat: OptionalField::Absent,
4393 fee_proportional_millionths: 0,
4394 excess_data: Vec::new()
4396 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4398 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4399 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4400 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4401 short_channel_id: 5,
4404 cltv_expiry_delta: (5 << 4) | 0,
4405 htlc_minimum_msat: 0,
4406 htlc_maximum_msat: OptionalField::Absent,
4408 fee_proportional_millionths: 0,
4409 excess_data: Vec::new()
4411 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4413 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4414 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4416 short_channel_id: 4,
4419 cltv_expiry_delta: (4 << 4) | 0,
4420 htlc_minimum_msat: 0,
4421 htlc_maximum_msat: OptionalField::Absent,
4423 fee_proportional_millionths: 0,
4424 excess_data: Vec::new()
4426 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4428 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4429 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4430 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4431 short_channel_id: 3,
4434 cltv_expiry_delta: (3 << 4) | 0,
4435 htlc_minimum_msat: 0,
4436 htlc_maximum_msat: OptionalField::Absent,
4438 fee_proportional_millionths: 0,
4439 excess_data: Vec::new()
4441 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4443 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4444 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4445 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4446 short_channel_id: 2,
4449 cltv_expiry_delta: (2 << 4) | 0,
4450 htlc_minimum_msat: 0,
4451 htlc_maximum_msat: OptionalField::Absent,
4453 fee_proportional_millionths: 0,
4454 excess_data: Vec::new()
4457 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4458 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4459 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4460 short_channel_id: 1,
4463 cltv_expiry_delta: (1 << 4) | 0,
4464 htlc_minimum_msat: 100,
4465 htlc_maximum_msat: OptionalField::Absent,
4467 fee_proportional_millionths: 0,
4468 excess_data: Vec::new()
4470 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4473 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4474 let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4475 assert_eq!(route.paths.len(), 1);
4476 assert_eq!(route.paths[0].len(), 3);
4478 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4479 assert_eq!(route.paths[0][0].short_channel_id, 6);
4480 assert_eq!(route.paths[0][0].fee_msat, 100);
4481 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4482 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4483 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4485 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4486 assert_eq!(route.paths[0][1].short_channel_id, 5);
4487 assert_eq!(route.paths[0][1].fee_msat, 0);
4488 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4489 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4490 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4492 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4493 assert_eq!(route.paths[0][2].short_channel_id, 1);
4494 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4495 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4496 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4497 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4503 fn exact_fee_liquidity_limit() {
4504 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4505 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4506 // we calculated fees on a higher value, resulting in us ignoring such paths.
4507 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4508 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4509 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4510 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4512 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4514 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4516 short_channel_id: 2,
4519 cltv_expiry_delta: 0,
4520 htlc_minimum_msat: 0,
4521 htlc_maximum_msat: OptionalField::Present(85_000),
4523 fee_proportional_millionths: 0,
4524 excess_data: Vec::new()
4527 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4529 short_channel_id: 12,
4532 cltv_expiry_delta: (4 << 4) | 1,
4533 htlc_minimum_msat: 0,
4534 htlc_maximum_msat: OptionalField::Present(270_000),
4536 fee_proportional_millionths: 1000000,
4537 excess_data: Vec::new()
4541 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4542 // 200% fee charged channel 13 in the 1-to-2 direction.
4543 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4544 assert_eq!(route.paths.len(), 1);
4545 assert_eq!(route.paths[0].len(), 2);
4547 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4548 assert_eq!(route.paths[0][0].short_channel_id, 12);
4549 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4550 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4551 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4552 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4554 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4555 assert_eq!(route.paths[0][1].short_channel_id, 13);
4556 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4557 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4558 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4559 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4564 fn htlc_max_reduction_below_min() {
4565 // Test that if, while walking the graph, we reduce the value being sent to meet an
4566 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4567 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4568 // resulting in us thinking there is no possible path, even if other paths exist.
4569 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4570 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4571 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4572 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4574 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4575 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4576 // then try to send 90_000.
4577 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4578 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4579 short_channel_id: 2,
4582 cltv_expiry_delta: 0,
4583 htlc_minimum_msat: 0,
4584 htlc_maximum_msat: OptionalField::Present(80_000),
4586 fee_proportional_millionths: 0,
4587 excess_data: Vec::new()
4589 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4590 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4591 short_channel_id: 4,
4594 cltv_expiry_delta: (4 << 4) | 1,
4595 htlc_minimum_msat: 90_000,
4596 htlc_maximum_msat: OptionalField::Absent,
4598 fee_proportional_millionths: 0,
4599 excess_data: Vec::new()
4603 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4604 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4605 // expensive) channels 12-13 path.
4606 let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4607 assert_eq!(route.paths.len(), 1);
4608 assert_eq!(route.paths[0].len(), 2);
4610 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4611 assert_eq!(route.paths[0][0].short_channel_id, 12);
4612 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4613 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4614 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4615 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4617 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4618 assert_eq!(route.paths[0][1].short_channel_id, 13);
4619 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4620 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4621 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4622 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4627 fn multiple_direct_first_hops() {
4628 // Previously we'd only ever considered one first hop path per counterparty.
4629 // However, as we don't restrict users to one channel per peer, we really need to support
4630 // looking at all first hop paths.
4631 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4632 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4633 // route over multiple channels with the same first hop.
4634 let secp_ctx = Secp256k1::new();
4635 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4636 let logger = Arc::new(test_utils::TestLogger::new());
4637 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4638 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4639 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4642 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4643 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4644 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4645 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4646 assert_eq!(route.paths.len(), 1);
4647 assert_eq!(route.paths[0].len(), 1);
4649 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4650 assert_eq!(route.paths[0][0].short_channel_id, 3);
4651 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4654 let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4655 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4656 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4657 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4658 assert_eq!(route.paths.len(), 2);
4659 assert_eq!(route.paths[0].len(), 1);
4660 assert_eq!(route.paths[1].len(), 1);
4662 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4663 assert_eq!(route.paths[0][0].short_channel_id, 3);
4664 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4666 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4667 assert_eq!(route.paths[1][0].short_channel_id, 2);
4668 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4673 fn prefers_shorter_route_with_higher_fees() {
4674 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4675 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4676 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4678 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4679 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4680 let route = get_route(
4681 &our_id, &payment_params, &network_graph, None, 100, 42,
4682 Arc::clone(&logger), &scorer
4684 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4686 assert_eq!(route.get_total_fees(), 100);
4687 assert_eq!(route.get_total_amount(), 100);
4688 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4690 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4691 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4692 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4693 let route = get_route(
4694 &our_id, &payment_params, &network_graph, None, 100, 42,
4695 Arc::clone(&logger), &scorer
4697 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4699 assert_eq!(route.get_total_fees(), 300);
4700 assert_eq!(route.get_total_amount(), 100);
4701 assert_eq!(path, vec![2, 4, 7, 10]);
4704 struct BadChannelScorer {
4705 short_channel_id: u64,
4709 impl Writeable for BadChannelScorer {
4710 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4712 impl Score for BadChannelScorer {
4713 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4714 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4717 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4718 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4721 struct BadNodeScorer {
4726 impl Writeable for BadNodeScorer {
4727 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4730 impl Score for BadNodeScorer {
4731 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4732 if *target == self.node_id { u64::max_value() } else { 0 }
4735 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4736 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4740 fn avoids_routing_through_bad_channels_and_nodes() {
4741 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4742 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4743 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4745 // A path to nodes[6] exists when no penalties are applied to any channel.
4746 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4747 let route = get_route(
4748 &our_id, &payment_params, &network_graph, None, 100, 42,
4749 Arc::clone(&logger), &scorer
4751 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4753 assert_eq!(route.get_total_fees(), 100);
4754 assert_eq!(route.get_total_amount(), 100);
4755 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4757 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4758 let scorer = BadChannelScorer { short_channel_id: 6 };
4759 let route = get_route(
4760 &our_id, &payment_params, &network_graph, None, 100, 42,
4761 Arc::clone(&logger), &scorer
4763 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4765 assert_eq!(route.get_total_fees(), 300);
4766 assert_eq!(route.get_total_amount(), 100);
4767 assert_eq!(path, vec![2, 4, 7, 10]);
4769 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4770 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4772 &our_id, &payment_params, &network_graph, None, 100, 42,
4773 Arc::clone(&logger), &scorer
4775 Err(LightningError { err, .. } ) => {
4776 assert_eq!(err, "Failed to find a path to the given destination");
4778 Ok(_) => panic!("Expected error"),
4783 fn total_fees_single_path() {
4787 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4788 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4789 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4792 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4793 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4794 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4797 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4798 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4799 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4802 payment_params: None,
4805 assert_eq!(route.get_total_fees(), 250);
4806 assert_eq!(route.get_total_amount(), 225);
4810 fn total_fees_multi_path() {
4814 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4815 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4816 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4819 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4820 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4821 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4825 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4826 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4827 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4830 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4831 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4832 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4835 payment_params: None,
4838 assert_eq!(route.get_total_fees(), 200);
4839 assert_eq!(route.get_total_amount(), 300);
4843 fn total_empty_route_no_panic() {
4844 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4845 // would both panic if the route was completely empty. We test to ensure they return 0
4846 // here, even though its somewhat nonsensical as a route.
4847 let route = Route { paths: Vec::new(), payment_params: None };
4849 assert_eq!(route.get_total_fees(), 0);
4850 assert_eq!(route.get_total_amount(), 0);
4854 fn limits_total_cltv_delta() {
4855 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4856 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4858 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4860 // Make sure that generally there is at least one route available
4861 let feasible_max_total_cltv_delta = 1008;
4862 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4863 .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
4864 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
4865 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4866 assert_ne!(path.len(), 0);
4868 // But not if we exclude all paths on the basis of their accumulated CLTV delta
4869 let fail_max_total_cltv_delta = 23;
4870 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4871 .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
4872 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer)
4874 Err(LightningError { err, .. } ) => {
4875 assert_eq!(err, "Failed to find a path to the given destination");
4877 Ok(_) => panic!("Expected error"),
4881 #[cfg(not(feature = "no-std"))]
4882 pub(super) fn random_init_seed() -> u64 {
4883 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4884 use core::hash::{BuildHasher, Hasher};
4885 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4886 println!("Using seed of {}", seed);
4889 #[cfg(not(feature = "no-std"))]
4890 use util::ser::Readable;
4893 #[cfg(not(feature = "no-std"))]
4894 fn generate_routes() {
4895 let mut d = match super::test_utils::get_route_file() {
4902 let graph = NetworkGraph::read(&mut d).unwrap();
4903 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4905 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4906 let mut seed = random_init_seed() as usize;
4907 let nodes = graph.read_only().nodes().clone();
4908 'load_endpoints: for _ in 0..10 {
4910 seed = seed.overflowing_mul(0xdeadbeef).0;
4911 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4912 seed = seed.overflowing_mul(0xdeadbeef).0;
4913 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4914 let payment_params = PaymentParameters::from_node_id(dst);
4915 let amt = seed as u64 % 200_000_000;
4916 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4917 continue 'load_endpoints;
4924 #[cfg(not(feature = "no-std"))]
4925 fn generate_routes_mpp() {
4926 let mut d = match super::test_utils::get_route_file() {
4933 let graph = NetworkGraph::read(&mut d).unwrap();
4934 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4936 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4937 let mut seed = random_init_seed() as usize;
4938 let nodes = graph.read_only().nodes().clone();
4939 'load_endpoints: for _ in 0..10 {
4941 seed = seed.overflowing_mul(0xdeadbeef).0;
4942 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4943 seed = seed.overflowing_mul(0xdeadbeef).0;
4944 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4945 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
4946 let amt = seed as u64 % 200_000_000;
4947 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4948 continue 'load_endpoints;
4955 #[cfg(all(test, not(feature = "no-std")))]
4956 pub(crate) mod test_utils {
4958 /// Tries to open a network graph file, or panics with a URL to fetch it.
4959 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4960 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4961 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4962 .or_else(|_| { // Fall back to guessing based on the binary location
4963 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4964 let mut path = std::env::current_exe().unwrap();
4965 path.pop(); // lightning-...
4967 path.pop(); // debug
4968 path.pop(); // target
4969 path.push("lightning");
4970 path.push("net_graph-2021-05-31.bin");
4971 eprintln!("{}", path.to_str().unwrap());
4974 .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");
4975 #[cfg(require_route_graph_test)]
4976 return Ok(res.unwrap());
4977 #[cfg(not(require_route_graph_test))]
4982 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4985 use bitcoin::hashes::Hash;
4986 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
4987 use chain::transaction::OutPoint;
4988 use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
4989 use ln::features::{InitFeatures, InvoiceFeatures};
4990 use routing::scoring::Scorer;
4991 use util::logger::{Logger, Record};
4995 struct DummyLogger {}
4996 impl Logger for DummyLogger {
4997 fn log(&self, _record: &Record) {}
5000 struct ZeroPenaltyScorer;
5001 impl Score for ZeroPenaltyScorer {
5002 fn channel_penalty_msat(
5003 &self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId
5005 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
5006 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
5009 fn read_network_graph() -> NetworkGraph {
5010 let mut d = test_utils::get_route_file().unwrap();
5011 NetworkGraph::read(&mut d).unwrap()
5014 fn payer_pubkey() -> PublicKey {
5015 let secp_ctx = Secp256k1::new();
5016 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5020 fn first_hop(node_id: PublicKey) -> ChannelDetails {
5022 channel_id: [0; 32],
5023 counterparty: ChannelCounterparty {
5024 features: InitFeatures::known(),
5026 unspendable_punishment_reserve: 0,
5027 forwarding_info: None,
5029 funding_txo: Some(OutPoint {
5030 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5032 short_channel_id: Some(1),
5033 channel_value_satoshis: 10_000_000,
5035 balance_msat: 10_000_000,
5036 outbound_capacity_msat: 10_000_000,
5037 inbound_capacity_msat: 0,
5038 unspendable_punishment_reserve: None,
5039 confirmations_required: None,
5040 force_close_spend_delay: None,
5042 is_funding_locked: true,
5049 fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5050 let network_graph = read_network_graph();
5051 let scorer = ZeroPenaltyScorer;
5052 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5056 fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5057 let network_graph = read_network_graph();
5058 let scorer = ZeroPenaltyScorer;
5059 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5063 fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5064 let network_graph = read_network_graph();
5065 let scorer = Scorer::default();
5066 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5070 fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5071 let network_graph = read_network_graph();
5072 let scorer = Scorer::default();
5073 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5076 fn generate_routes<S: Score>(
5077 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5079 let nodes = graph.read_only().nodes().clone();
5080 let payer = payer_pubkey();
5082 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5083 let mut routes = Vec::new();
5084 let mut route_endpoints = Vec::new();
5085 let mut seed: usize = 0xdeadbeef;
5086 'load_endpoints: for _ in 0..100 {
5089 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5091 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5092 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5093 let first_hop = first_hop(src);
5094 let amt = seed as u64 % 1_000_000;
5095 if let Ok(route) = get_route(&payer, ¶ms, &graph, Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer) {
5097 route_endpoints.push((first_hop, params, amt));
5098 continue 'load_endpoints;
5103 // ...and seed the scorer with success and failure data...
5104 for route in routes {
5105 let amount = route.get_total_amount();
5106 if amount < 250_000 {
5107 for path in route.paths {
5108 scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5110 } else if amount > 750_000 {
5111 for path in route.paths {
5112 let short_channel_id = path[path.len() / 2].short_channel_id;
5113 scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5118 // ...then benchmark finding paths between the nodes we learned.
5121 let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5122 assert!(get_route(&payer, params, &graph, Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer).is_ok());