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::{NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payee` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payee: Option<Payee>,
81 pub(crate) trait RoutePath {
82 /// Gets the fees for a given path, excluding any excess paid to the recipient.
83 fn get_path_fees(&self) -> u64;
85 impl RoutePath for Vec<RouteHop> {
86 fn get_path_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
89 .iter().map(|hop| &hop.fee_msat)
95 /// Returns the total amount of fees paid on this [`Route`].
97 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
98 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
99 pub fn get_total_fees(&self) -> u64 {
100 self.paths.iter().map(|path| path.get_path_fees()).sum()
103 /// Returns the total amount paid on this [`Route`], excluding the fees.
104 pub fn get_total_amount(&self) -> u64 {
105 return self.paths.iter()
106 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
111 const SERIALIZATION_VERSION: u8 = 1;
112 const MIN_SERIALIZATION_VERSION: u8 = 1;
114 impl Writeable for Route {
115 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
116 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
117 (self.paths.len() as u64).write(writer)?;
118 for hops in self.paths.iter() {
119 (hops.len() as u8).write(writer)?;
120 for hop in hops.iter() {
124 write_tlv_fields!(writer, {
125 (1, self.payee, option),
131 impl Readable for Route {
132 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
133 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
134 let path_count: u64 = Readable::read(reader)?;
135 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
136 for _ in 0..path_count {
137 let hop_count: u8 = Readable::read(reader)?;
138 let mut hops = Vec::with_capacity(hop_count as usize);
139 for _ in 0..hop_count {
140 hops.push(Readable::read(reader)?);
144 let mut payee = None;
145 read_tlv_fields!(reader, {
148 Ok(Route { paths, payee })
152 /// Parameters needed to find a [`Route`] for paying a [`Payee`].
154 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
157 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
158 #[derive(Clone, Debug)]
159 pub struct RouteParameters {
160 /// The recipient of the failed payment path.
163 /// The amount in msats sent on the failed payment path.
164 pub final_value_msat: u64,
166 /// The CLTV on the final hop of the failed payment path.
167 pub final_cltv_expiry_delta: u32,
170 impl_writeable_tlv_based!(RouteParameters, {
171 (0, payee, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// The recipient of a payment.
177 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
179 /// The node id of the payee.
180 pub pubkey: PublicKey,
182 /// Features supported by the payee.
184 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
185 /// does not contain any features.
187 /// [`for_keysend`]: Self::for_keysend
188 pub features: Option<InvoiceFeatures>,
190 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
191 pub route_hints: Vec<RouteHint>,
193 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
194 pub expiry_time: Option<u64>,
197 impl_writeable_tlv_based!(Payee, {
198 (0, pubkey, required),
199 (2, features, option),
200 (4, route_hints, vec_type),
201 (6, expiry_time, option),
205 /// Creates a payee with the node id of the given `pubkey`.
206 pub fn from_node_id(pubkey: PublicKey) -> Self {
215 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
216 pub fn for_keysend(pubkey: PublicKey) -> Self {
217 Self::from_node_id(pubkey).with_features(InvoiceFeatures::for_keysend())
220 /// Includes the payee's features.
222 /// (C-not exported) since bindings don't support move semantics
223 pub fn with_features(self, features: InvoiceFeatures) -> Self {
224 Self { features: Some(features), ..self }
227 /// Includes hints for routing to the payee.
229 /// (C-not exported) since bindings don't support move semantics
230 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
231 Self { route_hints, ..self }
234 /// Includes a payment expiration in seconds relative to the UNIX epoch.
236 /// (C-not exported) since bindings don't support move semantics
237 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
238 Self { expiry_time: Some(expiry_time), ..self }
242 /// A list of hops along a payment path terminating with a channel to the recipient.
243 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
244 pub struct RouteHint(pub Vec<RouteHintHop>);
247 impl Writeable for RouteHint {
248 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
249 (self.0.len() as u64).write(writer)?;
250 for hop in self.0.iter() {
257 impl Readable for RouteHint {
258 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
259 let hop_count: u64 = Readable::read(reader)?;
260 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
261 for _ in 0..hop_count {
262 hops.push(Readable::read(reader)?);
268 /// A channel descriptor for a hop along a payment path.
269 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
270 pub struct RouteHintHop {
271 /// The node_id of the non-target end of the route
272 pub src_node_id: PublicKey,
273 /// The short_channel_id of this channel
274 pub short_channel_id: u64,
275 /// The fees which must be paid to use this channel
276 pub fees: RoutingFees,
277 /// The difference in CLTV values between this node and the next node.
278 pub cltv_expiry_delta: u16,
279 /// The minimum value, in msat, which must be relayed to the next hop.
280 pub htlc_minimum_msat: Option<u64>,
281 /// The maximum value in msat available for routing with a single HTLC.
282 pub htlc_maximum_msat: Option<u64>,
285 impl_writeable_tlv_based!(RouteHintHop, {
286 (0, src_node_id, required),
287 (1, htlc_minimum_msat, option),
288 (2, short_channel_id, required),
289 (3, htlc_maximum_msat, option),
291 (6, cltv_expiry_delta, required),
294 #[derive(Eq, PartialEq)]
295 struct RouteGraphNode {
297 lowest_fee_to_peer_through_node: u64,
298 lowest_fee_to_node: u64,
299 // The maximum value a yet-to-be-constructed payment path might flow through this node.
300 // This value is upper-bounded by us by:
301 // - how much is needed for a path being constructed
302 // - how much value can channels following this node (up to the destination) can contribute,
303 // considering their capacity and fees
304 value_contribution_msat: u64,
305 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
306 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
307 path_htlc_minimum_msat: u64,
308 /// All penalties incurred from this hop on the way to the destination, as calculated using
310 path_penalty_msat: u64,
313 impl cmp::Ord for RouteGraphNode {
314 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
315 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
316 .checked_add(other.path_penalty_msat)
317 .unwrap_or_else(|| u64::max_value());
318 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
319 .checked_add(self.path_penalty_msat)
320 .unwrap_or_else(|| u64::max_value());
321 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
325 impl cmp::PartialOrd for RouteGraphNode {
326 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
327 Some(self.cmp(other))
331 struct DummyDirectionalChannelInfo {
332 cltv_expiry_delta: u32,
333 htlc_minimum_msat: u64,
334 htlc_maximum_msat: Option<u64>,
338 /// It's useful to keep track of the hops associated with the fees required to use them,
339 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
340 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
341 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
342 #[derive(Clone, Debug)]
343 struct PathBuildingHop<'a> {
344 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
345 // Note that node_features is calculated separately after our initial graph walk.
347 short_channel_id: u64,
348 channel_features: &'a ChannelFeatures,
350 cltv_expiry_delta: u32,
352 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
353 src_lowest_inbound_fees: RoutingFees,
354 /// Fees of the channel used in this hop.
355 channel_fees: RoutingFees,
356 /// All the fees paid *after* this channel on the way to the destination
357 next_hops_fee_msat: u64,
358 /// Fee paid for the use of the current channel (see channel_fees).
359 /// The value will be actually deducted from the counterparty balance on the previous link.
360 hop_use_fee_msat: u64,
361 /// Used to compare channels when choosing the for routing.
362 /// Includes paying for the use of a hop and the following hops, as well as
363 /// an estimated cost of reaching this hop.
364 /// Might get stale when fees are recomputed. Primarily for internal use.
366 /// This is useful for update_value_and_recompute_fees to make sure
367 /// we don't fall below the minimum. Should not be updated manually and
368 /// generally should not be accessed.
369 htlc_minimum_msat: u64,
370 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
371 /// walk and may be invalid thereafter.
372 path_htlc_minimum_msat: u64,
373 /// All penalties incurred from this channel on the way to the destination, as calculated using
375 path_penalty_msat: u64,
376 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
377 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
378 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
379 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
380 /// avoid processing them again.
382 #[cfg(any(test, feature = "fuzztarget"))]
383 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
384 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
385 // value_contribution_msat, which requires tracking it here. See comments below where it is
386 // used for more info.
387 value_contribution_msat: u64,
390 // Instantiated with a list of hops with correct data in them collected during path finding,
391 // an instance of this struct should be further modified only via given methods.
393 struct PaymentPath<'a> {
394 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
397 impl<'a> PaymentPath<'a> {
398 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
399 fn get_value_msat(&self) -> u64 {
400 self.hops.last().unwrap().0.fee_msat
403 fn get_total_fee_paid_msat(&self) -> u64 {
404 if self.hops.len() < 1 {
408 // Can't use next_hops_fee_msat because it gets outdated.
409 for (i, (hop, _)) in self.hops.iter().enumerate() {
410 if i != self.hops.len() - 1 {
411 result += hop.fee_msat;
417 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
418 // to change fees may result in an inconsistency.
420 // Sometimes we call this function right after constructing a path which is inconsistent in
421 // that it the value being transferred has decreased while we were doing path finding, leading
422 // to the fees being paid not lining up with the actual limits.
424 // Note that this function is not aware of the available_liquidity limit, and thus does not
425 // support increasing the value being transferred.
426 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
427 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
429 let mut total_fee_paid_msat = 0 as u64;
430 for i in (0..self.hops.len()).rev() {
431 let last_hop = i == self.hops.len() - 1;
433 // For non-last-hop, this value will represent the fees paid on the current hop. It
434 // will consist of the fees for the use of the next hop, and extra fees to match
435 // htlc_minimum_msat of the current channel. Last hop is handled separately.
436 let mut cur_hop_fees_msat = 0;
438 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
441 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
442 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
443 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
444 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
445 // set it too high just to maliciously take more fees by exploiting this
446 // match htlc_minimum_msat logic.
447 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
448 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
449 // Note that there is a risk that *previous hops* (those closer to us, as we go
450 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
452 // This might make us end up with a broken route, although this should be super-rare
453 // in practice, both because of how healthy channels look like, and how we pick
454 // channels in add_entry.
455 // Also, this can't be exploited more heavily than *announce a free path and fail
457 cur_hop_transferred_amount_msat += extra_fees_msat;
458 total_fee_paid_msat += extra_fees_msat;
459 cur_hop_fees_msat += extra_fees_msat;
463 // Final hop is a special case: it usually has just value_msat (by design), but also
464 // it still could overpay for the htlc_minimum_msat.
465 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
467 // Propagate updated fees for the use of the channels to one hop back, where they
468 // will be actually paid (fee_msat). The last hop is handled above separately.
469 cur_hop.fee_msat = cur_hop_fees_msat;
472 // Fee for the use of the current hop which will be deducted on the previous hop.
473 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
474 // this channel is free for us.
476 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
477 cur_hop.hop_use_fee_msat = new_fee;
478 total_fee_paid_msat += new_fee;
480 // It should not be possible because this function is called only to reduce the
481 // value. In that case, compute_fee was already called with the same fees for
482 // larger amount and there was no overflow.
490 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
491 let proportional_fee_millions =
492 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
493 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
494 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
498 // This function may be (indirectly) called without any verification,
499 // with channel_fees provided by a caller. We should handle it gracefully.
504 /// Finds a route from us (payer) to the given target node (payee).
506 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
507 /// Without this, MPP will only be used if the payee's features are available in the network graph.
509 /// Private routing paths between a public node and the target may be included in `params.payee`.
511 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
512 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
513 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
515 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
516 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
517 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
521 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
522 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
527 /// Panics if first_hops contains channels without short_channel_ids;
528 /// [`ChannelManager::list_usable_channels`] will never include such channels.
530 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
531 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
532 pub fn find_route<L: Deref, S: Score>(
533 our_node_pubkey: &PublicKey, params: &RouteParameters, network: &NetworkGraph,
534 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
535 ) -> Result<Route, LightningError>
536 where L::Target: Logger {
538 our_node_pubkey, ¶ms.payee, network, first_hops, params.final_value_msat,
539 params.final_cltv_expiry_delta, logger, scorer
543 pub(crate) fn get_route<L: Deref, S: Score>(
544 our_node_pubkey: &PublicKey, payee: &Payee, network: &NetworkGraph,
545 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
546 logger: L, scorer: &S
547 ) -> Result<Route, LightningError>
548 where L::Target: Logger {
549 let payee_node_id = NodeId::from_pubkey(&payee.pubkey);
550 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
552 if payee_node_id == our_node_id {
553 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
556 if final_value_msat > MAX_VALUE_MSAT {
557 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
560 if final_value_msat == 0 {
561 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
564 for route in payee.route_hints.iter() {
565 for hop in &route.0 {
566 if hop.src_node_id == payee.pubkey {
567 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
572 // The general routing idea is the following:
573 // 1. Fill first/last hops communicated by the caller.
574 // 2. Attempt to construct a path from payer to payee for transferring
575 // any ~sufficient (described later) value.
576 // If succeed, remember which channels were used and how much liquidity they have available,
577 // so that future paths don't rely on the same liquidity.
578 // 3. Prooceed to the next step if:
579 // - we hit the recommended target value;
580 // - OR if we could not construct a new path. Any next attempt will fail too.
581 // Otherwise, repeat step 2.
582 // 4. See if we managed to collect paths which aggregately are able to transfer target value
583 // (not recommended value). If yes, proceed. If not, fail routing.
584 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
585 // 6. Of all the found paths, select only those with the lowest total fee.
586 // 7. The last path in every selected route is likely to be more than we need.
587 // Reduce its value-to-transfer and recompute fees.
588 // 8. Choose the best route by the lowest total fee.
590 // As for the actual search algorithm,
591 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
592 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
594 // We are not a faithful Dijkstra's implementation because we can change values which impact
595 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
596 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
597 // the value we are currently attempting to send over a path, we simply reduce the value being
598 // sent along the path for any hops after that channel. This may imply that later fees (which
599 // we've already tabulated) are lower because a smaller value is passing through the channels
600 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
601 // channels which were selected earlier (and which may still be used for other paths without a
602 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
605 // One potentially problematic case for this algorithm would be if there are many
606 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
607 // graph walking), we may never find a path which is not liquidity-limited and has lower
608 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
609 // Because we only consider paths with at least 5% of the total value being sent, the damage
610 // from such a case should be limited, however this could be further reduced in the future by
611 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
612 // limits for the purposes of fee calculation.
614 // Alternatively, we could store more detailed path information in the heap (targets, below)
615 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
616 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
617 // and practically (as we would need to store dynamically-allocated path information in heap
618 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
619 // results of such an algorithm would likely be biased towards lower-value paths.
621 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
622 // outside of our current search value, running a path search more times to gather candidate
623 // paths at different values. While this may be acceptable, further path searches may increase
624 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
625 // graph for candidate paths, calculating the maximum value which can realistically be sent at
626 // the same time, remaining generic across different payment values.
628 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
629 // to use as the A* heuristic beyond just the cost to get one node further than the current
632 let network_graph = network.read_only();
633 let network_channels = network_graph.channels();
634 let network_nodes = network_graph.nodes();
635 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
636 cltv_expiry_delta: 0,
637 htlc_minimum_msat: 0,
638 htlc_maximum_msat: None,
641 proportional_millionths: 0,
645 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
646 // it. If the payee supports it they're supposed to include it in the invoice, so that should
648 let allow_mpp = if let Some(features) = &payee.features {
649 features.supports_basic_mpp()
650 } else if let Some(node) = network_nodes.get(&payee_node_id) {
651 if let Some(node_info) = node.announcement_info.as_ref() {
652 node_info.features.supports_basic_mpp()
655 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
656 payee.pubkey, if allow_mpp { "with" } else { "without" });
659 // Prepare the data we'll use for payee-to-payer search by
660 // inserting first hops suggested by the caller as targets.
661 // Our search will then attempt to reach them while traversing from the payee node.
662 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
663 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
664 if let Some(hops) = first_hops {
666 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
667 if chan.counterparty.node_id == *our_node_pubkey {
668 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
670 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
671 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
673 if first_hop_targets.is_empty() {
674 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
678 let empty_channel_features = ChannelFeatures::empty();
680 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
681 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
682 // adding duplicate entries when we find a better path to a given node.
683 let mut targets = BinaryHeap::new();
685 // Map from node_id to information about the best current path to that node, including feerate
687 let mut dist = HashMap::with_capacity(network_nodes.len());
689 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
690 // indicating that we may wish to try again with a higher value, potentially paying to meet an
691 // htlc_minimum with extra fees while still finding a cheaper path.
692 let mut hit_minimum_limit;
694 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
695 // We start with a path_value of the exact amount we want, and if that generates a route we may
696 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
697 // amount we want in total across paths, selecting the best subset at the end.
698 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
699 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
700 let mut path_value_msat = final_value_msat;
702 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
703 // This map allows paths to be aware of the channel use by other paths in the same call.
704 // This would help to make a better path finding decisions and not "overbook" channels.
705 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
706 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
708 // Keeping track of how much value we already collected across other paths. Helps to decide:
709 // - how much a new path should be transferring (upper bound);
710 // - whether a channel should be disregarded because
711 // it's available liquidity is too small comparing to how much more we need to collect;
712 // - when we want to stop looking for new paths.
713 let mut already_collected_value_msat = 0;
715 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee.pubkey, our_node_pubkey, final_value_msat);
717 macro_rules! add_entry {
718 // Adds entry which goes from $src_node_id to $dest_node_id
719 // over the channel with id $chan_id with fees described in
720 // $directional_info.
721 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
722 // since that value has to be transferred over this channel.
723 // Returns whether this channel caused an update to `targets`.
724 ( $chan_id: expr, $src_node_id: expr, $dest_node_id: expr, $directional_info: expr, $capacity_sats: expr, $chan_features: expr, $next_hops_fee_msat: expr,
725 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => { {
726 // We "return" whether we updated the path at the end, via this:
727 let mut did_add_update_path_to_src_node = false;
728 // Channels to self should not be used. This is more of belt-and-suspenders, because in
729 // practice these cases should be caught earlier:
730 // - for regular channels at channel announcement (TODO)
731 // - for first and last hops early in get_route
732 if $src_node_id != $dest_node_id.clone() {
733 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
734 let mut initial_liquidity_available_msat = None;
735 if let Some(capacity_sats) = $capacity_sats {
736 initial_liquidity_available_msat = Some(capacity_sats * 1000);
739 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
740 if let Some(available_msat) = initial_liquidity_available_msat {
741 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
743 initial_liquidity_available_msat = Some(htlc_maximum_msat);
747 match initial_liquidity_available_msat {
748 Some(available_msat) => available_msat,
749 // We assume channels with unknown balance have
750 // a capacity of 0.0025 BTC (or 250_000 sats).
751 None => 250_000 * 1000
755 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
756 // It may be misleading because we might later choose to reduce the value transferred
757 // over these channels, and the channel which was insufficient might become sufficient.
758 // Worst case: we drop a good channel here because it can't cover the high following
759 // fees caused by one expensive channel, but then this channel could have been used
760 // if the amount being transferred over this path is lower.
761 // We do this for now, but this is a subject for removal.
762 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
764 // Routing Fragmentation Mitigation heuristic:
766 // Routing fragmentation across many payment paths increases the overall routing
767 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
768 // Taking too many smaller paths also increases the chance of payment failure.
769 // Thus to avoid this effect, we require from our collected links to provide
770 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
772 // This requirement is currently 5% of the remaining-to-be-collected value.
773 // This means as we successfully advance in our collection,
774 // the absolute liquidity contribution is lowered,
775 // thus increasing the number of potential channels to be selected.
777 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
778 // or 100% if we're not allowed to do multipath payments.
779 let minimal_value_contribution_msat: u64 = if allow_mpp {
780 (recommended_value_msat - already_collected_value_msat + 19) / 20
784 // Verify the liquidity offered by this channel complies to the minimal contribution.
785 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
787 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
788 // Includes paying fees for the use of the following channels.
789 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
790 Some(result) => result,
791 // Can't overflow due to how the values were computed right above.
792 None => unreachable!(),
794 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
795 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
796 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
798 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
799 // bother considering this channel.
800 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
801 // be only reduced later (not increased), so this channel should just be skipped
802 // as not sufficient.
803 if !over_path_minimum_msat {
804 hit_minimum_limit = true;
805 } else if contributes_sufficient_value {
806 // Note that low contribution here (limited by available_liquidity_msat)
807 // might violate htlc_minimum_msat on the hops which are next along the
808 // payment path (upstream to the payee). To avoid that, we recompute path
809 // path fees knowing the final path contribution after constructing it.
810 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
811 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
812 .map(|fee_msat| cmp::max(fee_msat, $directional_info.htlc_minimum_msat))
813 .unwrap_or_else(|| u64::max_value());
814 let hm_entry = dist.entry($src_node_id);
815 let old_entry = hm_entry.or_insert_with(|| {
816 // If there was previously no known way to access
817 // the source node (recall it goes payee-to-payer) of $chan_id, first add
818 // a semi-dummy record just to compute the fees to reach the source node.
819 // This will affect our decision on selecting $chan_id
820 // as a way to reach the $dest_node_id.
821 let mut fee_base_msat = u32::max_value();
822 let mut fee_proportional_millionths = u32::max_value();
823 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
824 fee_base_msat = fees.base_msat;
825 fee_proportional_millionths = fees.proportional_millionths;
828 node_id: $dest_node_id.clone(),
830 channel_features: $chan_features,
832 cltv_expiry_delta: 0,
833 src_lowest_inbound_fees: RoutingFees {
834 base_msat: fee_base_msat,
835 proportional_millionths: fee_proportional_millionths,
837 channel_fees: $directional_info.fees,
838 next_hops_fee_msat: u64::max_value(),
839 hop_use_fee_msat: u64::max_value(),
840 total_fee_msat: u64::max_value(),
841 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
842 path_htlc_minimum_msat,
843 path_penalty_msat: u64::max_value(),
844 was_processed: false,
845 #[cfg(any(test, feature = "fuzztarget"))]
846 value_contribution_msat,
850 #[allow(unused_mut)] // We only use the mut in cfg(test)
851 let mut should_process = !old_entry.was_processed;
852 #[cfg(any(test, feature = "fuzztarget"))]
854 // In test/fuzzing builds, we do extra checks to make sure the skipping
855 // of already-seen nodes only happens in cases we expect (see below).
856 if !should_process { should_process = true; }
860 let mut hop_use_fee_msat = 0;
861 let mut total_fee_msat = $next_hops_fee_msat;
863 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
864 // will have the same effective-fee
865 if $src_node_id != our_node_id {
866 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
867 // max_value means we'll always fail
868 // the old_entry.total_fee_msat > total_fee_msat check
869 None => total_fee_msat = u64::max_value(),
871 hop_use_fee_msat = fee_msat;
872 total_fee_msat += hop_use_fee_msat;
873 // When calculating the lowest inbound fees to a node, we
874 // calculate fees here not based on the actual value we think
875 // will flow over this channel, but on the minimum value that
876 // we'll accept flowing over it. The minimum accepted value
877 // is a constant through each path collection run, ensuring
878 // consistent basis. Otherwise we may later find a
879 // different path to the source node that is more expensive,
880 // but which we consider to be cheaper because we are capacity
881 // constrained and the relative fee becomes lower.
882 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
883 .map(|a| a.checked_add(total_fee_msat)) {
888 total_fee_msat = u64::max_value();
895 let path_penalty_msat = $next_hops_path_penalty_msat.checked_add(
896 scorer.channel_penalty_msat($chan_id.clone(), amount_to_transfer_over_msat, Some(*available_liquidity_msat),
897 &$src_node_id, &$dest_node_id)).unwrap_or_else(|| u64::max_value());
898 let new_graph_node = RouteGraphNode {
899 node_id: $src_node_id,
900 lowest_fee_to_peer_through_node: total_fee_msat,
901 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
902 value_contribution_msat: value_contribution_msat,
903 path_htlc_minimum_msat,
907 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
908 // if this way is cheaper than the already known
909 // (considering the cost to "reach" this channel from the route destination,
910 // the cost of using this channel,
911 // and the cost of routing to the source node of this channel).
912 // Also, consider that htlc_minimum_msat_difference, because we might end up
913 // paying it. Consider the following exploit:
914 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
915 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
916 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
917 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
919 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
920 // but it may require additional tracking - we don't want to double-count
921 // the fees included in $next_hops_path_htlc_minimum_msat, but also
922 // can't use something that may decrease on future hops.
923 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
924 .checked_add(old_entry.path_penalty_msat)
925 .unwrap_or_else(|| u64::max_value());
926 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
927 .checked_add(path_penalty_msat)
928 .unwrap_or_else(|| u64::max_value());
930 if !old_entry.was_processed && new_cost < old_cost {
931 targets.push(new_graph_node);
932 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
933 old_entry.hop_use_fee_msat = hop_use_fee_msat;
934 old_entry.total_fee_msat = total_fee_msat;
935 old_entry.node_id = $dest_node_id.clone();
936 old_entry.short_channel_id = $chan_id.clone();
937 old_entry.channel_features = $chan_features;
938 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
939 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
940 old_entry.channel_fees = $directional_info.fees;
941 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
942 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
943 old_entry.path_penalty_msat = path_penalty_msat;
944 #[cfg(any(test, feature = "fuzztarget"))]
946 old_entry.value_contribution_msat = value_contribution_msat;
948 did_add_update_path_to_src_node = true;
949 } else if old_entry.was_processed && new_cost < old_cost {
950 #[cfg(any(test, feature = "fuzztarget"))]
952 // If we're skipping processing a node which was previously
953 // processed even though we found another path to it with a
954 // cheaper fee, check that it was because the second path we
955 // found (which we are processing now) has a lower value
956 // contribution due to an HTLC minimum limit.
958 // e.g. take a graph with two paths from node 1 to node 2, one
959 // through channel A, and one through channel B. Channel A and
960 // B are both in the to-process heap, with their scores set by
961 // a higher htlc_minimum than fee.
962 // Channel A is processed first, and the channels onwards from
963 // node 1 are added to the to-process heap. Thereafter, we pop
964 // Channel B off of the heap, note that it has a much more
965 // restrictive htlc_maximum_msat, and recalculate the fees for
966 // all of node 1's channels using the new, reduced, amount.
968 // This would be bogus - we'd be selecting a higher-fee path
969 // with a lower htlc_maximum_msat instead of the one we'd
970 // already decided to use.
971 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
973 value_contribution_msat + path_penalty_msat <
974 old_entry.value_contribution_msat + old_entry.path_penalty_msat
982 did_add_update_path_to_src_node
986 let empty_node_features = NodeFeatures::empty();
987 // Find ways (channels with destination) to reach a given node and store them
988 // in the corresponding data structures (routing graph etc).
989 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
990 // meaning how much will be paid in fees after this node (to the best of our knowledge).
991 // This data can later be helpful to optimize routing (pay lower fees).
992 macro_rules! add_entries_to_cheapest_to_target_node {
993 ( $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 ) => {
994 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
995 let was_processed = elem.was_processed;
996 elem.was_processed = true;
999 // Entries are added to dist in add_entry!() when there is a channel from a node.
1000 // Because there are no channels from payee, it will not have a dist entry at this point.
1001 // If we're processing any other node, it is always be the result of a channel from it.
1002 assert_eq!($node_id, payee_node_id);
1007 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1008 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1009 add_entry!(first_hop, our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat);
1013 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1016 &empty_node_features
1019 if !features.requires_unknown_bits() {
1020 for chan_id in $node.channels.iter() {
1021 let chan = network_channels.get(chan_id).unwrap();
1022 if !chan.features.requires_unknown_bits() {
1023 if chan.node_one == $node_id {
1024 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
1025 if first_hops.is_none() || chan.node_two != our_node_id {
1026 if let Some(two_to_one) = chan.two_to_one.as_ref() {
1027 if two_to_one.enabled {
1028 add_entry!(chan_id, chan.node_two, chan.node_one, two_to_one, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat);
1033 if first_hops.is_none() || chan.node_one != our_node_id{
1034 if let Some(one_to_two) = chan.one_to_two.as_ref() {
1035 if one_to_two.enabled {
1036 add_entry!(chan_id, chan.node_one, chan.node_two, one_to_two, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat);
1048 let mut payment_paths = Vec::<PaymentPath>::new();
1050 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1051 'paths_collection: loop {
1052 // For every new path, start from scratch, except
1053 // bookkeeped_channels_liquidity_available_msat, which will improve
1054 // the further iterations of path finding. Also don't erase first_hop_targets.
1057 hit_minimum_limit = false;
1059 // If first hop is a private channel and the only way to reach the payee, this is the only
1060 // place where it could be added.
1061 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1062 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1063 let added = add_entry!(first_hop, our_node_id, payee_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0, 0u64);
1064 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
1068 // Add the payee as a target, so that the payee-to-payer
1069 // search algorithm knows what to start with.
1070 match network_nodes.get(&payee_node_id) {
1071 // The payee is not in our network graph, so nothing to add here.
1072 // There is still a chance of reaching them via last_hops though,
1073 // so don't yet fail the payment here.
1074 // If not, targets.pop() will not even let us enter the loop in step 2.
1077 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64);
1082 // If a caller provided us with last hops, add them to routing targets. Since this happens
1083 // earlier than general path finding, they will be somewhat prioritized, although currently
1084 // it matters only if the fees are exactly the same.
1085 for route in payee.route_hints.iter().filter(|route| !route.0.is_empty()) {
1086 let first_hop_in_route = &(route.0)[0];
1087 let have_hop_src_in_graph =
1088 // Only add the hops in this route to our candidate set if either
1089 // we have a direct channel to the first hop or the first hop is
1090 // in the regular network graph.
1091 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1092 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1093 if have_hop_src_in_graph {
1094 // We start building the path from reverse, i.e., from payee
1095 // to the first RouteHintHop in the path.
1096 let hop_iter = route.0.iter().rev();
1097 let prev_hop_iter = core::iter::once(&payee.pubkey).chain(
1098 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1099 let mut hop_used = true;
1100 let mut aggregate_next_hops_fee_msat: u64 = 0;
1101 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1102 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1104 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1105 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
1106 // really sucks, cause we're gonna need that eventually.
1107 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
1109 let directional_info = DummyDirectionalChannelInfo {
1110 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
1111 htlc_minimum_msat: hop_htlc_minimum_msat,
1112 htlc_maximum_msat: hop.htlc_maximum_msat,
1116 // We want a value of final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR but we
1117 // need it to increment at each hop by the fee charged at later hops. Further,
1118 // we need to ensure we round up when we divide to get satoshis.
1119 let channel_cap_msat = final_value_msat
1120 .checked_mul(ROUTE_CAPACITY_PROVISION_FACTOR).and_then(|v| v.checked_add(aggregate_next_hops_fee_msat))
1121 .unwrap_or(u64::max_value());
1122 let channel_cap_sat = match channel_cap_msat.checked_add(999) {
1123 None => break, // We overflowed above, just ignore this route hint
1124 Some(val) => Some(val / 1000),
1127 let src_node_id = NodeId::from_pubkey(&hop.src_node_id);
1128 let dest_node_id = NodeId::from_pubkey(&prev_hop_id);
1129 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1130 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, final_value_msat, None, &src_node_id, &dest_node_id))
1131 .unwrap_or_else(|| u64::max_value());
1133 // We assume that the recipient only included route hints for routes which had
1134 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
1135 // invoices where the invoice does not specify value this may not be the case, but
1136 // better to include the hints than not.
1137 if !add_entry!(hop.short_channel_id, src_node_id, dest_node_id, directional_info, channel_cap_sat, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat) {
1138 // If this hop was not used then there is no use checking the preceding hops
1139 // in the RouteHint. We can break by just searching for a direct channel between
1140 // last checked hop and first_hop_targets
1144 // Searching for a direct channel between last checked hop and first_hop_targets
1145 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1146 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1147 add_entry!(first_hop, our_node_id , NodeId::from_pubkey(&prev_hop_id), dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat);
1155 // In the next values of the iterator, the aggregate fees already reflects
1156 // the sum of value sent from payer (final_value_msat) and routing fees
1157 // for the last node in the RouteHint. We need to just add the fees to
1158 // route through the current node so that the preceeding node (next iteration)
1160 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1161 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1162 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1164 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1165 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1166 .checked_add(hop_htlc_minimum_msat_inc);
1167 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1169 if idx == route.0.len() - 1 {
1170 // The last hop in this iterator is the first hop in
1171 // overall RouteHint.
1172 // If this hop connects to a node with which we have a direct channel,
1173 // ignore the network graph and, if the last hop was added, add our
1174 // direct channel to the candidate set.
1176 // Note that we *must* check if the last hop was added as `add_entry`
1177 // always assumes that the third argument is a node to which we have a
1179 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1180 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1181 add_entry!(first_hop, our_node_id , NodeId::from_pubkey(&hop.src_node_id), dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat);
1189 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1191 // At this point, targets are filled with the data from first and
1192 // last hops communicated by the caller, and the payment receiver.
1193 let mut found_new_path = false;
1196 // If this loop terminates due the exhaustion of targets, two situations are possible:
1197 // - not enough outgoing liquidity:
1198 // 0 < already_collected_value_msat < final_value_msat
1199 // - enough outgoing liquidity:
1200 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1201 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1202 // paths_collection will be stopped because found_new_path==false.
1203 // This is not necessarily a routing failure.
1204 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1206 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1207 // traversing the graph and arrange the path out of what we found.
1208 if node_id == our_node_id {
1209 let mut new_entry = dist.remove(&our_node_id).unwrap();
1210 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1213 let mut features_set = false;
1214 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1215 for (scid, _, _, ref features) in first_channels {
1216 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1217 ordered_hops.last_mut().unwrap().1 = features.clone();
1218 features_set = true;
1224 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1225 if let Some(node_info) = node.announcement_info.as_ref() {
1226 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1228 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1231 // We should be able to fill in features for everything except the last
1232 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1233 // should be able to extend it further as BOLT 11 does have feature
1234 // flags for the last hop node itself).
1235 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1239 // Means we succesfully traversed from the payer to the payee, now
1240 // save this path for the payment route. Also, update the liquidity
1241 // remaining on the used hops, so that we take them into account
1242 // while looking for more paths.
1243 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1247 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1248 Some(payment_hop) => payment_hop,
1249 // We can't arrive at None because, if we ever add an entry to targets,
1250 // we also fill in the entry in dist (see add_entry!).
1251 None => unreachable!(),
1253 // We "propagate" the fees one hop backward (topologically) here,
1254 // so that fees paid for a HTLC forwarding on the current channel are
1255 // associated with the previous channel (where they will be subtracted).
1256 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1257 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1258 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1260 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1261 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1262 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv_expiry_delta;
1264 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1265 ordered_hops.len(), value_contribution_msat, ordered_hops);
1267 let mut payment_path = PaymentPath {hops: ordered_hops};
1269 // We could have possibly constructed a slightly inconsistent path: since we reduce
1270 // value being transferred along the way, we could have violated htlc_minimum_msat
1271 // on some channels we already passed (assuming dest->source direction). Here, we
1272 // recompute the fees again, so that if that's the case, we match the currently
1273 // underpaid htlc_minimum_msat with fees.
1274 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1276 // Since a path allows to transfer as much value as
1277 // the smallest channel it has ("bottleneck"), we should recompute
1278 // the fees so sender HTLC don't overpay fees when traversing
1279 // larger channels than the bottleneck. This may happen because
1280 // when we were selecting those channels we were not aware how much value
1281 // this path will transfer, and the relative fee for them
1282 // might have been computed considering a larger value.
1283 // Remember that we used these channels so that we don't rely
1284 // on the same liquidity in future paths.
1285 let mut prevented_redundant_path_selection = false;
1286 for (payment_hop, _) in payment_path.hops.iter() {
1287 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1288 let mut spent_on_hop_msat = value_contribution_msat;
1289 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1290 spent_on_hop_msat += next_hops_fee_msat;
1291 if spent_on_hop_msat == *channel_liquidity_available_msat {
1292 // If this path used all of this channel's available liquidity, we know
1293 // this path will not be selected again in the next loop iteration.
1294 prevented_redundant_path_selection = true;
1296 *channel_liquidity_available_msat -= spent_on_hop_msat;
1298 if !prevented_redundant_path_selection {
1299 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1300 // we'll probably end up picking the same path again on the next iteration.
1301 // Decrease the available liquidity of a hop in the middle of the path.
1302 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1303 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1304 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1305 *victim_liquidity = 0;
1308 // Track the total amount all our collected paths allow to send so that we:
1309 // - know when to stop looking for more paths
1310 // - know which of the hops are useless considering how much more sats we need
1311 // (contributes_sufficient_value)
1312 already_collected_value_msat += value_contribution_msat;
1314 payment_paths.push(payment_path);
1315 found_new_path = true;
1316 break 'path_construction;
1319 // If we found a path back to the payee, we shouldn't try to process it again. This is
1320 // the equivalent of the `elem.was_processed` check in
1321 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1322 if node_id == payee_node_id { continue 'path_construction; }
1324 // Otherwise, since the current target node is not us,
1325 // keep "unrolling" the payment graph from payee to payer by
1326 // finding a way to reach the current target from the payer side.
1327 match network_nodes.get(&node_id) {
1330 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1336 // If we don't support MPP, no use trying to gather more value ever.
1337 break 'paths_collection;
1341 // Stop either when the recommended value is reached or if no new path was found in this
1343 // In the latter case, making another path finding attempt won't help,
1344 // because we deterministically terminated the search due to low liquidity.
1345 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1346 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1347 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1348 break 'paths_collection;
1349 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1350 // Further, if this was our first walk of the graph, and we weren't limited by an
1351 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1352 // limited by an htlc_minimum_msat value, find another path with a higher value,
1353 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1354 // still keeping a lower total fee than this path.
1355 if !hit_minimum_limit {
1356 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1357 break 'paths_collection;
1359 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1360 path_value_msat = recommended_value_msat;
1365 if payment_paths.len() == 0 {
1366 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1369 if already_collected_value_msat < final_value_msat {
1370 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1373 // Sort by total fees and take the best paths.
1374 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1375 if payment_paths.len() > 50 {
1376 payment_paths.truncate(50);
1379 // Draw multiple sufficient routes by randomly combining the selected paths.
1380 let mut drawn_routes = Vec::new();
1381 for i in 0..payment_paths.len() {
1382 let mut cur_route = Vec::<PaymentPath>::new();
1383 let mut aggregate_route_value_msat = 0;
1386 // TODO: real random shuffle
1387 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1388 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1391 for payment_path in cur_payment_paths {
1392 cur_route.push(payment_path.clone());
1393 aggregate_route_value_msat += payment_path.get_value_msat();
1394 if aggregate_route_value_msat > final_value_msat {
1395 // Last path likely overpaid. Substract it from the most expensive
1396 // (in terms of proportional fee) path in this route and recompute fees.
1397 // This might be not the most economically efficient way, but fewer paths
1398 // also makes routing more reliable.
1399 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1401 // First, drop some expensive low-value paths entirely if possible.
1402 // Sort by value so that we drop many really-low values first, since
1403 // fewer paths is better: the payment is less likely to fail.
1404 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1405 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1406 cur_route.sort_by_key(|path| path.get_value_msat());
1407 // We should make sure that at least 1 path left.
1408 let mut paths_left = cur_route.len();
1409 cur_route.retain(|path| {
1410 if paths_left == 1 {
1413 let mut keep = true;
1414 let path_value_msat = path.get_value_msat();
1415 if path_value_msat <= overpaid_value_msat {
1417 overpaid_value_msat -= path_value_msat;
1423 if overpaid_value_msat == 0 {
1427 assert!(cur_route.len() > 0);
1430 // Now, substract the overpaid value from the most-expensive path.
1431 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1432 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1433 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1434 let expensive_payment_path = cur_route.first_mut().unwrap();
1435 // We already dropped all the small channels above, meaning all the
1436 // remaining channels are larger than remaining overpaid_value_msat.
1437 // Thus, this can't be negative.
1438 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1439 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1443 drawn_routes.push(cur_route);
1447 // Select the best route by lowest total fee.
1448 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1449 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1450 for payment_path in drawn_routes.first().unwrap() {
1451 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1453 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)})?,
1454 node_features: node_features.clone(),
1455 short_channel_id: payment_hop.short_channel_id,
1456 channel_features: payment_hop.channel_features.clone(),
1457 fee_msat: payment_hop.fee_msat,
1458 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1463 if let Some(features) = &payee.features {
1464 for path in selected_paths.iter_mut() {
1465 if let Ok(route_hop) = path.last_mut().unwrap() {
1466 route_hop.node_features = features.to_context();
1472 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1473 payee: Some(payee.clone()),
1475 log_info!(logger, "Got route to {}: {}", payee.pubkey, log_route!(route));
1481 use routing::scoring::Score;
1482 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1483 use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1484 use chain::transaction::OutPoint;
1485 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1486 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1487 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1488 use ln::channelmanager;
1489 use util::test_utils;
1490 use util::ser::Writeable;
1492 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1493 use bitcoin::hashes::Hash;
1494 use bitcoin::network::constants::Network;
1495 use bitcoin::blockdata::constants::genesis_block;
1496 use bitcoin::blockdata::script::Builder;
1497 use bitcoin::blockdata::opcodes;
1498 use bitcoin::blockdata::transaction::TxOut;
1502 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1503 use bitcoin::secp256k1::{Secp256k1, All};
1506 use sync::{self, Arc};
1508 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1509 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1510 channelmanager::ChannelDetails {
1511 channel_id: [0; 32],
1512 counterparty: channelmanager::ChannelCounterparty {
1515 unspendable_punishment_reserve: 0,
1516 forwarding_info: None,
1518 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1520 channel_value_satoshis: 0,
1522 outbound_capacity_msat,
1523 inbound_capacity_msat: 42,
1524 unspendable_punishment_reserve: None,
1525 confirmations_required: None,
1526 force_close_spend_delay: None,
1527 is_outbound: true, is_funding_locked: true,
1528 is_usable: true, is_public: true,
1532 // Using the same keys for LN and BTC ids
1534 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1535 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1537 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1538 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1540 let unsigned_announcement = UnsignedChannelAnnouncement {
1542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1546 bitcoin_key_1: node_id_1,
1547 bitcoin_key_2: node_id_2,
1548 excess_data: Vec::new(),
1551 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1552 let valid_announcement = ChannelAnnouncement {
1553 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1554 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1555 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1556 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1557 contents: unsigned_announcement.clone(),
1559 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1560 Ok(res) => assert!(res),
1566 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1567 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1569 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1570 let valid_channel_update = ChannelUpdate {
1571 signature: secp_ctx.sign(&msghash, node_privkey),
1572 contents: update.clone()
1575 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1576 Ok(res) => assert!(res),
1581 fn add_or_update_node(
1582 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1583 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1585 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1586 let unsigned_announcement = UnsignedNodeAnnouncement {
1592 addresses: Vec::new(),
1593 excess_address_data: Vec::new(),
1594 excess_data: Vec::new(),
1596 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1597 let valid_announcement = NodeAnnouncement {
1598 signature: secp_ctx.sign(&msghash, node_privkey),
1599 contents: unsigned_announcement.clone()
1602 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1608 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1609 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1610 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1613 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1615 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1616 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1618 (our_privkey, our_id, privkeys, pubkeys)
1621 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1622 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1623 // test for it later.
1624 let idx = (id - 1) * 2 + 1;
1626 vec![1 << (idx - 8*3), 0, 0, 0]
1627 } else if idx > 8*2 {
1628 vec![1 << (idx - 8*2), 0, 0]
1629 } else if idx > 8*1 {
1630 vec![1 << (idx - 8*1), 0]
1636 fn build_graph() -> (
1638 sync::Arc<NetworkGraph>,
1639 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1640 sync::Arc<test_utils::TestChainSource>,
1641 sync::Arc<test_utils::TestLogger>,
1643 let secp_ctx = Secp256k1::new();
1644 let logger = Arc::new(test_utils::TestLogger::new());
1645 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1646 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1647 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1648 // Build network from our_id to node6:
1650 // -1(1)2- node0 -1(3)2-
1652 // our_id -1(12)2- node7 -1(13)2--- node2
1654 // -1(2)2- node1 -1(4)2-
1657 // chan1 1-to-2: disabled
1658 // chan1 2-to-1: enabled, 0 fee
1660 // chan2 1-to-2: enabled, ignored fee
1661 // chan2 2-to-1: enabled, 0 fee
1663 // chan3 1-to-2: enabled, 0 fee
1664 // chan3 2-to-1: enabled, 100 msat fee
1666 // chan4 1-to-2: enabled, 100% fee
1667 // chan4 2-to-1: enabled, 0 fee
1669 // chan12 1-to-2: enabled, ignored fee
1670 // chan12 2-to-1: enabled, 0 fee
1672 // chan13 1-to-2: enabled, 200% fee
1673 // chan13 2-to-1: enabled, 0 fee
1676 // -1(5)2- node3 -1(8)2--
1680 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1682 // -1(7)2- node5 -1(10)2-
1684 // Channels 5, 8, 9 and 10 are private channels.
1686 // chan5 1-to-2: enabled, 100 msat fee
1687 // chan5 2-to-1: enabled, 0 fee
1689 // chan6 1-to-2: enabled, 0 fee
1690 // chan6 2-to-1: enabled, 0 fee
1692 // chan7 1-to-2: enabled, 100% fee
1693 // chan7 2-to-1: enabled, 0 fee
1695 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1696 // chan8 2-to-1: enabled, 0 fee
1698 // chan9 1-to-2: enabled, 1001 msat fee
1699 // chan9 2-to-1: enabled, 0 fee
1701 // chan10 1-to-2: enabled, 0 fee
1702 // chan10 2-to-1: enabled, 0 fee
1704 // chan11 1-to-2: enabled, 0 fee
1705 // chan11 2-to-1: enabled, 0 fee
1707 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1709 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1710 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1712 short_channel_id: 1,
1715 cltv_expiry_delta: 0,
1716 htlc_minimum_msat: 0,
1717 htlc_maximum_msat: OptionalField::Absent,
1719 fee_proportional_millionths: 0,
1720 excess_data: Vec::new()
1723 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1725 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1726 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1727 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1728 short_channel_id: 2,
1731 cltv_expiry_delta: u16::max_value(),
1732 htlc_minimum_msat: 0,
1733 htlc_maximum_msat: OptionalField::Absent,
1734 fee_base_msat: u32::max_value(),
1735 fee_proportional_millionths: u32::max_value(),
1736 excess_data: Vec::new()
1738 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1739 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1740 short_channel_id: 2,
1743 cltv_expiry_delta: 0,
1744 htlc_minimum_msat: 0,
1745 htlc_maximum_msat: OptionalField::Absent,
1747 fee_proportional_millionths: 0,
1748 excess_data: Vec::new()
1751 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1753 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1754 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1755 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1756 short_channel_id: 12,
1759 cltv_expiry_delta: u16::max_value(),
1760 htlc_minimum_msat: 0,
1761 htlc_maximum_msat: OptionalField::Absent,
1762 fee_base_msat: u32::max_value(),
1763 fee_proportional_millionths: u32::max_value(),
1764 excess_data: Vec::new()
1766 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1768 short_channel_id: 12,
1771 cltv_expiry_delta: 0,
1772 htlc_minimum_msat: 0,
1773 htlc_maximum_msat: OptionalField::Absent,
1775 fee_proportional_millionths: 0,
1776 excess_data: Vec::new()
1779 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1781 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1782 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1784 short_channel_id: 3,
1787 cltv_expiry_delta: (3 << 8) | 1,
1788 htlc_minimum_msat: 0,
1789 htlc_maximum_msat: OptionalField::Absent,
1791 fee_proportional_millionths: 0,
1792 excess_data: Vec::new()
1794 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1796 short_channel_id: 3,
1799 cltv_expiry_delta: (3 << 8) | 2,
1800 htlc_minimum_msat: 0,
1801 htlc_maximum_msat: OptionalField::Absent,
1803 fee_proportional_millionths: 0,
1804 excess_data: Vec::new()
1807 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1808 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1810 short_channel_id: 4,
1813 cltv_expiry_delta: (4 << 8) | 1,
1814 htlc_minimum_msat: 0,
1815 htlc_maximum_msat: OptionalField::Absent,
1817 fee_proportional_millionths: 1000000,
1818 excess_data: Vec::new()
1820 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1822 short_channel_id: 4,
1825 cltv_expiry_delta: (4 << 8) | 2,
1826 htlc_minimum_msat: 0,
1827 htlc_maximum_msat: OptionalField::Absent,
1829 fee_proportional_millionths: 0,
1830 excess_data: Vec::new()
1833 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1834 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1836 short_channel_id: 13,
1839 cltv_expiry_delta: (13 << 8) | 1,
1840 htlc_minimum_msat: 0,
1841 htlc_maximum_msat: OptionalField::Absent,
1843 fee_proportional_millionths: 2000000,
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: 13,
1851 cltv_expiry_delta: (13 << 8) | 2,
1852 htlc_minimum_msat: 0,
1853 htlc_maximum_msat: OptionalField::Absent,
1855 fee_proportional_millionths: 0,
1856 excess_data: Vec::new()
1859 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1861 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1862 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1863 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1864 short_channel_id: 6,
1867 cltv_expiry_delta: (6 << 8) | 1,
1868 htlc_minimum_msat: 0,
1869 htlc_maximum_msat: OptionalField::Absent,
1871 fee_proportional_millionths: 0,
1872 excess_data: Vec::new()
1874 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1876 short_channel_id: 6,
1879 cltv_expiry_delta: (6 << 8) | 2,
1880 htlc_minimum_msat: 0,
1881 htlc_maximum_msat: OptionalField::Absent,
1883 fee_proportional_millionths: 0,
1884 excess_data: Vec::new(),
1887 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1888 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1889 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1890 short_channel_id: 11,
1893 cltv_expiry_delta: (11 << 8) | 1,
1894 htlc_minimum_msat: 0,
1895 htlc_maximum_msat: OptionalField::Absent,
1897 fee_proportional_millionths: 0,
1898 excess_data: Vec::new()
1900 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1902 short_channel_id: 11,
1905 cltv_expiry_delta: (11 << 8) | 2,
1906 htlc_minimum_msat: 0,
1907 htlc_maximum_msat: OptionalField::Absent,
1909 fee_proportional_millionths: 0,
1910 excess_data: Vec::new()
1913 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1915 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1917 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1918 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1919 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1920 short_channel_id: 7,
1923 cltv_expiry_delta: (7 << 8) | 1,
1924 htlc_minimum_msat: 0,
1925 htlc_maximum_msat: OptionalField::Absent,
1927 fee_proportional_millionths: 1000000,
1928 excess_data: Vec::new()
1930 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1931 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1932 short_channel_id: 7,
1935 cltv_expiry_delta: (7 << 8) | 2,
1936 htlc_minimum_msat: 0,
1937 htlc_maximum_msat: OptionalField::Absent,
1939 fee_proportional_millionths: 0,
1940 excess_data: Vec::new()
1943 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1945 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1949 fn simple_route_test() {
1950 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1951 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1952 let payee = Payee::from_node_id(nodes[2]);
1953 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1955 // Simple route to 2 via 1
1957 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
1958 assert_eq!(err, "Cannot send a payment of 0 msat");
1959 } else { panic!(); }
1961 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1962 assert_eq!(route.paths[0].len(), 2);
1964 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1965 assert_eq!(route.paths[0][0].short_channel_id, 2);
1966 assert_eq!(route.paths[0][0].fee_msat, 100);
1967 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1968 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1969 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1971 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1972 assert_eq!(route.paths[0][1].short_channel_id, 4);
1973 assert_eq!(route.paths[0][1].fee_msat, 100);
1974 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1975 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1976 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1980 fn invalid_first_hop_test() {
1981 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1982 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1983 let payee = Payee::from_node_id(nodes[2]);
1984 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1986 // Simple route to 2 via 1
1988 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1990 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
1991 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1992 } else { panic!(); }
1994 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1995 assert_eq!(route.paths[0].len(), 2);
1999 fn htlc_minimum_test() {
2000 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2001 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2002 let payee = Payee::from_node_id(nodes[2]);
2003 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2005 // Simple route to 2 via 1
2007 // Disable other paths
2008 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2009 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2010 short_channel_id: 12,
2012 flags: 2, // to disable
2013 cltv_expiry_delta: 0,
2014 htlc_minimum_msat: 0,
2015 htlc_maximum_msat: OptionalField::Absent,
2017 fee_proportional_millionths: 0,
2018 excess_data: Vec::new()
2020 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2022 short_channel_id: 3,
2024 flags: 2, // to disable
2025 cltv_expiry_delta: 0,
2026 htlc_minimum_msat: 0,
2027 htlc_maximum_msat: OptionalField::Absent,
2029 fee_proportional_millionths: 0,
2030 excess_data: Vec::new()
2032 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2034 short_channel_id: 13,
2036 flags: 2, // to disable
2037 cltv_expiry_delta: 0,
2038 htlc_minimum_msat: 0,
2039 htlc_maximum_msat: OptionalField::Absent,
2041 fee_proportional_millionths: 0,
2042 excess_data: Vec::new()
2044 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2046 short_channel_id: 6,
2048 flags: 2, // to disable
2049 cltv_expiry_delta: 0,
2050 htlc_minimum_msat: 0,
2051 htlc_maximum_msat: OptionalField::Absent,
2053 fee_proportional_millionths: 0,
2054 excess_data: Vec::new()
2056 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2057 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2058 short_channel_id: 7,
2060 flags: 2, // to disable
2061 cltv_expiry_delta: 0,
2062 htlc_minimum_msat: 0,
2063 htlc_maximum_msat: OptionalField::Absent,
2065 fee_proportional_millionths: 0,
2066 excess_data: Vec::new()
2069 // Check against amount_to_transfer_over_msat.
2070 // Set minimal HTLC of 200_000_000 msat.
2071 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2073 short_channel_id: 2,
2076 cltv_expiry_delta: 0,
2077 htlc_minimum_msat: 200_000_000,
2078 htlc_maximum_msat: OptionalField::Absent,
2080 fee_proportional_millionths: 0,
2081 excess_data: Vec::new()
2084 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2086 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2087 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2088 short_channel_id: 4,
2091 cltv_expiry_delta: 0,
2092 htlc_minimum_msat: 0,
2093 htlc_maximum_msat: OptionalField::Present(199_999_999),
2095 fee_proportional_millionths: 0,
2096 excess_data: Vec::new()
2099 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2100 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2101 assert_eq!(err, "Failed to find a path to the given destination");
2102 } else { panic!(); }
2104 // Lift the restriction on the first hop.
2105 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2106 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2107 short_channel_id: 2,
2110 cltv_expiry_delta: 0,
2111 htlc_minimum_msat: 0,
2112 htlc_maximum_msat: OptionalField::Absent,
2114 fee_proportional_millionths: 0,
2115 excess_data: Vec::new()
2118 // A payment above the minimum should pass
2119 let route = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2120 assert_eq!(route.paths[0].len(), 2);
2124 fn htlc_minimum_overpay_test() {
2125 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2126 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2127 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2128 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2130 // A route to node#2 via two paths.
2131 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2132 // Thus, they can't send 60 without overpaying.
2133 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2134 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2135 short_channel_id: 2,
2138 cltv_expiry_delta: 0,
2139 htlc_minimum_msat: 35_000,
2140 htlc_maximum_msat: OptionalField::Present(40_000),
2142 fee_proportional_millionths: 0,
2143 excess_data: Vec::new()
2145 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2146 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2147 short_channel_id: 12,
2150 cltv_expiry_delta: 0,
2151 htlc_minimum_msat: 35_000,
2152 htlc_maximum_msat: OptionalField::Present(40_000),
2154 fee_proportional_millionths: 0,
2155 excess_data: Vec::new()
2159 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2160 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2161 short_channel_id: 13,
2164 cltv_expiry_delta: 0,
2165 htlc_minimum_msat: 0,
2166 htlc_maximum_msat: OptionalField::Absent,
2168 fee_proportional_millionths: 0,
2169 excess_data: Vec::new()
2171 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2173 short_channel_id: 4,
2176 cltv_expiry_delta: 0,
2177 htlc_minimum_msat: 0,
2178 htlc_maximum_msat: OptionalField::Absent,
2180 fee_proportional_millionths: 0,
2181 excess_data: Vec::new()
2184 // Disable other paths
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: 1,
2189 flags: 2, // to disable
2190 cltv_expiry_delta: 0,
2191 htlc_minimum_msat: 0,
2192 htlc_maximum_msat: OptionalField::Absent,
2194 fee_proportional_millionths: 0,
2195 excess_data: Vec::new()
2198 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2199 // Overpay fees to hit htlc_minimum_msat.
2200 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2201 // TODO: this could be better balanced to overpay 10k and not 15k.
2202 assert_eq!(overpaid_fees, 15_000);
2204 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2205 // while taking even more fee to match htlc_minimum_msat.
2206 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2208 short_channel_id: 12,
2211 cltv_expiry_delta: 0,
2212 htlc_minimum_msat: 65_000,
2213 htlc_maximum_msat: OptionalField::Present(80_000),
2215 fee_proportional_millionths: 0,
2216 excess_data: Vec::new()
2218 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2220 short_channel_id: 2,
2223 cltv_expiry_delta: 0,
2224 htlc_minimum_msat: 0,
2225 htlc_maximum_msat: OptionalField::Absent,
2227 fee_proportional_millionths: 0,
2228 excess_data: Vec::new()
2230 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2232 short_channel_id: 4,
2235 cltv_expiry_delta: 0,
2236 htlc_minimum_msat: 0,
2237 htlc_maximum_msat: OptionalField::Absent,
2239 fee_proportional_millionths: 100_000,
2240 excess_data: Vec::new()
2243 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2244 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2245 assert_eq!(route.paths.len(), 1);
2246 assert_eq!(route.paths[0][0].short_channel_id, 12);
2247 let fees = route.paths[0][0].fee_msat;
2248 assert_eq!(fees, 5_000);
2250 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2251 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2252 // the other channel.
2253 assert_eq!(route.paths.len(), 1);
2254 assert_eq!(route.paths[0][0].short_channel_id, 2);
2255 let fees = route.paths[0][0].fee_msat;
2256 assert_eq!(fees, 5_000);
2260 fn disable_channels_test() {
2261 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2262 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2263 let payee = Payee::from_node_id(nodes[2]);
2264 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2266 // // Disable channels 4 and 12 by flags=2
2267 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2268 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2269 short_channel_id: 4,
2271 flags: 2, // to disable
2272 cltv_expiry_delta: 0,
2273 htlc_minimum_msat: 0,
2274 htlc_maximum_msat: OptionalField::Absent,
2276 fee_proportional_millionths: 0,
2277 excess_data: Vec::new()
2279 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2280 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2281 short_channel_id: 12,
2283 flags: 2, // to disable
2284 cltv_expiry_delta: 0,
2285 htlc_minimum_msat: 0,
2286 htlc_maximum_msat: OptionalField::Absent,
2288 fee_proportional_millionths: 0,
2289 excess_data: Vec::new()
2292 // If all the channels require some features we don't understand, route should fail
2293 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2294 assert_eq!(err, "Failed to find a path to the given destination");
2295 } else { panic!(); }
2297 // If we specify a channel to node7, that overrides our local channel view and that gets used
2298 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2299 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2300 assert_eq!(route.paths[0].len(), 2);
2302 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2303 assert_eq!(route.paths[0][0].short_channel_id, 42);
2304 assert_eq!(route.paths[0][0].fee_msat, 200);
2305 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2306 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2307 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2309 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2310 assert_eq!(route.paths[0][1].short_channel_id, 13);
2311 assert_eq!(route.paths[0][1].fee_msat, 100);
2312 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2313 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2314 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2318 fn disable_node_test() {
2319 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2320 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2321 let payee = Payee::from_node_id(nodes[2]);
2322 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2324 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2325 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2326 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2327 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2328 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2330 // If all nodes require some features we don't understand, route should fail
2331 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2332 assert_eq!(err, "Failed to find a path to the given destination");
2333 } else { panic!(); }
2335 // If we specify a channel to node7, that overrides our local channel view and that gets used
2336 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2337 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2338 assert_eq!(route.paths[0].len(), 2);
2340 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2341 assert_eq!(route.paths[0][0].short_channel_id, 42);
2342 assert_eq!(route.paths[0][0].fee_msat, 200);
2343 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2344 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2345 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2347 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2348 assert_eq!(route.paths[0][1].short_channel_id, 13);
2349 assert_eq!(route.paths[0][1].fee_msat, 100);
2350 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2351 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2352 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2354 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2355 // naively) assume that the user checked the feature bits on the invoice, which override
2356 // the node_announcement.
2360 fn our_chans_test() {
2361 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2362 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2363 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2365 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2366 let payee = Payee::from_node_id(nodes[0]);
2367 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2368 assert_eq!(route.paths[0].len(), 3);
2370 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2371 assert_eq!(route.paths[0][0].short_channel_id, 2);
2372 assert_eq!(route.paths[0][0].fee_msat, 200);
2373 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2374 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2375 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2377 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2378 assert_eq!(route.paths[0][1].short_channel_id, 4);
2379 assert_eq!(route.paths[0][1].fee_msat, 100);
2380 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2381 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2382 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2384 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2385 assert_eq!(route.paths[0][2].short_channel_id, 3);
2386 assert_eq!(route.paths[0][2].fee_msat, 100);
2387 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2388 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2389 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2391 // If we specify a channel to node7, that overrides our local channel view and that gets used
2392 let payee = Payee::from_node_id(nodes[2]);
2393 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2394 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2395 assert_eq!(route.paths[0].len(), 2);
2397 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2398 assert_eq!(route.paths[0][0].short_channel_id, 42);
2399 assert_eq!(route.paths[0][0].fee_msat, 200);
2400 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2401 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2402 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2404 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2405 assert_eq!(route.paths[0][1].short_channel_id, 13);
2406 assert_eq!(route.paths[0][1].fee_msat, 100);
2407 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2408 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2409 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2412 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2413 let zero_fees = RoutingFees {
2415 proportional_millionths: 0,
2417 vec![RouteHint(vec![RouteHintHop {
2418 src_node_id: nodes[3],
2419 short_channel_id: 8,
2421 cltv_expiry_delta: (8 << 8) | 1,
2422 htlc_minimum_msat: None,
2423 htlc_maximum_msat: None,
2425 ]), RouteHint(vec![RouteHintHop {
2426 src_node_id: nodes[4],
2427 short_channel_id: 9,
2430 proportional_millionths: 0,
2432 cltv_expiry_delta: (9 << 8) | 1,
2433 htlc_minimum_msat: None,
2434 htlc_maximum_msat: None,
2435 }]), RouteHint(vec![RouteHintHop {
2436 src_node_id: nodes[5],
2437 short_channel_id: 10,
2439 cltv_expiry_delta: (10 << 8) | 1,
2440 htlc_minimum_msat: None,
2441 htlc_maximum_msat: None,
2445 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2446 let zero_fees = RoutingFees {
2448 proportional_millionths: 0,
2450 vec![RouteHint(vec![RouteHintHop {
2451 src_node_id: nodes[2],
2452 short_channel_id: 5,
2455 proportional_millionths: 0,
2457 cltv_expiry_delta: (5 << 8) | 1,
2458 htlc_minimum_msat: None,
2459 htlc_maximum_msat: None,
2461 src_node_id: nodes[3],
2462 short_channel_id: 8,
2464 cltv_expiry_delta: (8 << 8) | 1,
2465 htlc_minimum_msat: None,
2466 htlc_maximum_msat: None,
2468 ]), RouteHint(vec![RouteHintHop {
2469 src_node_id: nodes[4],
2470 short_channel_id: 9,
2473 proportional_millionths: 0,
2475 cltv_expiry_delta: (9 << 8) | 1,
2476 htlc_minimum_msat: None,
2477 htlc_maximum_msat: None,
2478 }]), RouteHint(vec![RouteHintHop {
2479 src_node_id: nodes[5],
2480 short_channel_id: 10,
2482 cltv_expiry_delta: (10 << 8) | 1,
2483 htlc_minimum_msat: None,
2484 htlc_maximum_msat: None,
2489 fn partial_route_hint_test() {
2490 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2491 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2492 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2494 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2495 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2496 // RouteHint may be partially used by the algo to build the best path.
2498 // First check that last hop can't have its source as the payee.
2499 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2500 src_node_id: nodes[6],
2501 short_channel_id: 8,
2504 proportional_millionths: 0,
2506 cltv_expiry_delta: (8 << 8) | 1,
2507 htlc_minimum_msat: None,
2508 htlc_maximum_msat: None,
2511 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2512 invalid_last_hops.push(invalid_last_hop);
2514 let payee = Payee::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2515 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2516 assert_eq!(err, "Route hint cannot have the payee as the source.");
2517 } else { panic!(); }
2520 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2521 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2522 assert_eq!(route.paths[0].len(), 5);
2524 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2525 assert_eq!(route.paths[0][0].short_channel_id, 2);
2526 assert_eq!(route.paths[0][0].fee_msat, 100);
2527 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2528 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2529 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2531 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2532 assert_eq!(route.paths[0][1].short_channel_id, 4);
2533 assert_eq!(route.paths[0][1].fee_msat, 0);
2534 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2535 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2536 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2538 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2539 assert_eq!(route.paths[0][2].short_channel_id, 6);
2540 assert_eq!(route.paths[0][2].fee_msat, 0);
2541 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2542 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2543 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2545 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2546 assert_eq!(route.paths[0][3].short_channel_id, 11);
2547 assert_eq!(route.paths[0][3].fee_msat, 0);
2548 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2549 // If we have a peer in the node map, we'll use their features here since we don't have
2550 // a way of figuring out their features from the invoice:
2551 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2552 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2554 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2555 assert_eq!(route.paths[0][4].short_channel_id, 8);
2556 assert_eq!(route.paths[0][4].fee_msat, 100);
2557 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2558 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2559 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2562 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2563 let zero_fees = RoutingFees {
2565 proportional_millionths: 0,
2567 vec![RouteHint(vec![RouteHintHop {
2568 src_node_id: nodes[3],
2569 short_channel_id: 8,
2571 cltv_expiry_delta: (8 << 8) | 1,
2572 htlc_minimum_msat: None,
2573 htlc_maximum_msat: None,
2574 }]), RouteHint(vec![
2576 ]), RouteHint(vec![RouteHintHop {
2577 src_node_id: nodes[5],
2578 short_channel_id: 10,
2580 cltv_expiry_delta: (10 << 8) | 1,
2581 htlc_minimum_msat: None,
2582 htlc_maximum_msat: None,
2587 fn ignores_empty_last_hops_test() {
2588 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2589 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2590 let payee = Payee::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2591 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2593 // Test handling of an empty RouteHint passed in Invoice.
2595 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2596 assert_eq!(route.paths[0].len(), 5);
2598 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2599 assert_eq!(route.paths[0][0].short_channel_id, 2);
2600 assert_eq!(route.paths[0][0].fee_msat, 100);
2601 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2602 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2603 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2605 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2606 assert_eq!(route.paths[0][1].short_channel_id, 4);
2607 assert_eq!(route.paths[0][1].fee_msat, 0);
2608 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2609 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2610 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2612 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2613 assert_eq!(route.paths[0][2].short_channel_id, 6);
2614 assert_eq!(route.paths[0][2].fee_msat, 0);
2615 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2616 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2617 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2619 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2620 assert_eq!(route.paths[0][3].short_channel_id, 11);
2621 assert_eq!(route.paths[0][3].fee_msat, 0);
2622 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2623 // If we have a peer in the node map, we'll use their features here since we don't have
2624 // a way of figuring out their features from the invoice:
2625 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2626 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2628 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2629 assert_eq!(route.paths[0][4].short_channel_id, 8);
2630 assert_eq!(route.paths[0][4].fee_msat, 100);
2631 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2632 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2633 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2636 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2637 let zero_fees = RoutingFees {
2639 proportional_millionths: 0,
2641 vec![RouteHint(vec![RouteHintHop {
2642 src_node_id: nodes[2],
2643 short_channel_id: 5,
2646 proportional_millionths: 0,
2648 cltv_expiry_delta: (5 << 8) | 1,
2649 htlc_minimum_msat: None,
2650 htlc_maximum_msat: None,
2652 src_node_id: nodes[3],
2653 short_channel_id: 8,
2655 cltv_expiry_delta: (8 << 8) | 1,
2656 htlc_minimum_msat: None,
2657 htlc_maximum_msat: None,
2658 }]), RouteHint(vec![RouteHintHop {
2659 src_node_id: nodes[5],
2660 short_channel_id: 10,
2662 cltv_expiry_delta: (10 << 8) | 1,
2663 htlc_minimum_msat: None,
2664 htlc_maximum_msat: None,
2669 fn multi_hint_last_hops_test() {
2670 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2671 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2672 let payee = Payee::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2673 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2674 // Test through channels 2, 3, 5, 8.
2675 // Test shows that multiple hop hints are considered.
2677 // Disabling channels 6 & 7 by flags=2
2678 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2679 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2680 short_channel_id: 6,
2682 flags: 2, // to disable
2683 cltv_expiry_delta: 0,
2684 htlc_minimum_msat: 0,
2685 htlc_maximum_msat: OptionalField::Absent,
2687 fee_proportional_millionths: 0,
2688 excess_data: Vec::new()
2690 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2691 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2692 short_channel_id: 7,
2694 flags: 2, // to disable
2695 cltv_expiry_delta: 0,
2696 htlc_minimum_msat: 0,
2697 htlc_maximum_msat: OptionalField::Absent,
2699 fee_proportional_millionths: 0,
2700 excess_data: Vec::new()
2703 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2704 assert_eq!(route.paths[0].len(), 4);
2706 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2707 assert_eq!(route.paths[0][0].short_channel_id, 2);
2708 assert_eq!(route.paths[0][0].fee_msat, 200);
2709 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2710 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2711 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2713 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2714 assert_eq!(route.paths[0][1].short_channel_id, 4);
2715 assert_eq!(route.paths[0][1].fee_msat, 100);
2716 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2717 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2718 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2720 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2721 assert_eq!(route.paths[0][2].short_channel_id, 5);
2722 assert_eq!(route.paths[0][2].fee_msat, 0);
2723 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2724 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2725 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2727 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2728 assert_eq!(route.paths[0][3].short_channel_id, 8);
2729 assert_eq!(route.paths[0][3].fee_msat, 100);
2730 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2731 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2732 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2735 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2736 let zero_fees = RoutingFees {
2738 proportional_millionths: 0,
2740 vec![RouteHint(vec![RouteHintHop {
2741 src_node_id: nodes[4],
2742 short_channel_id: 11,
2744 cltv_expiry_delta: (11 << 8) | 1,
2745 htlc_minimum_msat: None,
2746 htlc_maximum_msat: None,
2748 src_node_id: nodes[3],
2749 short_channel_id: 8,
2751 cltv_expiry_delta: (8 << 8) | 1,
2752 htlc_minimum_msat: None,
2753 htlc_maximum_msat: None,
2754 }]), RouteHint(vec![RouteHintHop {
2755 src_node_id: nodes[4],
2756 short_channel_id: 9,
2759 proportional_millionths: 0,
2761 cltv_expiry_delta: (9 << 8) | 1,
2762 htlc_minimum_msat: None,
2763 htlc_maximum_msat: None,
2764 }]), RouteHint(vec![RouteHintHop {
2765 src_node_id: nodes[5],
2766 short_channel_id: 10,
2768 cltv_expiry_delta: (10 << 8) | 1,
2769 htlc_minimum_msat: None,
2770 htlc_maximum_msat: None,
2775 fn last_hops_with_public_channel_test() {
2776 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2777 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2778 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2779 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2780 // This test shows that public routes can be present in the invoice
2781 // which would be handled in the same manner.
2783 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2784 assert_eq!(route.paths[0].len(), 5);
2786 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2787 assert_eq!(route.paths[0][0].short_channel_id, 2);
2788 assert_eq!(route.paths[0][0].fee_msat, 100);
2789 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2790 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2791 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2793 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2794 assert_eq!(route.paths[0][1].short_channel_id, 4);
2795 assert_eq!(route.paths[0][1].fee_msat, 0);
2796 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2797 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2798 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2800 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2801 assert_eq!(route.paths[0][2].short_channel_id, 6);
2802 assert_eq!(route.paths[0][2].fee_msat, 0);
2803 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2804 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2805 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2807 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2808 assert_eq!(route.paths[0][3].short_channel_id, 11);
2809 assert_eq!(route.paths[0][3].fee_msat, 0);
2810 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2811 // If we have a peer in the node map, we'll use their features here since we don't have
2812 // a way of figuring out their features from the invoice:
2813 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2814 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2816 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2817 assert_eq!(route.paths[0][4].short_channel_id, 8);
2818 assert_eq!(route.paths[0][4].fee_msat, 100);
2819 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2820 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2821 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2825 fn our_chans_last_hop_connect_test() {
2826 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2827 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2828 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2830 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2831 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2832 let mut last_hops = last_hops(&nodes);
2833 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2834 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2835 assert_eq!(route.paths[0].len(), 2);
2837 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2838 assert_eq!(route.paths[0][0].short_channel_id, 42);
2839 assert_eq!(route.paths[0][0].fee_msat, 0);
2840 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2841 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2842 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2844 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2845 assert_eq!(route.paths[0][1].short_channel_id, 8);
2846 assert_eq!(route.paths[0][1].fee_msat, 100);
2847 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2848 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2849 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2851 last_hops[0].0[0].fees.base_msat = 1000;
2853 // Revert to via 6 as the fee on 8 goes up
2854 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops);
2855 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2856 assert_eq!(route.paths[0].len(), 4);
2858 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2859 assert_eq!(route.paths[0][0].short_channel_id, 2);
2860 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2861 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2862 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2863 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2865 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2866 assert_eq!(route.paths[0][1].short_channel_id, 4);
2867 assert_eq!(route.paths[0][1].fee_msat, 100);
2868 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2869 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2870 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2872 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2873 assert_eq!(route.paths[0][2].short_channel_id, 7);
2874 assert_eq!(route.paths[0][2].fee_msat, 0);
2875 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2876 // If we have a peer in the node map, we'll use their features here since we don't have
2877 // a way of figuring out their features from the invoice:
2878 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2879 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2881 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2882 assert_eq!(route.paths[0][3].short_channel_id, 10);
2883 assert_eq!(route.paths[0][3].fee_msat, 100);
2884 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2885 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2886 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2888 // ...but still use 8 for larger payments as 6 has a variable feerate
2889 let route = get_route(&our_id, &payee, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2890 assert_eq!(route.paths[0].len(), 5);
2892 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2893 assert_eq!(route.paths[0][0].short_channel_id, 2);
2894 assert_eq!(route.paths[0][0].fee_msat, 3000);
2895 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2896 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2897 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2899 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2900 assert_eq!(route.paths[0][1].short_channel_id, 4);
2901 assert_eq!(route.paths[0][1].fee_msat, 0);
2902 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2903 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2904 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2906 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2907 assert_eq!(route.paths[0][2].short_channel_id, 6);
2908 assert_eq!(route.paths[0][2].fee_msat, 0);
2909 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2910 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2911 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2913 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2914 assert_eq!(route.paths[0][3].short_channel_id, 11);
2915 assert_eq!(route.paths[0][3].fee_msat, 1000);
2916 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2917 // If we have a peer in the node map, we'll use their features here since we don't have
2918 // a way of figuring out their features from the invoice:
2919 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2920 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2922 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2923 assert_eq!(route.paths[0][4].short_channel_id, 8);
2924 assert_eq!(route.paths[0][4].fee_msat, 2000);
2925 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2926 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2927 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2930 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> {
2931 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2932 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2933 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2935 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2936 let last_hops = RouteHint(vec![RouteHintHop {
2937 src_node_id: middle_node_id,
2938 short_channel_id: 8,
2941 proportional_millionths: last_hop_fee_prop,
2943 cltv_expiry_delta: (8 << 8) | 1,
2944 htlc_minimum_msat: None,
2945 htlc_maximum_msat: last_hop_htlc_max,
2947 let payee = Payee::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
2948 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2949 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2950 get_route(&source_node_id, &payee, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer)
2954 fn unannounced_path_test() {
2955 // We should be able to send a payment to a destination without any help of a routing graph
2956 // if we have a channel with a common counterparty that appears in the first and last hop
2958 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2960 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2961 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2962 assert_eq!(route.paths[0].len(), 2);
2964 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2965 assert_eq!(route.paths[0][0].short_channel_id, 42);
2966 assert_eq!(route.paths[0][0].fee_msat, 1001);
2967 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2968 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2969 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2971 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2972 assert_eq!(route.paths[0][1].short_channel_id, 8);
2973 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2974 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2975 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2976 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2980 fn overflow_unannounced_path_test_liquidity_underflow() {
2981 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2982 // the last-hop had a fee which overflowed a u64, we'd panic.
2983 // This was due to us adding the first-hop from us unconditionally, causing us to think
2984 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2985 // In this test, we previously hit a subtraction underflow due to having less available
2986 // liquidity at the last hop than 0.
2987 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());
2991 fn overflow_unannounced_path_test_feerate_overflow() {
2992 // This tests for the same case as above, except instead of hitting a subtraction
2993 // underflow, we hit a case where the fee charged at a hop overflowed.
2994 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());
2998 fn available_amount_while_routing_test() {
2999 // Tests whether we choose the correct available channel amount while routing.
3001 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3002 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3003 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3004 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3006 // We will use a simple single-path route from
3007 // our node to node2 via node0: channels {1, 3}.
3009 // First disable all other paths.
3010 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3012 short_channel_id: 2,
3015 cltv_expiry_delta: 0,
3016 htlc_minimum_msat: 0,
3017 htlc_maximum_msat: OptionalField::Present(100_000),
3019 fee_proportional_millionths: 0,
3020 excess_data: Vec::new()
3022 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3024 short_channel_id: 12,
3027 cltv_expiry_delta: 0,
3028 htlc_minimum_msat: 0,
3029 htlc_maximum_msat: OptionalField::Present(100_000),
3031 fee_proportional_millionths: 0,
3032 excess_data: Vec::new()
3035 // Make the first channel (#1) very permissive,
3036 // and we will be testing all limits on the second channel.
3037 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3038 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3039 short_channel_id: 1,
3042 cltv_expiry_delta: 0,
3043 htlc_minimum_msat: 0,
3044 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3046 fee_proportional_millionths: 0,
3047 excess_data: Vec::new()
3050 // First, let's see if routing works if we have absolutely no idea about the available amount.
3051 // In this case, it should be set to 250_000 sats.
3052 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3053 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3054 short_channel_id: 3,
3057 cltv_expiry_delta: 0,
3058 htlc_minimum_msat: 0,
3059 htlc_maximum_msat: OptionalField::Absent,
3061 fee_proportional_millionths: 0,
3062 excess_data: Vec::new()
3066 // Attempt to route more than available results in a failure.
3067 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3068 &our_id, &payee, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3069 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3070 } else { panic!(); }
3074 // Now, attempt to route an exact amount we have should be fine.
3075 let route = get_route(&our_id, &payee, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3076 assert_eq!(route.paths.len(), 1);
3077 let path = route.paths.last().unwrap();
3078 assert_eq!(path.len(), 2);
3079 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3080 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3083 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3084 // Disable channel #1 and use another first hop.
3085 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3086 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3087 short_channel_id: 1,
3090 cltv_expiry_delta: 0,
3091 htlc_minimum_msat: 0,
3092 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3094 fee_proportional_millionths: 0,
3095 excess_data: Vec::new()
3098 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3099 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3102 // Attempt to route more than available results in a failure.
3103 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3104 &our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3105 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3106 } else { panic!(); }
3110 // Now, attempt to route an exact amount we have should be fine.
3111 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3112 assert_eq!(route.paths.len(), 1);
3113 let path = route.paths.last().unwrap();
3114 assert_eq!(path.len(), 2);
3115 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3116 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3119 // Enable channel #1 back.
3120 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3121 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3122 short_channel_id: 1,
3125 cltv_expiry_delta: 0,
3126 htlc_minimum_msat: 0,
3127 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3129 fee_proportional_millionths: 0,
3130 excess_data: Vec::new()
3134 // Now let's see if routing works if we know only htlc_maximum_msat.
3135 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3137 short_channel_id: 3,
3140 cltv_expiry_delta: 0,
3141 htlc_minimum_msat: 0,
3142 htlc_maximum_msat: OptionalField::Present(15_000),
3144 fee_proportional_millionths: 0,
3145 excess_data: Vec::new()
3149 // Attempt to route more than available results in a failure.
3150 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3151 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3152 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3153 } else { panic!(); }
3157 // Now, attempt to route an exact amount we have should be fine.
3158 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3159 assert_eq!(route.paths.len(), 1);
3160 let path = route.paths.last().unwrap();
3161 assert_eq!(path.len(), 2);
3162 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3163 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3166 // Now let's see if routing works if we know only capacity from the UTXO.
3168 // We can't change UTXO capacity on the fly, so we'll disable
3169 // the existing channel and add another one with the capacity we need.
3170 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3172 short_channel_id: 3,
3175 cltv_expiry_delta: 0,
3176 htlc_minimum_msat: 0,
3177 htlc_maximum_msat: OptionalField::Absent,
3179 fee_proportional_millionths: 0,
3180 excess_data: Vec::new()
3183 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3184 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3185 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3186 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3187 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3189 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3190 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3192 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3193 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3195 short_channel_id: 333,
3198 cltv_expiry_delta: (3 << 8) | 1,
3199 htlc_minimum_msat: 0,
3200 htlc_maximum_msat: OptionalField::Absent,
3202 fee_proportional_millionths: 0,
3203 excess_data: Vec::new()
3205 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3206 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3207 short_channel_id: 333,
3210 cltv_expiry_delta: (3 << 8) | 2,
3211 htlc_minimum_msat: 0,
3212 htlc_maximum_msat: OptionalField::Absent,
3214 fee_proportional_millionths: 0,
3215 excess_data: Vec::new()
3219 // Attempt to route more than available results in a failure.
3220 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3221 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3222 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3223 } else { panic!(); }
3227 // Now, attempt to route an exact amount we have should be fine.
3228 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3229 assert_eq!(route.paths.len(), 1);
3230 let path = route.paths.last().unwrap();
3231 assert_eq!(path.len(), 2);
3232 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3233 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3236 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3237 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3239 short_channel_id: 333,
3242 cltv_expiry_delta: 0,
3243 htlc_minimum_msat: 0,
3244 htlc_maximum_msat: OptionalField::Present(10_000),
3246 fee_proportional_millionths: 0,
3247 excess_data: Vec::new()
3251 // Attempt to route more than available results in a failure.
3252 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3253 &our_id, &payee, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3254 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3255 } else { panic!(); }
3259 // Now, attempt to route an exact amount we have should be fine.
3260 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3261 assert_eq!(route.paths.len(), 1);
3262 let path = route.paths.last().unwrap();
3263 assert_eq!(path.len(), 2);
3264 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3265 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3270 fn available_liquidity_last_hop_test() {
3271 // Check that available liquidity properly limits the path even when only
3272 // one of the latter hops is limited.
3273 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3274 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3275 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3276 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3278 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3279 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3280 // Total capacity: 50 sats.
3282 // Disable other potential paths.
3283 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3284 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3285 short_channel_id: 2,
3288 cltv_expiry_delta: 0,
3289 htlc_minimum_msat: 0,
3290 htlc_maximum_msat: OptionalField::Present(100_000),
3292 fee_proportional_millionths: 0,
3293 excess_data: Vec::new()
3295 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3296 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3297 short_channel_id: 7,
3300 cltv_expiry_delta: 0,
3301 htlc_minimum_msat: 0,
3302 htlc_maximum_msat: OptionalField::Present(100_000),
3304 fee_proportional_millionths: 0,
3305 excess_data: Vec::new()
3310 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3311 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3312 short_channel_id: 12,
3315 cltv_expiry_delta: 0,
3316 htlc_minimum_msat: 0,
3317 htlc_maximum_msat: OptionalField::Present(100_000),
3319 fee_proportional_millionths: 0,
3320 excess_data: Vec::new()
3322 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3323 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3324 short_channel_id: 13,
3327 cltv_expiry_delta: 0,
3328 htlc_minimum_msat: 0,
3329 htlc_maximum_msat: OptionalField::Present(100_000),
3331 fee_proportional_millionths: 0,
3332 excess_data: Vec::new()
3335 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3337 short_channel_id: 6,
3340 cltv_expiry_delta: 0,
3341 htlc_minimum_msat: 0,
3342 htlc_maximum_msat: OptionalField::Present(50_000),
3344 fee_proportional_millionths: 0,
3345 excess_data: Vec::new()
3347 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3349 short_channel_id: 11,
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()
3360 // Attempt to route more than available results in a failure.
3361 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3362 &our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3363 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3364 } else { panic!(); }
3368 // Now, attempt to route 49 sats (just a bit below the capacity).
3369 let route = get_route(&our_id, &payee, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3370 assert_eq!(route.paths.len(), 1);
3371 let mut total_amount_paid_msat = 0;
3372 for path in &route.paths {
3373 assert_eq!(path.len(), 4);
3374 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3375 total_amount_paid_msat += path.last().unwrap().fee_msat;
3377 assert_eq!(total_amount_paid_msat, 49_000);
3381 // Attempt to route an exact amount is also fine
3382 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3383 assert_eq!(route.paths.len(), 1);
3384 let mut total_amount_paid_msat = 0;
3385 for path in &route.paths {
3386 assert_eq!(path.len(), 4);
3387 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3388 total_amount_paid_msat += path.last().unwrap().fee_msat;
3390 assert_eq!(total_amount_paid_msat, 50_000);
3395 fn ignore_fee_first_hop_test() {
3396 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3397 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3398 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3399 let payee = Payee::from_node_id(nodes[2]);
3401 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3402 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3404 short_channel_id: 1,
3407 cltv_expiry_delta: 0,
3408 htlc_minimum_msat: 0,
3409 htlc_maximum_msat: OptionalField::Present(100_000),
3410 fee_base_msat: 1_000_000,
3411 fee_proportional_millionths: 0,
3412 excess_data: Vec::new()
3414 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3415 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3416 short_channel_id: 3,
3419 cltv_expiry_delta: 0,
3420 htlc_minimum_msat: 0,
3421 htlc_maximum_msat: OptionalField::Present(50_000),
3423 fee_proportional_millionths: 0,
3424 excess_data: Vec::new()
3428 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3429 assert_eq!(route.paths.len(), 1);
3430 let mut total_amount_paid_msat = 0;
3431 for path in &route.paths {
3432 assert_eq!(path.len(), 2);
3433 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3434 total_amount_paid_msat += path.last().unwrap().fee_msat;
3436 assert_eq!(total_amount_paid_msat, 50_000);
3441 fn simple_mpp_route_test() {
3442 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3443 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3444 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3445 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3447 // We need a route consisting of 3 paths:
3448 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3449 // To achieve this, the amount being transferred should be around
3450 // the total capacity of these 3 paths.
3452 // First, we set limits on these (previously unlimited) channels.
3453 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3455 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3456 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3457 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3458 short_channel_id: 1,
3461 cltv_expiry_delta: 0,
3462 htlc_minimum_msat: 0,
3463 htlc_maximum_msat: OptionalField::Present(100_000),
3465 fee_proportional_millionths: 0,
3466 excess_data: Vec::new()
3468 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3469 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3470 short_channel_id: 3,
3473 cltv_expiry_delta: 0,
3474 htlc_minimum_msat: 0,
3475 htlc_maximum_msat: OptionalField::Present(50_000),
3477 fee_proportional_millionths: 0,
3478 excess_data: Vec::new()
3481 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3482 // (total limit 60).
3483 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3484 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3485 short_channel_id: 12,
3488 cltv_expiry_delta: 0,
3489 htlc_minimum_msat: 0,
3490 htlc_maximum_msat: OptionalField::Present(60_000),
3492 fee_proportional_millionths: 0,
3493 excess_data: Vec::new()
3495 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3496 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3497 short_channel_id: 13,
3500 cltv_expiry_delta: 0,
3501 htlc_minimum_msat: 0,
3502 htlc_maximum_msat: OptionalField::Present(60_000),
3504 fee_proportional_millionths: 0,
3505 excess_data: Vec::new()
3508 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3509 // (total capacity 180 sats).
3510 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3511 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3512 short_channel_id: 2,
3515 cltv_expiry_delta: 0,
3516 htlc_minimum_msat: 0,
3517 htlc_maximum_msat: OptionalField::Present(200_000),
3519 fee_proportional_millionths: 0,
3520 excess_data: Vec::new()
3522 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3523 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3524 short_channel_id: 4,
3527 cltv_expiry_delta: 0,
3528 htlc_minimum_msat: 0,
3529 htlc_maximum_msat: OptionalField::Present(180_000),
3531 fee_proportional_millionths: 0,
3532 excess_data: Vec::new()
3536 // Attempt to route more than available results in a failure.
3537 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3538 &our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3539 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3540 } else { panic!(); }
3544 // Now, attempt to route 250 sats (just a bit below the capacity).
3545 // Our algorithm should provide us with these 3 paths.
3546 let route = get_route(&our_id, &payee, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3547 assert_eq!(route.paths.len(), 3);
3548 let mut total_amount_paid_msat = 0;
3549 for path in &route.paths {
3550 assert_eq!(path.len(), 2);
3551 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3552 total_amount_paid_msat += path.last().unwrap().fee_msat;
3554 assert_eq!(total_amount_paid_msat, 250_000);
3558 // Attempt to route an exact amount is also fine
3559 let route = get_route(&our_id, &payee, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3560 assert_eq!(route.paths.len(), 3);
3561 let mut total_amount_paid_msat = 0;
3562 for path in &route.paths {
3563 assert_eq!(path.len(), 2);
3564 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3565 total_amount_paid_msat += path.last().unwrap().fee_msat;
3567 assert_eq!(total_amount_paid_msat, 290_000);
3572 fn long_mpp_route_test() {
3573 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3574 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3575 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3576 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3578 // We need a route consisting of 3 paths:
3579 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3580 // Note that these paths overlap (channels 5, 12, 13).
3581 // We will route 300 sats.
3582 // Each path will have 100 sats capacity, those channels which
3583 // are used twice will have 200 sats capacity.
3585 // Disable other potential paths.
3586 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3588 short_channel_id: 2,
3591 cltv_expiry_delta: 0,
3592 htlc_minimum_msat: 0,
3593 htlc_maximum_msat: OptionalField::Present(100_000),
3595 fee_proportional_millionths: 0,
3596 excess_data: Vec::new()
3598 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3599 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3600 short_channel_id: 7,
3603 cltv_expiry_delta: 0,
3604 htlc_minimum_msat: 0,
3605 htlc_maximum_msat: OptionalField::Present(100_000),
3607 fee_proportional_millionths: 0,
3608 excess_data: Vec::new()
3611 // Path via {node0, node2} is channels {1, 3, 5}.
3612 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3613 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3614 short_channel_id: 1,
3617 cltv_expiry_delta: 0,
3618 htlc_minimum_msat: 0,
3619 htlc_maximum_msat: OptionalField::Present(100_000),
3621 fee_proportional_millionths: 0,
3622 excess_data: Vec::new()
3624 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3625 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3626 short_channel_id: 3,
3629 cltv_expiry_delta: 0,
3630 htlc_minimum_msat: 0,
3631 htlc_maximum_msat: OptionalField::Present(100_000),
3633 fee_proportional_millionths: 0,
3634 excess_data: Vec::new()
3637 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3638 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3639 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3641 short_channel_id: 5,
3644 cltv_expiry_delta: 0,
3645 htlc_minimum_msat: 0,
3646 htlc_maximum_msat: OptionalField::Present(200_000),
3648 fee_proportional_millionths: 0,
3649 excess_data: Vec::new()
3652 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3653 // Add 100 sats to the capacities of {12, 13}, because these channels
3654 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3655 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3657 short_channel_id: 12,
3660 cltv_expiry_delta: 0,
3661 htlc_minimum_msat: 0,
3662 htlc_maximum_msat: OptionalField::Present(200_000),
3664 fee_proportional_millionths: 0,
3665 excess_data: Vec::new()
3667 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3669 short_channel_id: 13,
3672 cltv_expiry_delta: 0,
3673 htlc_minimum_msat: 0,
3674 htlc_maximum_msat: OptionalField::Present(200_000),
3676 fee_proportional_millionths: 0,
3677 excess_data: Vec::new()
3680 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3681 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3682 short_channel_id: 6,
3685 cltv_expiry_delta: 0,
3686 htlc_minimum_msat: 0,
3687 htlc_maximum_msat: OptionalField::Present(100_000),
3689 fee_proportional_millionths: 0,
3690 excess_data: Vec::new()
3692 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3693 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3694 short_channel_id: 11,
3697 cltv_expiry_delta: 0,
3698 htlc_minimum_msat: 0,
3699 htlc_maximum_msat: OptionalField::Present(100_000),
3701 fee_proportional_millionths: 0,
3702 excess_data: Vec::new()
3705 // Path via {node7, node2} is channels {12, 13, 5}.
3706 // We already limited them to 200 sats (they are used twice for 100 sats).
3707 // Nothing to do here.
3710 // Attempt to route more than available results in a failure.
3711 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3712 &our_id, &payee, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3713 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3714 } else { panic!(); }
3718 // Now, attempt to route 300 sats (exact amount we can route).
3719 // Our algorithm should provide us with these 3 paths, 100 sats each.
3720 let route = get_route(&our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3721 assert_eq!(route.paths.len(), 3);
3723 let mut total_amount_paid_msat = 0;
3724 for path in &route.paths {
3725 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3726 total_amount_paid_msat += path.last().unwrap().fee_msat;
3728 assert_eq!(total_amount_paid_msat, 300_000);
3734 fn mpp_cheaper_route_test() {
3735 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3736 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3737 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3738 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3740 // This test checks that if we have two cheaper paths and one more expensive path,
3741 // so that liquidity-wise any 2 of 3 combination is sufficient,
3742 // two cheaper paths will be taken.
3743 // These paths have equal available liquidity.
3745 // We need a combination of 3 paths:
3746 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3747 // Note that these paths overlap (channels 5, 12, 13).
3748 // Each path will have 100 sats capacity, those channels which
3749 // are used twice will have 200 sats capacity.
3751 // Disable other potential paths.
3752 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3753 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3754 short_channel_id: 2,
3757 cltv_expiry_delta: 0,
3758 htlc_minimum_msat: 0,
3759 htlc_maximum_msat: OptionalField::Present(100_000),
3761 fee_proportional_millionths: 0,
3762 excess_data: Vec::new()
3764 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3765 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3766 short_channel_id: 7,
3769 cltv_expiry_delta: 0,
3770 htlc_minimum_msat: 0,
3771 htlc_maximum_msat: OptionalField::Present(100_000),
3773 fee_proportional_millionths: 0,
3774 excess_data: Vec::new()
3777 // Path via {node0, node2} is channels {1, 3, 5}.
3778 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3780 short_channel_id: 1,
3783 cltv_expiry_delta: 0,
3784 htlc_minimum_msat: 0,
3785 htlc_maximum_msat: OptionalField::Present(100_000),
3787 fee_proportional_millionths: 0,
3788 excess_data: Vec::new()
3790 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3792 short_channel_id: 3,
3795 cltv_expiry_delta: 0,
3796 htlc_minimum_msat: 0,
3797 htlc_maximum_msat: OptionalField::Present(100_000),
3799 fee_proportional_millionths: 0,
3800 excess_data: Vec::new()
3803 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3804 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3805 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3806 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3807 short_channel_id: 5,
3810 cltv_expiry_delta: 0,
3811 htlc_minimum_msat: 0,
3812 htlc_maximum_msat: OptionalField::Present(200_000),
3814 fee_proportional_millionths: 0,
3815 excess_data: Vec::new()
3818 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3819 // Add 100 sats to the capacities of {12, 13}, because these channels
3820 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3821 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3822 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3823 short_channel_id: 12,
3826 cltv_expiry_delta: 0,
3827 htlc_minimum_msat: 0,
3828 htlc_maximum_msat: OptionalField::Present(200_000),
3830 fee_proportional_millionths: 0,
3831 excess_data: Vec::new()
3833 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3834 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3835 short_channel_id: 13,
3838 cltv_expiry_delta: 0,
3839 htlc_minimum_msat: 0,
3840 htlc_maximum_msat: OptionalField::Present(200_000),
3842 fee_proportional_millionths: 0,
3843 excess_data: Vec::new()
3846 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3847 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3848 short_channel_id: 6,
3851 cltv_expiry_delta: 0,
3852 htlc_minimum_msat: 0,
3853 htlc_maximum_msat: OptionalField::Present(100_000),
3854 fee_base_msat: 1_000,
3855 fee_proportional_millionths: 0,
3856 excess_data: Vec::new()
3858 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3859 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3860 short_channel_id: 11,
3863 cltv_expiry_delta: 0,
3864 htlc_minimum_msat: 0,
3865 htlc_maximum_msat: OptionalField::Present(100_000),
3867 fee_proportional_millionths: 0,
3868 excess_data: Vec::new()
3871 // Path via {node7, node2} is channels {12, 13, 5}.
3872 // We already limited them to 200 sats (they are used twice for 100 sats).
3873 // Nothing to do here.
3876 // Now, attempt to route 180 sats.
3877 // Our algorithm should provide us with these 2 paths.
3878 let route = get_route(&our_id, &payee, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3879 assert_eq!(route.paths.len(), 2);
3881 let mut total_value_transferred_msat = 0;
3882 let mut total_paid_msat = 0;
3883 for path in &route.paths {
3884 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3885 total_value_transferred_msat += path.last().unwrap().fee_msat;
3887 total_paid_msat += hop.fee_msat;
3890 // If we paid fee, this would be higher.
3891 assert_eq!(total_value_transferred_msat, 180_000);
3892 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3893 assert_eq!(total_fees_paid, 0);
3898 fn fees_on_mpp_route_test() {
3899 // This test makes sure that MPP algorithm properly takes into account
3900 // fees charged on the channels, by making the fees impactful:
3901 // if the fee is not properly accounted for, the behavior is different.
3902 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3903 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3904 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3905 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3907 // We need a route consisting of 2 paths:
3908 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3909 // We will route 200 sats, Each path will have 100 sats capacity.
3911 // This test is not particularly stable: e.g.,
3912 // there's a way to route via {node0, node2, node4}.
3913 // It works while pathfinding is deterministic, but can be broken otherwise.
3914 // It's fine to ignore this concern for now.
3916 // Disable other potential paths.
3917 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3919 short_channel_id: 2,
3922 cltv_expiry_delta: 0,
3923 htlc_minimum_msat: 0,
3924 htlc_maximum_msat: OptionalField::Present(100_000),
3926 fee_proportional_millionths: 0,
3927 excess_data: Vec::new()
3930 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3931 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3932 short_channel_id: 7,
3935 cltv_expiry_delta: 0,
3936 htlc_minimum_msat: 0,
3937 htlc_maximum_msat: OptionalField::Present(100_000),
3939 fee_proportional_millionths: 0,
3940 excess_data: Vec::new()
3943 // Path via {node0, node2} is channels {1, 3, 5}.
3944 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3945 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3946 short_channel_id: 1,
3949 cltv_expiry_delta: 0,
3950 htlc_minimum_msat: 0,
3951 htlc_maximum_msat: OptionalField::Present(100_000),
3953 fee_proportional_millionths: 0,
3954 excess_data: Vec::new()
3956 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3957 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3958 short_channel_id: 3,
3961 cltv_expiry_delta: 0,
3962 htlc_minimum_msat: 0,
3963 htlc_maximum_msat: OptionalField::Present(100_000),
3965 fee_proportional_millionths: 0,
3966 excess_data: Vec::new()
3969 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3970 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3971 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3972 short_channel_id: 5,
3975 cltv_expiry_delta: 0,
3976 htlc_minimum_msat: 0,
3977 htlc_maximum_msat: OptionalField::Present(100_000),
3979 fee_proportional_millionths: 0,
3980 excess_data: Vec::new()
3983 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3984 // All channels should be 100 sats capacity. But for the fee experiment,
3985 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3986 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3987 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3988 // so no matter how large are other channels,
3989 // the whole path will be limited by 100 sats with just these 2 conditions:
3990 // - channel 12 capacity is 250 sats
3991 // - fee for channel 6 is 150 sats
3992 // Let's test this by enforcing these 2 conditions and removing other limits.
3993 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3995 short_channel_id: 12,
3998 cltv_expiry_delta: 0,
3999 htlc_minimum_msat: 0,
4000 htlc_maximum_msat: OptionalField::Present(250_000),
4002 fee_proportional_millionths: 0,
4003 excess_data: Vec::new()
4005 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4007 short_channel_id: 13,
4010 cltv_expiry_delta: 0,
4011 htlc_minimum_msat: 0,
4012 htlc_maximum_msat: OptionalField::Absent,
4014 fee_proportional_millionths: 0,
4015 excess_data: Vec::new()
4018 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4020 short_channel_id: 6,
4023 cltv_expiry_delta: 0,
4024 htlc_minimum_msat: 0,
4025 htlc_maximum_msat: OptionalField::Absent,
4026 fee_base_msat: 150_000,
4027 fee_proportional_millionths: 0,
4028 excess_data: Vec::new()
4030 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4032 short_channel_id: 11,
4035 cltv_expiry_delta: 0,
4036 htlc_minimum_msat: 0,
4037 htlc_maximum_msat: OptionalField::Absent,
4039 fee_proportional_millionths: 0,
4040 excess_data: Vec::new()
4044 // Attempt to route more than available results in a failure.
4045 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4046 &our_id, &payee, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4047 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4048 } else { panic!(); }
4052 // Now, attempt to route 200 sats (exact amount we can route).
4053 let route = get_route(&our_id, &payee, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4054 assert_eq!(route.paths.len(), 2);
4056 let mut total_amount_paid_msat = 0;
4057 for path in &route.paths {
4058 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4059 total_amount_paid_msat += path.last().unwrap().fee_msat;
4061 assert_eq!(total_amount_paid_msat, 200_000);
4062 assert_eq!(route.get_total_fees(), 150_000);
4067 fn mpp_with_last_hops() {
4068 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4069 // via a single last-hop route hint, we'd fail to route if we first collected routes
4070 // totaling close but not quite enough to fund the full payment.
4072 // This was because we considered last-hop hints to have exactly the sought payment amount
4073 // instead of the amount we were trying to collect, needlessly limiting our path searching
4074 // at the very first hop.
4076 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4077 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4078 // to only have the remaining to-collect amount in available liquidity.
4080 // This bug appeared in production in some specific channel configurations.
4081 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4082 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4083 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4084 let payee = Payee::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4085 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4086 src_node_id: nodes[2],
4087 short_channel_id: 42,
4088 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4089 cltv_expiry_delta: 42,
4090 htlc_minimum_msat: None,
4091 htlc_maximum_msat: None,
4094 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4095 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4096 // would first use the no-fee route and then fail to find a path along the second route as
4097 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4098 // under 5% of our payment amount.
4099 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4101 short_channel_id: 1,
4104 cltv_expiry_delta: u16::max_value(),
4105 htlc_minimum_msat: 0,
4106 htlc_maximum_msat: OptionalField::Present(99_000),
4107 fee_base_msat: u32::max_value(),
4108 fee_proportional_millionths: u32::max_value(),
4109 excess_data: Vec::new()
4111 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4113 short_channel_id: 2,
4116 cltv_expiry_delta: u16::max_value(),
4117 htlc_minimum_msat: 0,
4118 htlc_maximum_msat: OptionalField::Present(99_000),
4119 fee_base_msat: u32::max_value(),
4120 fee_proportional_millionths: u32::max_value(),
4121 excess_data: Vec::new()
4123 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4125 short_channel_id: 4,
4128 cltv_expiry_delta: (4 << 8) | 1,
4129 htlc_minimum_msat: 0,
4130 htlc_maximum_msat: OptionalField::Absent,
4132 fee_proportional_millionths: 0,
4133 excess_data: Vec::new()
4135 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4137 short_channel_id: 13,
4139 flags: 0|2, // Channel disabled
4140 cltv_expiry_delta: (13 << 8) | 1,
4141 htlc_minimum_msat: 0,
4142 htlc_maximum_msat: OptionalField::Absent,
4144 fee_proportional_millionths: 2000000,
4145 excess_data: Vec::new()
4148 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4150 let route = get_route(&our_id, &payee, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4151 assert_eq!(route.paths.len(), 2);
4152 // Paths are somewhat randomly ordered, but:
4153 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4154 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4155 assert_eq!(route.paths[0][0].short_channel_id, 2);
4156 assert_eq!(route.paths[0][0].fee_msat, 1);
4157 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4158 assert_eq!(route.paths[1][0].short_channel_id, 1);
4159 assert_eq!(route.paths[1][0].fee_msat, 0);
4160 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4161 assert_eq!(route.get_total_fees(), 1);
4162 assert_eq!(route.get_total_amount(), 100_000);
4166 fn drop_lowest_channel_mpp_route_test() {
4167 // This test checks that low-capacity channel is dropped when after
4168 // path finding we realize that we found more capacity than we need.
4169 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4170 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4171 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4172 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4174 // We need a route consisting of 3 paths:
4175 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4177 // The first and the second paths should be sufficient, but the third should be
4178 // cheaper, so that we select it but drop later.
4180 // First, we set limits on these (previously unlimited) channels.
4181 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4183 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4184 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4186 short_channel_id: 1,
4189 cltv_expiry_delta: 0,
4190 htlc_minimum_msat: 0,
4191 htlc_maximum_msat: OptionalField::Present(100_000),
4193 fee_proportional_millionths: 0,
4194 excess_data: Vec::new()
4196 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4198 short_channel_id: 3,
4201 cltv_expiry_delta: 0,
4202 htlc_minimum_msat: 0,
4203 htlc_maximum_msat: OptionalField::Present(50_000),
4205 fee_proportional_millionths: 0,
4206 excess_data: Vec::new()
4209 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4210 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4212 short_channel_id: 12,
4215 cltv_expiry_delta: 0,
4216 htlc_minimum_msat: 0,
4217 htlc_maximum_msat: OptionalField::Present(60_000),
4219 fee_proportional_millionths: 0,
4220 excess_data: Vec::new()
4222 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4224 short_channel_id: 13,
4227 cltv_expiry_delta: 0,
4228 htlc_minimum_msat: 0,
4229 htlc_maximum_msat: OptionalField::Present(60_000),
4231 fee_proportional_millionths: 0,
4232 excess_data: Vec::new()
4235 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
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: 2,
4241 cltv_expiry_delta: 0,
4242 htlc_minimum_msat: 0,
4243 htlc_maximum_msat: OptionalField::Present(20_000),
4245 fee_proportional_millionths: 0,
4246 excess_data: Vec::new()
4248 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4249 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4250 short_channel_id: 4,
4253 cltv_expiry_delta: 0,
4254 htlc_minimum_msat: 0,
4255 htlc_maximum_msat: OptionalField::Present(20_000),
4257 fee_proportional_millionths: 0,
4258 excess_data: Vec::new()
4262 // Attempt to route more than available results in a failure.
4263 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4264 &our_id, &payee, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4265 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4266 } else { panic!(); }
4270 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4271 // Our algorithm should provide us with these 3 paths.
4272 let route = get_route(&our_id, &payee, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4273 assert_eq!(route.paths.len(), 3);
4274 let mut total_amount_paid_msat = 0;
4275 for path in &route.paths {
4276 assert_eq!(path.len(), 2);
4277 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4278 total_amount_paid_msat += path.last().unwrap().fee_msat;
4280 assert_eq!(total_amount_paid_msat, 125_000);
4284 // Attempt to route without the last small cheap channel
4285 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4286 assert_eq!(route.paths.len(), 2);
4287 let mut total_amount_paid_msat = 0;
4288 for path in &route.paths {
4289 assert_eq!(path.len(), 2);
4290 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4291 total_amount_paid_msat += path.last().unwrap().fee_msat;
4293 assert_eq!(total_amount_paid_msat, 90_000);
4298 fn min_criteria_consistency() {
4299 // Test that we don't use an inconsistent metric between updating and walking nodes during
4300 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4301 // was updated with a different criterion from the heap sorting, resulting in loops in
4302 // calculated paths. We test for that specific case here.
4304 // We construct a network that looks like this:
4306 // node2 -1(3)2- node3
4310 // node1 -1(5)2- node4 -1(1)2- node6
4316 // We create a loop on the side of our real path - our destination is node 6, with a
4317 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4318 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4319 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4320 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4321 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4322 // "previous hop" being set to node 3, creating a loop in the path.
4323 let secp_ctx = Secp256k1::new();
4324 let logger = Arc::new(test_utils::TestLogger::new());
4325 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4326 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4327 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4328 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4329 let payee = Payee::from_node_id(nodes[6]);
4331 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4332 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4333 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4334 short_channel_id: 6,
4337 cltv_expiry_delta: (6 << 8) | 0,
4338 htlc_minimum_msat: 0,
4339 htlc_maximum_msat: OptionalField::Absent,
4341 fee_proportional_millionths: 0,
4342 excess_data: Vec::new()
4344 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4346 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4347 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4349 short_channel_id: 5,
4352 cltv_expiry_delta: (5 << 8) | 0,
4353 htlc_minimum_msat: 0,
4354 htlc_maximum_msat: OptionalField::Absent,
4356 fee_proportional_millionths: 0,
4357 excess_data: Vec::new()
4359 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4361 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4362 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4363 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4364 short_channel_id: 4,
4367 cltv_expiry_delta: (4 << 8) | 0,
4368 htlc_minimum_msat: 0,
4369 htlc_maximum_msat: OptionalField::Absent,
4371 fee_proportional_millionths: 0,
4372 excess_data: Vec::new()
4374 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4376 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4377 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4378 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4379 short_channel_id: 3,
4382 cltv_expiry_delta: (3 << 8) | 0,
4383 htlc_minimum_msat: 0,
4384 htlc_maximum_msat: OptionalField::Absent,
4386 fee_proportional_millionths: 0,
4387 excess_data: Vec::new()
4389 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4391 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4392 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4394 short_channel_id: 2,
4397 cltv_expiry_delta: (2 << 8) | 0,
4398 htlc_minimum_msat: 0,
4399 htlc_maximum_msat: OptionalField::Absent,
4401 fee_proportional_millionths: 0,
4402 excess_data: Vec::new()
4405 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4406 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4407 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4408 short_channel_id: 1,
4411 cltv_expiry_delta: (1 << 8) | 0,
4412 htlc_minimum_msat: 100,
4413 htlc_maximum_msat: OptionalField::Absent,
4415 fee_proportional_millionths: 0,
4416 excess_data: Vec::new()
4418 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4421 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4422 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4423 assert_eq!(route.paths.len(), 1);
4424 assert_eq!(route.paths[0].len(), 3);
4426 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4427 assert_eq!(route.paths[0][0].short_channel_id, 6);
4428 assert_eq!(route.paths[0][0].fee_msat, 100);
4429 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4430 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4431 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4433 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4434 assert_eq!(route.paths[0][1].short_channel_id, 5);
4435 assert_eq!(route.paths[0][1].fee_msat, 0);
4436 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4437 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4438 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4440 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4441 assert_eq!(route.paths[0][2].short_channel_id, 1);
4442 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4443 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4444 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4445 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4451 fn exact_fee_liquidity_limit() {
4452 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4453 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4454 // we calculated fees on a higher value, resulting in us ignoring such paths.
4455 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4456 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4457 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4458 let payee = Payee::from_node_id(nodes[2]);
4460 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4462 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4463 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4464 short_channel_id: 2,
4467 cltv_expiry_delta: 0,
4468 htlc_minimum_msat: 0,
4469 htlc_maximum_msat: OptionalField::Present(85_000),
4471 fee_proportional_millionths: 0,
4472 excess_data: Vec::new()
4475 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4477 short_channel_id: 12,
4480 cltv_expiry_delta: (4 << 8) | 1,
4481 htlc_minimum_msat: 0,
4482 htlc_maximum_msat: OptionalField::Present(270_000),
4484 fee_proportional_millionths: 1000000,
4485 excess_data: Vec::new()
4489 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4490 // 200% fee charged channel 13 in the 1-to-2 direction.
4491 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4492 assert_eq!(route.paths.len(), 1);
4493 assert_eq!(route.paths[0].len(), 2);
4495 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4496 assert_eq!(route.paths[0][0].short_channel_id, 12);
4497 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4498 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4499 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4500 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4502 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4503 assert_eq!(route.paths[0][1].short_channel_id, 13);
4504 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4505 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4506 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4507 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4512 fn htlc_max_reduction_below_min() {
4513 // Test that if, while walking the graph, we reduce the value being sent to meet an
4514 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4515 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4516 // resulting in us thinking there is no possible path, even if other paths exist.
4517 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4518 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4519 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4520 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4522 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4523 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4524 // then try to send 90_000.
4525 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4527 short_channel_id: 2,
4530 cltv_expiry_delta: 0,
4531 htlc_minimum_msat: 0,
4532 htlc_maximum_msat: OptionalField::Present(80_000),
4534 fee_proportional_millionths: 0,
4535 excess_data: Vec::new()
4537 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4538 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4539 short_channel_id: 4,
4542 cltv_expiry_delta: (4 << 8) | 1,
4543 htlc_minimum_msat: 90_000,
4544 htlc_maximum_msat: OptionalField::Absent,
4546 fee_proportional_millionths: 0,
4547 excess_data: Vec::new()
4551 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4552 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4553 // expensive) channels 12-13 path.
4554 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4555 assert_eq!(route.paths.len(), 1);
4556 assert_eq!(route.paths[0].len(), 2);
4558 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4559 assert_eq!(route.paths[0][0].short_channel_id, 12);
4560 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4561 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4562 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4563 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4565 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4566 assert_eq!(route.paths[0][1].short_channel_id, 13);
4567 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4568 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4569 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4570 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4575 fn multiple_direct_first_hops() {
4576 // Previously we'd only ever considered one first hop path per counterparty.
4577 // However, as we don't restrict users to one channel per peer, we really need to support
4578 // looking at all first hop paths.
4579 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4580 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4581 // route over multiple channels with the same first hop.
4582 let secp_ctx = Secp256k1::new();
4583 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4584 let logger = Arc::new(test_utils::TestLogger::new());
4585 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4586 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4587 let payee = Payee::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4590 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4591 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4592 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4593 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4594 assert_eq!(route.paths.len(), 1);
4595 assert_eq!(route.paths[0].len(), 1);
4597 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4598 assert_eq!(route.paths[0][0].short_channel_id, 3);
4599 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4602 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4603 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4604 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4605 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4606 assert_eq!(route.paths.len(), 2);
4607 assert_eq!(route.paths[0].len(), 1);
4608 assert_eq!(route.paths[1].len(), 1);
4610 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4611 assert_eq!(route.paths[0][0].short_channel_id, 3);
4612 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4614 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4615 assert_eq!(route.paths[1][0].short_channel_id, 2);
4616 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4621 fn prefers_shorter_route_with_higher_fees() {
4622 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4623 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4624 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4626 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4627 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4628 let route = get_route(
4629 &our_id, &payee, &network_graph, None, 100, 42,
4630 Arc::clone(&logger), &scorer
4632 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4634 assert_eq!(route.get_total_fees(), 100);
4635 assert_eq!(route.get_total_amount(), 100);
4636 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4638 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4639 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4640 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4641 let route = get_route(
4642 &our_id, &payee, &network_graph, None, 100, 42,
4643 Arc::clone(&logger), &scorer
4645 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4647 assert_eq!(route.get_total_fees(), 300);
4648 assert_eq!(route.get_total_amount(), 100);
4649 assert_eq!(path, vec![2, 4, 7, 10]);
4652 struct BadChannelScorer {
4653 short_channel_id: u64,
4656 impl Score for BadChannelScorer {
4657 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId) -> u64 {
4658 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4661 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4664 struct BadNodeScorer {
4668 impl Score for BadNodeScorer {
4669 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, target: &NodeId) -> u64 {
4670 if *target == self.node_id { u64::max_value() } else { 0 }
4673 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4677 fn avoids_routing_through_bad_channels_and_nodes() {
4678 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4679 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4680 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4682 // A path to nodes[6] exists when no penalties are applied to any channel.
4683 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4684 let route = get_route(
4685 &our_id, &payee, &network_graph, None, 100, 42,
4686 Arc::clone(&logger), &scorer
4688 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4690 assert_eq!(route.get_total_fees(), 100);
4691 assert_eq!(route.get_total_amount(), 100);
4692 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4694 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4695 let scorer = BadChannelScorer { short_channel_id: 6 };
4696 let route = get_route(
4697 &our_id, &payee, &network_graph, None, 100, 42,
4698 Arc::clone(&logger), &scorer
4700 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4702 assert_eq!(route.get_total_fees(), 300);
4703 assert_eq!(route.get_total_amount(), 100);
4704 assert_eq!(path, vec![2, 4, 7, 10]);
4706 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4707 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4709 &our_id, &payee, &network_graph, None, 100, 42,
4710 Arc::clone(&logger), &scorer
4712 Err(LightningError { err, .. } ) => {
4713 assert_eq!(err, "Failed to find a path to the given destination");
4715 Ok(_) => panic!("Expected error"),
4720 fn total_fees_single_path() {
4724 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4725 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4726 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4729 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4730 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4731 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4734 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4735 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4736 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4742 assert_eq!(route.get_total_fees(), 250);
4743 assert_eq!(route.get_total_amount(), 225);
4747 fn total_fees_multi_path() {
4751 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4752 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4753 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4756 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4757 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4758 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4762 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4763 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4764 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4767 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4768 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4769 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4775 assert_eq!(route.get_total_fees(), 200);
4776 assert_eq!(route.get_total_amount(), 300);
4780 fn total_empty_route_no_panic() {
4781 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4782 // would both panic if the route was completely empty. We test to ensure they return 0
4783 // here, even though its somewhat nonsensical as a route.
4784 let route = Route { paths: Vec::new(), payee: None };
4786 assert_eq!(route.get_total_fees(), 0);
4787 assert_eq!(route.get_total_amount(), 0);
4790 #[cfg(not(feature = "no-std"))]
4791 pub(super) fn random_init_seed() -> u64 {
4792 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4793 use core::hash::{BuildHasher, Hasher};
4794 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4795 println!("Using seed of {}", seed);
4798 #[cfg(not(feature = "no-std"))]
4799 use util::ser::Readable;
4802 #[cfg(not(feature = "no-std"))]
4803 fn generate_routes() {
4804 let mut d = match super::test_utils::get_route_file() {
4811 let graph = NetworkGraph::read(&mut d).unwrap();
4812 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4814 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4815 let mut seed = random_init_seed() as usize;
4816 let nodes = graph.read_only().nodes().clone();
4817 'load_endpoints: for _ in 0..10 {
4819 seed = seed.overflowing_mul(0xdeadbeef).0;
4820 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4821 seed = seed.overflowing_mul(0xdeadbeef).0;
4822 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4823 let payee = Payee::from_node_id(dst);
4824 let amt = seed as u64 % 200_000_000;
4825 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4826 continue 'load_endpoints;
4833 #[cfg(not(feature = "no-std"))]
4834 fn generate_routes_mpp() {
4835 let mut d = match super::test_utils::get_route_file() {
4842 let graph = NetworkGraph::read(&mut d).unwrap();
4843 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4845 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4846 let mut seed = random_init_seed() as usize;
4847 let nodes = graph.read_only().nodes().clone();
4848 'load_endpoints: for _ in 0..10 {
4850 seed = seed.overflowing_mul(0xdeadbeef).0;
4851 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4852 seed = seed.overflowing_mul(0xdeadbeef).0;
4853 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4854 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4855 let amt = seed as u64 % 200_000_000;
4856 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4857 continue 'load_endpoints;
4864 #[cfg(all(test, not(feature = "no-std")))]
4865 pub(crate) mod test_utils {
4867 /// Tries to open a network graph file, or panics with a URL to fetch it.
4868 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4869 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4870 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4871 .or_else(|_| { // Fall back to guessing based on the binary location
4872 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4873 let mut path = std::env::current_exe().unwrap();
4874 path.pop(); // lightning-...
4876 path.pop(); // debug
4877 path.pop(); // target
4878 path.push("lightning");
4879 path.push("net_graph-2021-05-31.bin");
4880 eprintln!("{}", path.to_str().unwrap());
4883 .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");
4884 #[cfg(require_route_graph_test)]
4885 return Ok(res.unwrap());
4886 #[cfg(not(require_route_graph_test))]
4891 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4894 use routing::scoring::Scorer;
4895 use util::logger::{Logger, Record};
4899 struct DummyLogger {}
4900 impl Logger for DummyLogger {
4901 fn log(&self, _record: &Record) {}
4905 fn generate_routes(bench: &mut Bencher) {
4906 let mut d = test_utils::get_route_file().unwrap();
4907 let graph = NetworkGraph::read(&mut d).unwrap();
4908 let nodes = graph.read_only().nodes().clone();
4909 let scorer = Scorer::with_fixed_penalty(0);
4911 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4912 let mut path_endpoints = Vec::new();
4913 let mut seed: usize = 0xdeadbeef;
4914 'load_endpoints: for _ in 0..100 {
4917 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4919 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4920 let payee = Payee::from_node_id(dst);
4921 let amt = seed as u64 % 1_000_000;
4922 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4923 path_endpoints.push((src, dst, amt));
4924 continue 'load_endpoints;
4929 // ...then benchmark finding paths between the nodes we learned.
4932 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4933 let payee = Payee::from_node_id(dst);
4934 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4940 fn generate_mpp_routes(bench: &mut Bencher) {
4941 let mut d = test_utils::get_route_file().unwrap();
4942 let graph = NetworkGraph::read(&mut d).unwrap();
4943 let nodes = graph.read_only().nodes().clone();
4944 let scorer = Scorer::with_fixed_penalty(0);
4946 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4947 let mut path_endpoints = Vec::new();
4948 let mut seed: usize = 0xdeadbeef;
4949 'load_endpoints: for _ in 0..100 {
4952 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4954 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4955 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4956 let amt = seed as u64 % 1_000_000;
4957 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4958 path_endpoints.push((src, dst, amt));
4959 continue 'load_endpoints;
4964 // ...then benchmark finding paths between the nodes we learned.
4967 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4968 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4969 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());