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 util::ser::Writer;
1494 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1495 use bitcoin::hashes::Hash;
1496 use bitcoin::network::constants::Network;
1497 use bitcoin::blockdata::constants::genesis_block;
1498 use bitcoin::blockdata::script::Builder;
1499 use bitcoin::blockdata::opcodes;
1500 use bitcoin::blockdata::transaction::TxOut;
1504 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1505 use bitcoin::secp256k1::{Secp256k1, All};
1508 use sync::{self, Arc};
1510 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1511 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1512 channelmanager::ChannelDetails {
1513 channel_id: [0; 32],
1514 counterparty: channelmanager::ChannelCounterparty {
1517 unspendable_punishment_reserve: 0,
1518 forwarding_info: None,
1520 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1522 channel_value_satoshis: 0,
1524 outbound_capacity_msat,
1525 inbound_capacity_msat: 42,
1526 unspendable_punishment_reserve: None,
1527 confirmations_required: None,
1528 force_close_spend_delay: None,
1529 is_outbound: true, is_funding_locked: true,
1530 is_usable: true, is_public: true,
1534 // Using the same keys for LN and BTC ids
1536 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1537 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1539 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1540 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1542 let unsigned_announcement = UnsignedChannelAnnouncement {
1544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1548 bitcoin_key_1: node_id_1,
1549 bitcoin_key_2: node_id_2,
1550 excess_data: Vec::new(),
1553 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1554 let valid_announcement = ChannelAnnouncement {
1555 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1556 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1557 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1558 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1559 contents: unsigned_announcement.clone(),
1561 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1562 Ok(res) => assert!(res),
1568 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1569 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1571 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1572 let valid_channel_update = ChannelUpdate {
1573 signature: secp_ctx.sign(&msghash, node_privkey),
1574 contents: update.clone()
1577 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1578 Ok(res) => assert!(res),
1583 fn add_or_update_node(
1584 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1585 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1587 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1588 let unsigned_announcement = UnsignedNodeAnnouncement {
1594 addresses: Vec::new(),
1595 excess_address_data: Vec::new(),
1596 excess_data: Vec::new(),
1598 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1599 let valid_announcement = NodeAnnouncement {
1600 signature: secp_ctx.sign(&msghash, node_privkey),
1601 contents: unsigned_announcement.clone()
1604 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1610 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1611 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1612 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1615 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1617 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1618 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1620 (our_privkey, our_id, privkeys, pubkeys)
1623 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1624 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1625 // test for it later.
1626 let idx = (id - 1) * 2 + 1;
1628 vec![1 << (idx - 8*3), 0, 0, 0]
1629 } else if idx > 8*2 {
1630 vec![1 << (idx - 8*2), 0, 0]
1631 } else if idx > 8*1 {
1632 vec![1 << (idx - 8*1), 0]
1638 fn build_graph() -> (
1640 sync::Arc<NetworkGraph>,
1641 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1642 sync::Arc<test_utils::TestChainSource>,
1643 sync::Arc<test_utils::TestLogger>,
1645 let secp_ctx = Secp256k1::new();
1646 let logger = Arc::new(test_utils::TestLogger::new());
1647 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1648 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1649 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1650 // Build network from our_id to node6:
1652 // -1(1)2- node0 -1(3)2-
1654 // our_id -1(12)2- node7 -1(13)2--- node2
1656 // -1(2)2- node1 -1(4)2-
1659 // chan1 1-to-2: disabled
1660 // chan1 2-to-1: enabled, 0 fee
1662 // chan2 1-to-2: enabled, ignored fee
1663 // chan2 2-to-1: enabled, 0 fee
1665 // chan3 1-to-2: enabled, 0 fee
1666 // chan3 2-to-1: enabled, 100 msat fee
1668 // chan4 1-to-2: enabled, 100% fee
1669 // chan4 2-to-1: enabled, 0 fee
1671 // chan12 1-to-2: enabled, ignored fee
1672 // chan12 2-to-1: enabled, 0 fee
1674 // chan13 1-to-2: enabled, 200% fee
1675 // chan13 2-to-1: enabled, 0 fee
1678 // -1(5)2- node3 -1(8)2--
1682 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1684 // -1(7)2- node5 -1(10)2-
1686 // Channels 5, 8, 9 and 10 are private channels.
1688 // chan5 1-to-2: enabled, 100 msat fee
1689 // chan5 2-to-1: enabled, 0 fee
1691 // chan6 1-to-2: enabled, 0 fee
1692 // chan6 2-to-1: enabled, 0 fee
1694 // chan7 1-to-2: enabled, 100% fee
1695 // chan7 2-to-1: enabled, 0 fee
1697 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1698 // chan8 2-to-1: enabled, 0 fee
1700 // chan9 1-to-2: enabled, 1001 msat fee
1701 // chan9 2-to-1: enabled, 0 fee
1703 // chan10 1-to-2: enabled, 0 fee
1704 // chan10 2-to-1: enabled, 0 fee
1706 // chan11 1-to-2: enabled, 0 fee
1707 // chan11 2-to-1: enabled, 0 fee
1709 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1711 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1712 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1713 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1714 short_channel_id: 1,
1717 cltv_expiry_delta: 0,
1718 htlc_minimum_msat: 0,
1719 htlc_maximum_msat: OptionalField::Absent,
1721 fee_proportional_millionths: 0,
1722 excess_data: Vec::new()
1725 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1727 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1728 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1729 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1730 short_channel_id: 2,
1733 cltv_expiry_delta: u16::max_value(),
1734 htlc_minimum_msat: 0,
1735 htlc_maximum_msat: OptionalField::Absent,
1736 fee_base_msat: u32::max_value(),
1737 fee_proportional_millionths: u32::max_value(),
1738 excess_data: Vec::new()
1740 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1741 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1742 short_channel_id: 2,
1745 cltv_expiry_delta: 0,
1746 htlc_minimum_msat: 0,
1747 htlc_maximum_msat: OptionalField::Absent,
1749 fee_proportional_millionths: 0,
1750 excess_data: Vec::new()
1753 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1755 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1756 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1758 short_channel_id: 12,
1761 cltv_expiry_delta: u16::max_value(),
1762 htlc_minimum_msat: 0,
1763 htlc_maximum_msat: OptionalField::Absent,
1764 fee_base_msat: u32::max_value(),
1765 fee_proportional_millionths: u32::max_value(),
1766 excess_data: Vec::new()
1768 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1769 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1770 short_channel_id: 12,
1773 cltv_expiry_delta: 0,
1774 htlc_minimum_msat: 0,
1775 htlc_maximum_msat: OptionalField::Absent,
1777 fee_proportional_millionths: 0,
1778 excess_data: Vec::new()
1781 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1783 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1784 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1785 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1786 short_channel_id: 3,
1789 cltv_expiry_delta: (3 << 8) | 1,
1790 htlc_minimum_msat: 0,
1791 htlc_maximum_msat: OptionalField::Absent,
1793 fee_proportional_millionths: 0,
1794 excess_data: Vec::new()
1796 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1798 short_channel_id: 3,
1801 cltv_expiry_delta: (3 << 8) | 2,
1802 htlc_minimum_msat: 0,
1803 htlc_maximum_msat: OptionalField::Absent,
1805 fee_proportional_millionths: 0,
1806 excess_data: Vec::new()
1809 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1810 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1811 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1812 short_channel_id: 4,
1815 cltv_expiry_delta: (4 << 8) | 1,
1816 htlc_minimum_msat: 0,
1817 htlc_maximum_msat: OptionalField::Absent,
1819 fee_proportional_millionths: 1000000,
1820 excess_data: Vec::new()
1822 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1823 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1824 short_channel_id: 4,
1827 cltv_expiry_delta: (4 << 8) | 2,
1828 htlc_minimum_msat: 0,
1829 htlc_maximum_msat: OptionalField::Absent,
1831 fee_proportional_millionths: 0,
1832 excess_data: Vec::new()
1835 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1836 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1837 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1838 short_channel_id: 13,
1841 cltv_expiry_delta: (13 << 8) | 1,
1842 htlc_minimum_msat: 0,
1843 htlc_maximum_msat: OptionalField::Absent,
1845 fee_proportional_millionths: 2000000,
1846 excess_data: Vec::new()
1848 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1850 short_channel_id: 13,
1853 cltv_expiry_delta: (13 << 8) | 2,
1854 htlc_minimum_msat: 0,
1855 htlc_maximum_msat: OptionalField::Absent,
1857 fee_proportional_millionths: 0,
1858 excess_data: Vec::new()
1861 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1863 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1864 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1865 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1866 short_channel_id: 6,
1869 cltv_expiry_delta: (6 << 8) | 1,
1870 htlc_minimum_msat: 0,
1871 htlc_maximum_msat: OptionalField::Absent,
1873 fee_proportional_millionths: 0,
1874 excess_data: Vec::new()
1876 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1878 short_channel_id: 6,
1881 cltv_expiry_delta: (6 << 8) | 2,
1882 htlc_minimum_msat: 0,
1883 htlc_maximum_msat: OptionalField::Absent,
1885 fee_proportional_millionths: 0,
1886 excess_data: Vec::new(),
1889 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1890 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1892 short_channel_id: 11,
1895 cltv_expiry_delta: (11 << 8) | 1,
1896 htlc_minimum_msat: 0,
1897 htlc_maximum_msat: OptionalField::Absent,
1899 fee_proportional_millionths: 0,
1900 excess_data: Vec::new()
1902 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1904 short_channel_id: 11,
1907 cltv_expiry_delta: (11 << 8) | 2,
1908 htlc_minimum_msat: 0,
1909 htlc_maximum_msat: OptionalField::Absent,
1911 fee_proportional_millionths: 0,
1912 excess_data: Vec::new()
1915 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1917 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1919 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1920 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1921 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1922 short_channel_id: 7,
1925 cltv_expiry_delta: (7 << 8) | 1,
1926 htlc_minimum_msat: 0,
1927 htlc_maximum_msat: OptionalField::Absent,
1929 fee_proportional_millionths: 1000000,
1930 excess_data: Vec::new()
1932 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1933 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1934 short_channel_id: 7,
1937 cltv_expiry_delta: (7 << 8) | 2,
1938 htlc_minimum_msat: 0,
1939 htlc_maximum_msat: OptionalField::Absent,
1941 fee_proportional_millionths: 0,
1942 excess_data: Vec::new()
1945 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1947 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1951 fn simple_route_test() {
1952 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1953 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1954 let payee = Payee::from_node_id(nodes[2]);
1955 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1957 // Simple route to 2 via 1
1959 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
1960 assert_eq!(err, "Cannot send a payment of 0 msat");
1961 } else { panic!(); }
1963 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1964 assert_eq!(route.paths[0].len(), 2);
1966 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1967 assert_eq!(route.paths[0][0].short_channel_id, 2);
1968 assert_eq!(route.paths[0][0].fee_msat, 100);
1969 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1970 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1971 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1973 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1974 assert_eq!(route.paths[0][1].short_channel_id, 4);
1975 assert_eq!(route.paths[0][1].fee_msat, 100);
1976 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1977 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1978 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1982 fn invalid_first_hop_test() {
1983 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1984 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1985 let payee = Payee::from_node_id(nodes[2]);
1986 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1988 // Simple route to 2 via 1
1990 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1992 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) {
1993 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1994 } else { panic!(); }
1996 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1997 assert_eq!(route.paths[0].len(), 2);
2001 fn htlc_minimum_test() {
2002 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2003 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2004 let payee = Payee::from_node_id(nodes[2]);
2005 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2007 // Simple route to 2 via 1
2009 // Disable other paths
2010 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2012 short_channel_id: 12,
2014 flags: 2, // to disable
2015 cltv_expiry_delta: 0,
2016 htlc_minimum_msat: 0,
2017 htlc_maximum_msat: OptionalField::Absent,
2019 fee_proportional_millionths: 0,
2020 excess_data: Vec::new()
2022 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2024 short_channel_id: 3,
2026 flags: 2, // to disable
2027 cltv_expiry_delta: 0,
2028 htlc_minimum_msat: 0,
2029 htlc_maximum_msat: OptionalField::Absent,
2031 fee_proportional_millionths: 0,
2032 excess_data: Vec::new()
2034 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2036 short_channel_id: 13,
2038 flags: 2, // to disable
2039 cltv_expiry_delta: 0,
2040 htlc_minimum_msat: 0,
2041 htlc_maximum_msat: OptionalField::Absent,
2043 fee_proportional_millionths: 0,
2044 excess_data: Vec::new()
2046 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2048 short_channel_id: 6,
2050 flags: 2, // to disable
2051 cltv_expiry_delta: 0,
2052 htlc_minimum_msat: 0,
2053 htlc_maximum_msat: OptionalField::Absent,
2055 fee_proportional_millionths: 0,
2056 excess_data: Vec::new()
2058 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2059 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2060 short_channel_id: 7,
2062 flags: 2, // to disable
2063 cltv_expiry_delta: 0,
2064 htlc_minimum_msat: 0,
2065 htlc_maximum_msat: OptionalField::Absent,
2067 fee_proportional_millionths: 0,
2068 excess_data: Vec::new()
2071 // Check against amount_to_transfer_over_msat.
2072 // Set minimal HTLC of 200_000_000 msat.
2073 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2074 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2075 short_channel_id: 2,
2078 cltv_expiry_delta: 0,
2079 htlc_minimum_msat: 200_000_000,
2080 htlc_maximum_msat: OptionalField::Absent,
2082 fee_proportional_millionths: 0,
2083 excess_data: Vec::new()
2086 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2088 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2089 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2090 short_channel_id: 4,
2093 cltv_expiry_delta: 0,
2094 htlc_minimum_msat: 0,
2095 htlc_maximum_msat: OptionalField::Present(199_999_999),
2097 fee_proportional_millionths: 0,
2098 excess_data: Vec::new()
2101 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2102 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2103 assert_eq!(err, "Failed to find a path to the given destination");
2104 } else { panic!(); }
2106 // Lift the restriction on the first hop.
2107 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2108 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2109 short_channel_id: 2,
2112 cltv_expiry_delta: 0,
2113 htlc_minimum_msat: 0,
2114 htlc_maximum_msat: OptionalField::Absent,
2116 fee_proportional_millionths: 0,
2117 excess_data: Vec::new()
2120 // A payment above the minimum should pass
2121 let route = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2122 assert_eq!(route.paths[0].len(), 2);
2126 fn htlc_minimum_overpay_test() {
2127 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2128 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2129 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2130 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2132 // A route to node#2 via two paths.
2133 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2134 // Thus, they can't send 60 without overpaying.
2135 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2136 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2137 short_channel_id: 2,
2140 cltv_expiry_delta: 0,
2141 htlc_minimum_msat: 35_000,
2142 htlc_maximum_msat: OptionalField::Present(40_000),
2144 fee_proportional_millionths: 0,
2145 excess_data: Vec::new()
2147 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2148 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2149 short_channel_id: 12,
2152 cltv_expiry_delta: 0,
2153 htlc_minimum_msat: 35_000,
2154 htlc_maximum_msat: OptionalField::Present(40_000),
2156 fee_proportional_millionths: 0,
2157 excess_data: Vec::new()
2161 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2162 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2163 short_channel_id: 13,
2166 cltv_expiry_delta: 0,
2167 htlc_minimum_msat: 0,
2168 htlc_maximum_msat: OptionalField::Absent,
2170 fee_proportional_millionths: 0,
2171 excess_data: Vec::new()
2173 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2174 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2175 short_channel_id: 4,
2178 cltv_expiry_delta: 0,
2179 htlc_minimum_msat: 0,
2180 htlc_maximum_msat: OptionalField::Absent,
2182 fee_proportional_millionths: 0,
2183 excess_data: Vec::new()
2186 // Disable other paths
2187 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2188 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2189 short_channel_id: 1,
2191 flags: 2, // to disable
2192 cltv_expiry_delta: 0,
2193 htlc_minimum_msat: 0,
2194 htlc_maximum_msat: OptionalField::Absent,
2196 fee_proportional_millionths: 0,
2197 excess_data: Vec::new()
2200 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2201 // Overpay fees to hit htlc_minimum_msat.
2202 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2203 // TODO: this could be better balanced to overpay 10k and not 15k.
2204 assert_eq!(overpaid_fees, 15_000);
2206 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2207 // while taking even more fee to match htlc_minimum_msat.
2208 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210 short_channel_id: 12,
2213 cltv_expiry_delta: 0,
2214 htlc_minimum_msat: 65_000,
2215 htlc_maximum_msat: OptionalField::Present(80_000),
2217 fee_proportional_millionths: 0,
2218 excess_data: Vec::new()
2220 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2221 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2222 short_channel_id: 2,
2225 cltv_expiry_delta: 0,
2226 htlc_minimum_msat: 0,
2227 htlc_maximum_msat: OptionalField::Absent,
2229 fee_proportional_millionths: 0,
2230 excess_data: Vec::new()
2232 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2233 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2234 short_channel_id: 4,
2237 cltv_expiry_delta: 0,
2238 htlc_minimum_msat: 0,
2239 htlc_maximum_msat: OptionalField::Absent,
2241 fee_proportional_millionths: 100_000,
2242 excess_data: Vec::new()
2245 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2246 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2247 assert_eq!(route.paths.len(), 1);
2248 assert_eq!(route.paths[0][0].short_channel_id, 12);
2249 let fees = route.paths[0][0].fee_msat;
2250 assert_eq!(fees, 5_000);
2252 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2253 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2254 // the other channel.
2255 assert_eq!(route.paths.len(), 1);
2256 assert_eq!(route.paths[0][0].short_channel_id, 2);
2257 let fees = route.paths[0][0].fee_msat;
2258 assert_eq!(fees, 5_000);
2262 fn disable_channels_test() {
2263 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2264 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2265 let payee = Payee::from_node_id(nodes[2]);
2266 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2268 // // Disable channels 4 and 12 by flags=2
2269 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2270 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2271 short_channel_id: 4,
2273 flags: 2, // to disable
2274 cltv_expiry_delta: 0,
2275 htlc_minimum_msat: 0,
2276 htlc_maximum_msat: OptionalField::Absent,
2278 fee_proportional_millionths: 0,
2279 excess_data: Vec::new()
2281 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2282 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2283 short_channel_id: 12,
2285 flags: 2, // to disable
2286 cltv_expiry_delta: 0,
2287 htlc_minimum_msat: 0,
2288 htlc_maximum_msat: OptionalField::Absent,
2290 fee_proportional_millionths: 0,
2291 excess_data: Vec::new()
2294 // If all the channels require some features we don't understand, route should fail
2295 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2296 assert_eq!(err, "Failed to find a path to the given destination");
2297 } else { panic!(); }
2299 // If we specify a channel to node7, that overrides our local channel view and that gets used
2300 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2301 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2302 assert_eq!(route.paths[0].len(), 2);
2304 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2305 assert_eq!(route.paths[0][0].short_channel_id, 42);
2306 assert_eq!(route.paths[0][0].fee_msat, 200);
2307 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2308 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2309 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2311 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2312 assert_eq!(route.paths[0][1].short_channel_id, 13);
2313 assert_eq!(route.paths[0][1].fee_msat, 100);
2314 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2315 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2316 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2320 fn disable_node_test() {
2321 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2322 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2323 let payee = Payee::from_node_id(nodes[2]);
2324 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2326 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2327 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2328 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2329 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2330 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2332 // If all nodes require some features we don't understand, route should fail
2333 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2334 assert_eq!(err, "Failed to find a path to the given destination");
2335 } else { panic!(); }
2337 // If we specify a channel to node7, that overrides our local channel view and that gets used
2338 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2339 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2340 assert_eq!(route.paths[0].len(), 2);
2342 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2343 assert_eq!(route.paths[0][0].short_channel_id, 42);
2344 assert_eq!(route.paths[0][0].fee_msat, 200);
2345 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2346 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2347 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2349 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2350 assert_eq!(route.paths[0][1].short_channel_id, 13);
2351 assert_eq!(route.paths[0][1].fee_msat, 100);
2352 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2353 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2354 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2356 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2357 // naively) assume that the user checked the feature bits on the invoice, which override
2358 // the node_announcement.
2362 fn our_chans_test() {
2363 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2364 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2365 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2367 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2368 let payee = Payee::from_node_id(nodes[0]);
2369 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2370 assert_eq!(route.paths[0].len(), 3);
2372 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2373 assert_eq!(route.paths[0][0].short_channel_id, 2);
2374 assert_eq!(route.paths[0][0].fee_msat, 200);
2375 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2376 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2377 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2379 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2380 assert_eq!(route.paths[0][1].short_channel_id, 4);
2381 assert_eq!(route.paths[0][1].fee_msat, 100);
2382 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2383 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2384 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2386 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2387 assert_eq!(route.paths[0][2].short_channel_id, 3);
2388 assert_eq!(route.paths[0][2].fee_msat, 100);
2389 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2390 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2391 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2393 // If we specify a channel to node7, that overrides our local channel view and that gets used
2394 let payee = Payee::from_node_id(nodes[2]);
2395 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2396 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2397 assert_eq!(route.paths[0].len(), 2);
2399 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2400 assert_eq!(route.paths[0][0].short_channel_id, 42);
2401 assert_eq!(route.paths[0][0].fee_msat, 200);
2402 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2403 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2404 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2406 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2407 assert_eq!(route.paths[0][1].short_channel_id, 13);
2408 assert_eq!(route.paths[0][1].fee_msat, 100);
2409 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2410 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2411 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2414 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2415 let zero_fees = RoutingFees {
2417 proportional_millionths: 0,
2419 vec![RouteHint(vec![RouteHintHop {
2420 src_node_id: nodes[3],
2421 short_channel_id: 8,
2423 cltv_expiry_delta: (8 << 8) | 1,
2424 htlc_minimum_msat: None,
2425 htlc_maximum_msat: None,
2427 ]), RouteHint(vec![RouteHintHop {
2428 src_node_id: nodes[4],
2429 short_channel_id: 9,
2432 proportional_millionths: 0,
2434 cltv_expiry_delta: (9 << 8) | 1,
2435 htlc_minimum_msat: None,
2436 htlc_maximum_msat: None,
2437 }]), RouteHint(vec![RouteHintHop {
2438 src_node_id: nodes[5],
2439 short_channel_id: 10,
2441 cltv_expiry_delta: (10 << 8) | 1,
2442 htlc_minimum_msat: None,
2443 htlc_maximum_msat: None,
2447 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2448 let zero_fees = RoutingFees {
2450 proportional_millionths: 0,
2452 vec![RouteHint(vec![RouteHintHop {
2453 src_node_id: nodes[2],
2454 short_channel_id: 5,
2457 proportional_millionths: 0,
2459 cltv_expiry_delta: (5 << 8) | 1,
2460 htlc_minimum_msat: None,
2461 htlc_maximum_msat: None,
2463 src_node_id: nodes[3],
2464 short_channel_id: 8,
2466 cltv_expiry_delta: (8 << 8) | 1,
2467 htlc_minimum_msat: None,
2468 htlc_maximum_msat: None,
2470 ]), RouteHint(vec![RouteHintHop {
2471 src_node_id: nodes[4],
2472 short_channel_id: 9,
2475 proportional_millionths: 0,
2477 cltv_expiry_delta: (9 << 8) | 1,
2478 htlc_minimum_msat: None,
2479 htlc_maximum_msat: None,
2480 }]), RouteHint(vec![RouteHintHop {
2481 src_node_id: nodes[5],
2482 short_channel_id: 10,
2484 cltv_expiry_delta: (10 << 8) | 1,
2485 htlc_minimum_msat: None,
2486 htlc_maximum_msat: None,
2491 fn partial_route_hint_test() {
2492 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2493 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2494 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2496 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2497 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2498 // RouteHint may be partially used by the algo to build the best path.
2500 // First check that last hop can't have its source as the payee.
2501 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2502 src_node_id: nodes[6],
2503 short_channel_id: 8,
2506 proportional_millionths: 0,
2508 cltv_expiry_delta: (8 << 8) | 1,
2509 htlc_minimum_msat: None,
2510 htlc_maximum_msat: None,
2513 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2514 invalid_last_hops.push(invalid_last_hop);
2516 let payee = Payee::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2517 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2518 assert_eq!(err, "Route hint cannot have the payee as the source.");
2519 } else { panic!(); }
2522 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2523 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2524 assert_eq!(route.paths[0].len(), 5);
2526 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2527 assert_eq!(route.paths[0][0].short_channel_id, 2);
2528 assert_eq!(route.paths[0][0].fee_msat, 100);
2529 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2530 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2531 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2533 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2534 assert_eq!(route.paths[0][1].short_channel_id, 4);
2535 assert_eq!(route.paths[0][1].fee_msat, 0);
2536 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2537 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2538 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2540 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2541 assert_eq!(route.paths[0][2].short_channel_id, 6);
2542 assert_eq!(route.paths[0][2].fee_msat, 0);
2543 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2544 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2545 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2547 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2548 assert_eq!(route.paths[0][3].short_channel_id, 11);
2549 assert_eq!(route.paths[0][3].fee_msat, 0);
2550 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2551 // If we have a peer in the node map, we'll use their features here since we don't have
2552 // a way of figuring out their features from the invoice:
2553 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2554 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2556 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2557 assert_eq!(route.paths[0][4].short_channel_id, 8);
2558 assert_eq!(route.paths[0][4].fee_msat, 100);
2559 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2560 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2561 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2564 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2565 let zero_fees = RoutingFees {
2567 proportional_millionths: 0,
2569 vec![RouteHint(vec![RouteHintHop {
2570 src_node_id: nodes[3],
2571 short_channel_id: 8,
2573 cltv_expiry_delta: (8 << 8) | 1,
2574 htlc_minimum_msat: None,
2575 htlc_maximum_msat: None,
2576 }]), RouteHint(vec![
2578 ]), RouteHint(vec![RouteHintHop {
2579 src_node_id: nodes[5],
2580 short_channel_id: 10,
2582 cltv_expiry_delta: (10 << 8) | 1,
2583 htlc_minimum_msat: None,
2584 htlc_maximum_msat: None,
2589 fn ignores_empty_last_hops_test() {
2590 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2591 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2592 let payee = Payee::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2593 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2595 // Test handling of an empty RouteHint passed in Invoice.
2597 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2598 assert_eq!(route.paths[0].len(), 5);
2600 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2601 assert_eq!(route.paths[0][0].short_channel_id, 2);
2602 assert_eq!(route.paths[0][0].fee_msat, 100);
2603 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2604 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2605 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2607 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2608 assert_eq!(route.paths[0][1].short_channel_id, 4);
2609 assert_eq!(route.paths[0][1].fee_msat, 0);
2610 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2611 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2612 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2614 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2615 assert_eq!(route.paths[0][2].short_channel_id, 6);
2616 assert_eq!(route.paths[0][2].fee_msat, 0);
2617 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2618 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2619 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2621 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2622 assert_eq!(route.paths[0][3].short_channel_id, 11);
2623 assert_eq!(route.paths[0][3].fee_msat, 0);
2624 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2625 // If we have a peer in the node map, we'll use their features here since we don't have
2626 // a way of figuring out their features from the invoice:
2627 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2628 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2630 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2631 assert_eq!(route.paths[0][4].short_channel_id, 8);
2632 assert_eq!(route.paths[0][4].fee_msat, 100);
2633 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2634 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2635 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2638 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2639 let zero_fees = RoutingFees {
2641 proportional_millionths: 0,
2643 vec![RouteHint(vec![RouteHintHop {
2644 src_node_id: nodes[2],
2645 short_channel_id: 5,
2648 proportional_millionths: 0,
2650 cltv_expiry_delta: (5 << 8) | 1,
2651 htlc_minimum_msat: None,
2652 htlc_maximum_msat: None,
2654 src_node_id: nodes[3],
2655 short_channel_id: 8,
2657 cltv_expiry_delta: (8 << 8) | 1,
2658 htlc_minimum_msat: None,
2659 htlc_maximum_msat: None,
2660 }]), RouteHint(vec![RouteHintHop {
2661 src_node_id: nodes[5],
2662 short_channel_id: 10,
2664 cltv_expiry_delta: (10 << 8) | 1,
2665 htlc_minimum_msat: None,
2666 htlc_maximum_msat: None,
2671 fn multi_hint_last_hops_test() {
2672 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2673 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2674 let payee = Payee::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2675 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2676 // Test through channels 2, 3, 5, 8.
2677 // Test shows that multiple hop hints are considered.
2679 // Disabling channels 6 & 7 by flags=2
2680 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2681 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2682 short_channel_id: 6,
2684 flags: 2, // to disable
2685 cltv_expiry_delta: 0,
2686 htlc_minimum_msat: 0,
2687 htlc_maximum_msat: OptionalField::Absent,
2689 fee_proportional_millionths: 0,
2690 excess_data: Vec::new()
2692 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2693 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2694 short_channel_id: 7,
2696 flags: 2, // to disable
2697 cltv_expiry_delta: 0,
2698 htlc_minimum_msat: 0,
2699 htlc_maximum_msat: OptionalField::Absent,
2701 fee_proportional_millionths: 0,
2702 excess_data: Vec::new()
2705 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2706 assert_eq!(route.paths[0].len(), 4);
2708 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2709 assert_eq!(route.paths[0][0].short_channel_id, 2);
2710 assert_eq!(route.paths[0][0].fee_msat, 200);
2711 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2712 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2713 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2715 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2716 assert_eq!(route.paths[0][1].short_channel_id, 4);
2717 assert_eq!(route.paths[0][1].fee_msat, 100);
2718 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2719 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2720 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2722 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2723 assert_eq!(route.paths[0][2].short_channel_id, 5);
2724 assert_eq!(route.paths[0][2].fee_msat, 0);
2725 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2726 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2727 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2729 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2730 assert_eq!(route.paths[0][3].short_channel_id, 8);
2731 assert_eq!(route.paths[0][3].fee_msat, 100);
2732 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2733 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2734 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2737 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2738 let zero_fees = RoutingFees {
2740 proportional_millionths: 0,
2742 vec![RouteHint(vec![RouteHintHop {
2743 src_node_id: nodes[4],
2744 short_channel_id: 11,
2746 cltv_expiry_delta: (11 << 8) | 1,
2747 htlc_minimum_msat: None,
2748 htlc_maximum_msat: None,
2750 src_node_id: nodes[3],
2751 short_channel_id: 8,
2753 cltv_expiry_delta: (8 << 8) | 1,
2754 htlc_minimum_msat: None,
2755 htlc_maximum_msat: None,
2756 }]), RouteHint(vec![RouteHintHop {
2757 src_node_id: nodes[4],
2758 short_channel_id: 9,
2761 proportional_millionths: 0,
2763 cltv_expiry_delta: (9 << 8) | 1,
2764 htlc_minimum_msat: None,
2765 htlc_maximum_msat: None,
2766 }]), RouteHint(vec![RouteHintHop {
2767 src_node_id: nodes[5],
2768 short_channel_id: 10,
2770 cltv_expiry_delta: (10 << 8) | 1,
2771 htlc_minimum_msat: None,
2772 htlc_maximum_msat: None,
2777 fn last_hops_with_public_channel_test() {
2778 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2779 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2780 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2781 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2782 // This test shows that public routes can be present in the invoice
2783 // which would be handled in the same manner.
2785 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2786 assert_eq!(route.paths[0].len(), 5);
2788 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2789 assert_eq!(route.paths[0][0].short_channel_id, 2);
2790 assert_eq!(route.paths[0][0].fee_msat, 100);
2791 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2792 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2793 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2795 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2796 assert_eq!(route.paths[0][1].short_channel_id, 4);
2797 assert_eq!(route.paths[0][1].fee_msat, 0);
2798 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2799 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2800 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2802 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2803 assert_eq!(route.paths[0][2].short_channel_id, 6);
2804 assert_eq!(route.paths[0][2].fee_msat, 0);
2805 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2806 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2807 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2809 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2810 assert_eq!(route.paths[0][3].short_channel_id, 11);
2811 assert_eq!(route.paths[0][3].fee_msat, 0);
2812 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2813 // If we have a peer in the node map, we'll use their features here since we don't have
2814 // a way of figuring out their features from the invoice:
2815 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2816 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2818 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2819 assert_eq!(route.paths[0][4].short_channel_id, 8);
2820 assert_eq!(route.paths[0][4].fee_msat, 100);
2821 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2822 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2823 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2827 fn our_chans_last_hop_connect_test() {
2828 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2829 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2830 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2832 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2833 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2834 let mut last_hops = last_hops(&nodes);
2835 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2836 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2837 assert_eq!(route.paths[0].len(), 2);
2839 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2840 assert_eq!(route.paths[0][0].short_channel_id, 42);
2841 assert_eq!(route.paths[0][0].fee_msat, 0);
2842 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2843 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2844 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2846 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2847 assert_eq!(route.paths[0][1].short_channel_id, 8);
2848 assert_eq!(route.paths[0][1].fee_msat, 100);
2849 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2850 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2851 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2853 last_hops[0].0[0].fees.base_msat = 1000;
2855 // Revert to via 6 as the fee on 8 goes up
2856 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops);
2857 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2858 assert_eq!(route.paths[0].len(), 4);
2860 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2861 assert_eq!(route.paths[0][0].short_channel_id, 2);
2862 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2863 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2864 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2865 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2867 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2868 assert_eq!(route.paths[0][1].short_channel_id, 4);
2869 assert_eq!(route.paths[0][1].fee_msat, 100);
2870 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2871 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2872 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2874 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2875 assert_eq!(route.paths[0][2].short_channel_id, 7);
2876 assert_eq!(route.paths[0][2].fee_msat, 0);
2877 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2878 // If we have a peer in the node map, we'll use their features here since we don't have
2879 // a way of figuring out their features from the invoice:
2880 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2881 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2883 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2884 assert_eq!(route.paths[0][3].short_channel_id, 10);
2885 assert_eq!(route.paths[0][3].fee_msat, 100);
2886 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2887 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2888 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2890 // ...but still use 8 for larger payments as 6 has a variable feerate
2891 let route = get_route(&our_id, &payee, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2892 assert_eq!(route.paths[0].len(), 5);
2894 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2895 assert_eq!(route.paths[0][0].short_channel_id, 2);
2896 assert_eq!(route.paths[0][0].fee_msat, 3000);
2897 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2898 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2899 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2901 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2902 assert_eq!(route.paths[0][1].short_channel_id, 4);
2903 assert_eq!(route.paths[0][1].fee_msat, 0);
2904 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2905 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2906 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2908 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2909 assert_eq!(route.paths[0][2].short_channel_id, 6);
2910 assert_eq!(route.paths[0][2].fee_msat, 0);
2911 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2912 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2913 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2915 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2916 assert_eq!(route.paths[0][3].short_channel_id, 11);
2917 assert_eq!(route.paths[0][3].fee_msat, 1000);
2918 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2919 // If we have a peer in the node map, we'll use their features here since we don't have
2920 // a way of figuring out their features from the invoice:
2921 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2922 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2924 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2925 assert_eq!(route.paths[0][4].short_channel_id, 8);
2926 assert_eq!(route.paths[0][4].fee_msat, 2000);
2927 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2928 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2929 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2932 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> {
2933 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2934 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2935 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2937 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2938 let last_hops = RouteHint(vec![RouteHintHop {
2939 src_node_id: middle_node_id,
2940 short_channel_id: 8,
2943 proportional_millionths: last_hop_fee_prop,
2945 cltv_expiry_delta: (8 << 8) | 1,
2946 htlc_minimum_msat: None,
2947 htlc_maximum_msat: last_hop_htlc_max,
2949 let payee = Payee::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
2950 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2951 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2952 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)
2956 fn unannounced_path_test() {
2957 // We should be able to send a payment to a destination without any help of a routing graph
2958 // if we have a channel with a common counterparty that appears in the first and last hop
2960 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2962 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2963 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2964 assert_eq!(route.paths[0].len(), 2);
2966 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2967 assert_eq!(route.paths[0][0].short_channel_id, 42);
2968 assert_eq!(route.paths[0][0].fee_msat, 1001);
2969 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2970 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2971 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2973 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2974 assert_eq!(route.paths[0][1].short_channel_id, 8);
2975 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2976 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2977 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2978 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2982 fn overflow_unannounced_path_test_liquidity_underflow() {
2983 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2984 // the last-hop had a fee which overflowed a u64, we'd panic.
2985 // This was due to us adding the first-hop from us unconditionally, causing us to think
2986 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2987 // In this test, we previously hit a subtraction underflow due to having less available
2988 // liquidity at the last hop than 0.
2989 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());
2993 fn overflow_unannounced_path_test_feerate_overflow() {
2994 // This tests for the same case as above, except instead of hitting a subtraction
2995 // underflow, we hit a case where the fee charged at a hop overflowed.
2996 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());
3000 fn available_amount_while_routing_test() {
3001 // Tests whether we choose the correct available channel amount while routing.
3003 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3004 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3005 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3006 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3008 // We will use a simple single-path route from
3009 // our node to node2 via node0: channels {1, 3}.
3011 // First disable all other paths.
3012 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3014 short_channel_id: 2,
3017 cltv_expiry_delta: 0,
3018 htlc_minimum_msat: 0,
3019 htlc_maximum_msat: OptionalField::Present(100_000),
3021 fee_proportional_millionths: 0,
3022 excess_data: Vec::new()
3024 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3026 short_channel_id: 12,
3029 cltv_expiry_delta: 0,
3030 htlc_minimum_msat: 0,
3031 htlc_maximum_msat: OptionalField::Present(100_000),
3033 fee_proportional_millionths: 0,
3034 excess_data: Vec::new()
3037 // Make the first channel (#1) very permissive,
3038 // and we will be testing all limits on the second channel.
3039 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3040 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3041 short_channel_id: 1,
3044 cltv_expiry_delta: 0,
3045 htlc_minimum_msat: 0,
3046 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3048 fee_proportional_millionths: 0,
3049 excess_data: Vec::new()
3052 // First, let's see if routing works if we have absolutely no idea about the available amount.
3053 // In this case, it should be set to 250_000 sats.
3054 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3055 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3056 short_channel_id: 3,
3059 cltv_expiry_delta: 0,
3060 htlc_minimum_msat: 0,
3061 htlc_maximum_msat: OptionalField::Absent,
3063 fee_proportional_millionths: 0,
3064 excess_data: Vec::new()
3068 // Attempt to route more than available results in a failure.
3069 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3070 &our_id, &payee, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3071 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3072 } else { panic!(); }
3076 // Now, attempt to route an exact amount we have should be fine.
3077 let route = get_route(&our_id, &payee, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3078 assert_eq!(route.paths.len(), 1);
3079 let path = route.paths.last().unwrap();
3080 assert_eq!(path.len(), 2);
3081 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3082 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3085 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3086 // Disable channel #1 and use another first hop.
3087 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3089 short_channel_id: 1,
3092 cltv_expiry_delta: 0,
3093 htlc_minimum_msat: 0,
3094 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3096 fee_proportional_millionths: 0,
3097 excess_data: Vec::new()
3100 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3101 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3104 // Attempt to route more than available results in a failure.
3105 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3106 &our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3107 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3108 } else { panic!(); }
3112 // Now, attempt to route an exact amount we have should be fine.
3113 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3114 assert_eq!(route.paths.len(), 1);
3115 let path = route.paths.last().unwrap();
3116 assert_eq!(path.len(), 2);
3117 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3118 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3121 // Enable channel #1 back.
3122 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3123 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3124 short_channel_id: 1,
3127 cltv_expiry_delta: 0,
3128 htlc_minimum_msat: 0,
3129 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3131 fee_proportional_millionths: 0,
3132 excess_data: Vec::new()
3136 // Now let's see if routing works if we know only htlc_maximum_msat.
3137 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3139 short_channel_id: 3,
3142 cltv_expiry_delta: 0,
3143 htlc_minimum_msat: 0,
3144 htlc_maximum_msat: OptionalField::Present(15_000),
3146 fee_proportional_millionths: 0,
3147 excess_data: Vec::new()
3151 // Attempt to route more than available results in a failure.
3152 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3153 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3154 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3155 } else { panic!(); }
3159 // Now, attempt to route an exact amount we have should be fine.
3160 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3161 assert_eq!(route.paths.len(), 1);
3162 let path = route.paths.last().unwrap();
3163 assert_eq!(path.len(), 2);
3164 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3165 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3168 // Now let's see if routing works if we know only capacity from the UTXO.
3170 // We can't change UTXO capacity on the fly, so we'll disable
3171 // the existing channel and add another one with the capacity we need.
3172 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3173 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3174 short_channel_id: 3,
3177 cltv_expiry_delta: 0,
3178 htlc_minimum_msat: 0,
3179 htlc_maximum_msat: OptionalField::Absent,
3181 fee_proportional_millionths: 0,
3182 excess_data: Vec::new()
3185 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3186 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3187 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3188 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3189 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3191 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3192 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3194 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3195 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3196 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3197 short_channel_id: 333,
3200 cltv_expiry_delta: (3 << 8) | 1,
3201 htlc_minimum_msat: 0,
3202 htlc_maximum_msat: OptionalField::Absent,
3204 fee_proportional_millionths: 0,
3205 excess_data: Vec::new()
3207 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3208 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3209 short_channel_id: 333,
3212 cltv_expiry_delta: (3 << 8) | 2,
3213 htlc_minimum_msat: 0,
3214 htlc_maximum_msat: OptionalField::Absent,
3216 fee_proportional_millionths: 0,
3217 excess_data: Vec::new()
3221 // Attempt to route more than available results in a failure.
3222 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3223 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3224 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3225 } else { panic!(); }
3229 // Now, attempt to route an exact amount we have should be fine.
3230 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3231 assert_eq!(route.paths.len(), 1);
3232 let path = route.paths.last().unwrap();
3233 assert_eq!(path.len(), 2);
3234 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3235 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3238 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3239 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3240 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3241 short_channel_id: 333,
3244 cltv_expiry_delta: 0,
3245 htlc_minimum_msat: 0,
3246 htlc_maximum_msat: OptionalField::Present(10_000),
3248 fee_proportional_millionths: 0,
3249 excess_data: Vec::new()
3253 // Attempt to route more than available results in a failure.
3254 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3255 &our_id, &payee, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3256 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3257 } else { panic!(); }
3261 // Now, attempt to route an exact amount we have should be fine.
3262 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3263 assert_eq!(route.paths.len(), 1);
3264 let path = route.paths.last().unwrap();
3265 assert_eq!(path.len(), 2);
3266 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3267 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3272 fn available_liquidity_last_hop_test() {
3273 // Check that available liquidity properly limits the path even when only
3274 // one of the latter hops is limited.
3275 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3276 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3277 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3278 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3280 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3281 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3282 // Total capacity: 50 sats.
3284 // Disable other potential paths.
3285 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3286 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3287 short_channel_id: 2,
3290 cltv_expiry_delta: 0,
3291 htlc_minimum_msat: 0,
3292 htlc_maximum_msat: OptionalField::Present(100_000),
3294 fee_proportional_millionths: 0,
3295 excess_data: Vec::new()
3297 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3298 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3299 short_channel_id: 7,
3302 cltv_expiry_delta: 0,
3303 htlc_minimum_msat: 0,
3304 htlc_maximum_msat: OptionalField::Present(100_000),
3306 fee_proportional_millionths: 0,
3307 excess_data: Vec::new()
3312 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3313 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3314 short_channel_id: 12,
3317 cltv_expiry_delta: 0,
3318 htlc_minimum_msat: 0,
3319 htlc_maximum_msat: OptionalField::Present(100_000),
3321 fee_proportional_millionths: 0,
3322 excess_data: Vec::new()
3324 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3325 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3326 short_channel_id: 13,
3329 cltv_expiry_delta: 0,
3330 htlc_minimum_msat: 0,
3331 htlc_maximum_msat: OptionalField::Present(100_000),
3333 fee_proportional_millionths: 0,
3334 excess_data: Vec::new()
3337 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3338 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3339 short_channel_id: 6,
3342 cltv_expiry_delta: 0,
3343 htlc_minimum_msat: 0,
3344 htlc_maximum_msat: OptionalField::Present(50_000),
3346 fee_proportional_millionths: 0,
3347 excess_data: Vec::new()
3349 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3351 short_channel_id: 11,
3354 cltv_expiry_delta: 0,
3355 htlc_minimum_msat: 0,
3356 htlc_maximum_msat: OptionalField::Present(100_000),
3358 fee_proportional_millionths: 0,
3359 excess_data: Vec::new()
3362 // Attempt to route more than available results in a failure.
3363 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3364 &our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3365 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3366 } else { panic!(); }
3370 // Now, attempt to route 49 sats (just a bit below the capacity).
3371 let route = get_route(&our_id, &payee, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3372 assert_eq!(route.paths.len(), 1);
3373 let mut total_amount_paid_msat = 0;
3374 for path in &route.paths {
3375 assert_eq!(path.len(), 4);
3376 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3377 total_amount_paid_msat += path.last().unwrap().fee_msat;
3379 assert_eq!(total_amount_paid_msat, 49_000);
3383 // Attempt to route an exact amount is also fine
3384 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3385 assert_eq!(route.paths.len(), 1);
3386 let mut total_amount_paid_msat = 0;
3387 for path in &route.paths {
3388 assert_eq!(path.len(), 4);
3389 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3390 total_amount_paid_msat += path.last().unwrap().fee_msat;
3392 assert_eq!(total_amount_paid_msat, 50_000);
3397 fn ignore_fee_first_hop_test() {
3398 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3399 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3400 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3401 let payee = Payee::from_node_id(nodes[2]);
3403 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3404 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3405 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3406 short_channel_id: 1,
3409 cltv_expiry_delta: 0,
3410 htlc_minimum_msat: 0,
3411 htlc_maximum_msat: OptionalField::Present(100_000),
3412 fee_base_msat: 1_000_000,
3413 fee_proportional_millionths: 0,
3414 excess_data: Vec::new()
3416 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3417 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3418 short_channel_id: 3,
3421 cltv_expiry_delta: 0,
3422 htlc_minimum_msat: 0,
3423 htlc_maximum_msat: OptionalField::Present(50_000),
3425 fee_proportional_millionths: 0,
3426 excess_data: Vec::new()
3430 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3431 assert_eq!(route.paths.len(), 1);
3432 let mut total_amount_paid_msat = 0;
3433 for path in &route.paths {
3434 assert_eq!(path.len(), 2);
3435 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3436 total_amount_paid_msat += path.last().unwrap().fee_msat;
3438 assert_eq!(total_amount_paid_msat, 50_000);
3443 fn simple_mpp_route_test() {
3444 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3445 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3446 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3447 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3449 // We need a route consisting of 3 paths:
3450 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3451 // To achieve this, the amount being transferred should be around
3452 // the total capacity of these 3 paths.
3454 // First, we set limits on these (previously unlimited) channels.
3455 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3457 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3458 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3459 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3460 short_channel_id: 1,
3463 cltv_expiry_delta: 0,
3464 htlc_minimum_msat: 0,
3465 htlc_maximum_msat: OptionalField::Present(100_000),
3467 fee_proportional_millionths: 0,
3468 excess_data: Vec::new()
3470 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3471 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3472 short_channel_id: 3,
3475 cltv_expiry_delta: 0,
3476 htlc_minimum_msat: 0,
3477 htlc_maximum_msat: OptionalField::Present(50_000),
3479 fee_proportional_millionths: 0,
3480 excess_data: Vec::new()
3483 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3484 // (total limit 60).
3485 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3486 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3487 short_channel_id: 12,
3490 cltv_expiry_delta: 0,
3491 htlc_minimum_msat: 0,
3492 htlc_maximum_msat: OptionalField::Present(60_000),
3494 fee_proportional_millionths: 0,
3495 excess_data: Vec::new()
3497 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3498 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3499 short_channel_id: 13,
3502 cltv_expiry_delta: 0,
3503 htlc_minimum_msat: 0,
3504 htlc_maximum_msat: OptionalField::Present(60_000),
3506 fee_proportional_millionths: 0,
3507 excess_data: Vec::new()
3510 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3511 // (total capacity 180 sats).
3512 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3514 short_channel_id: 2,
3517 cltv_expiry_delta: 0,
3518 htlc_minimum_msat: 0,
3519 htlc_maximum_msat: OptionalField::Present(200_000),
3521 fee_proportional_millionths: 0,
3522 excess_data: Vec::new()
3524 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3525 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3526 short_channel_id: 4,
3529 cltv_expiry_delta: 0,
3530 htlc_minimum_msat: 0,
3531 htlc_maximum_msat: OptionalField::Present(180_000),
3533 fee_proportional_millionths: 0,
3534 excess_data: Vec::new()
3538 // Attempt to route more than available results in a failure.
3539 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3540 &our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3541 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3542 } else { panic!(); }
3546 // Now, attempt to route 250 sats (just a bit below the capacity).
3547 // Our algorithm should provide us with these 3 paths.
3548 let route = get_route(&our_id, &payee, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3549 assert_eq!(route.paths.len(), 3);
3550 let mut total_amount_paid_msat = 0;
3551 for path in &route.paths {
3552 assert_eq!(path.len(), 2);
3553 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3554 total_amount_paid_msat += path.last().unwrap().fee_msat;
3556 assert_eq!(total_amount_paid_msat, 250_000);
3560 // Attempt to route an exact amount is also fine
3561 let route = get_route(&our_id, &payee, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3562 assert_eq!(route.paths.len(), 3);
3563 let mut total_amount_paid_msat = 0;
3564 for path in &route.paths {
3565 assert_eq!(path.len(), 2);
3566 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3567 total_amount_paid_msat += path.last().unwrap().fee_msat;
3569 assert_eq!(total_amount_paid_msat, 290_000);
3574 fn long_mpp_route_test() {
3575 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3576 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3577 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3578 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3580 // We need a route consisting of 3 paths:
3581 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3582 // Note that these paths overlap (channels 5, 12, 13).
3583 // We will route 300 sats.
3584 // Each path will have 100 sats capacity, those channels which
3585 // are used twice will have 200 sats capacity.
3587 // Disable other potential paths.
3588 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3589 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3590 short_channel_id: 2,
3593 cltv_expiry_delta: 0,
3594 htlc_minimum_msat: 0,
3595 htlc_maximum_msat: OptionalField::Present(100_000),
3597 fee_proportional_millionths: 0,
3598 excess_data: Vec::new()
3600 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3601 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3602 short_channel_id: 7,
3605 cltv_expiry_delta: 0,
3606 htlc_minimum_msat: 0,
3607 htlc_maximum_msat: OptionalField::Present(100_000),
3609 fee_proportional_millionths: 0,
3610 excess_data: Vec::new()
3613 // Path via {node0, node2} is channels {1, 3, 5}.
3614 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3616 short_channel_id: 1,
3619 cltv_expiry_delta: 0,
3620 htlc_minimum_msat: 0,
3621 htlc_maximum_msat: OptionalField::Present(100_000),
3623 fee_proportional_millionths: 0,
3624 excess_data: Vec::new()
3626 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3627 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3628 short_channel_id: 3,
3631 cltv_expiry_delta: 0,
3632 htlc_minimum_msat: 0,
3633 htlc_maximum_msat: OptionalField::Present(100_000),
3635 fee_proportional_millionths: 0,
3636 excess_data: Vec::new()
3639 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3640 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3641 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3642 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3643 short_channel_id: 5,
3646 cltv_expiry_delta: 0,
3647 htlc_minimum_msat: 0,
3648 htlc_maximum_msat: OptionalField::Present(200_000),
3650 fee_proportional_millionths: 0,
3651 excess_data: Vec::new()
3654 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3655 // Add 100 sats to the capacities of {12, 13}, because these channels
3656 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3657 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3658 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3659 short_channel_id: 12,
3662 cltv_expiry_delta: 0,
3663 htlc_minimum_msat: 0,
3664 htlc_maximum_msat: OptionalField::Present(200_000),
3666 fee_proportional_millionths: 0,
3667 excess_data: Vec::new()
3669 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3670 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3671 short_channel_id: 13,
3674 cltv_expiry_delta: 0,
3675 htlc_minimum_msat: 0,
3676 htlc_maximum_msat: OptionalField::Present(200_000),
3678 fee_proportional_millionths: 0,
3679 excess_data: Vec::new()
3682 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3684 short_channel_id: 6,
3687 cltv_expiry_delta: 0,
3688 htlc_minimum_msat: 0,
3689 htlc_maximum_msat: OptionalField::Present(100_000),
3691 fee_proportional_millionths: 0,
3692 excess_data: Vec::new()
3694 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3695 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3696 short_channel_id: 11,
3699 cltv_expiry_delta: 0,
3700 htlc_minimum_msat: 0,
3701 htlc_maximum_msat: OptionalField::Present(100_000),
3703 fee_proportional_millionths: 0,
3704 excess_data: Vec::new()
3707 // Path via {node7, node2} is channels {12, 13, 5}.
3708 // We already limited them to 200 sats (they are used twice for 100 sats).
3709 // Nothing to do here.
3712 // Attempt to route more than available results in a failure.
3713 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3714 &our_id, &payee, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3715 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3716 } else { panic!(); }
3720 // Now, attempt to route 300 sats (exact amount we can route).
3721 // Our algorithm should provide us with these 3 paths, 100 sats each.
3722 let route = get_route(&our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3723 assert_eq!(route.paths.len(), 3);
3725 let mut total_amount_paid_msat = 0;
3726 for path in &route.paths {
3727 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3728 total_amount_paid_msat += path.last().unwrap().fee_msat;
3730 assert_eq!(total_amount_paid_msat, 300_000);
3736 fn mpp_cheaper_route_test() {
3737 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3738 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3739 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3740 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3742 // This test checks that if we have two cheaper paths and one more expensive path,
3743 // so that liquidity-wise any 2 of 3 combination is sufficient,
3744 // two cheaper paths will be taken.
3745 // These paths have equal available liquidity.
3747 // We need a combination of 3 paths:
3748 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3749 // Note that these paths overlap (channels 5, 12, 13).
3750 // Each path will have 100 sats capacity, those channels which
3751 // are used twice will have 200 sats capacity.
3753 // Disable other potential paths.
3754 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3755 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3756 short_channel_id: 2,
3759 cltv_expiry_delta: 0,
3760 htlc_minimum_msat: 0,
3761 htlc_maximum_msat: OptionalField::Present(100_000),
3763 fee_proportional_millionths: 0,
3764 excess_data: Vec::new()
3766 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3767 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3768 short_channel_id: 7,
3771 cltv_expiry_delta: 0,
3772 htlc_minimum_msat: 0,
3773 htlc_maximum_msat: OptionalField::Present(100_000),
3775 fee_proportional_millionths: 0,
3776 excess_data: Vec::new()
3779 // Path via {node0, node2} is channels {1, 3, 5}.
3780 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3781 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3782 short_channel_id: 1,
3785 cltv_expiry_delta: 0,
3786 htlc_minimum_msat: 0,
3787 htlc_maximum_msat: OptionalField::Present(100_000),
3789 fee_proportional_millionths: 0,
3790 excess_data: Vec::new()
3792 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3793 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3794 short_channel_id: 3,
3797 cltv_expiry_delta: 0,
3798 htlc_minimum_msat: 0,
3799 htlc_maximum_msat: OptionalField::Present(100_000),
3801 fee_proportional_millionths: 0,
3802 excess_data: Vec::new()
3805 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3806 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3807 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3808 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3809 short_channel_id: 5,
3812 cltv_expiry_delta: 0,
3813 htlc_minimum_msat: 0,
3814 htlc_maximum_msat: OptionalField::Present(200_000),
3816 fee_proportional_millionths: 0,
3817 excess_data: Vec::new()
3820 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3821 // Add 100 sats to the capacities of {12, 13}, because these channels
3822 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3823 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3824 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3825 short_channel_id: 12,
3828 cltv_expiry_delta: 0,
3829 htlc_minimum_msat: 0,
3830 htlc_maximum_msat: OptionalField::Present(200_000),
3832 fee_proportional_millionths: 0,
3833 excess_data: Vec::new()
3835 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3836 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3837 short_channel_id: 13,
3840 cltv_expiry_delta: 0,
3841 htlc_minimum_msat: 0,
3842 htlc_maximum_msat: OptionalField::Present(200_000),
3844 fee_proportional_millionths: 0,
3845 excess_data: Vec::new()
3848 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3850 short_channel_id: 6,
3853 cltv_expiry_delta: 0,
3854 htlc_minimum_msat: 0,
3855 htlc_maximum_msat: OptionalField::Present(100_000),
3856 fee_base_msat: 1_000,
3857 fee_proportional_millionths: 0,
3858 excess_data: Vec::new()
3860 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3862 short_channel_id: 11,
3865 cltv_expiry_delta: 0,
3866 htlc_minimum_msat: 0,
3867 htlc_maximum_msat: OptionalField::Present(100_000),
3869 fee_proportional_millionths: 0,
3870 excess_data: Vec::new()
3873 // Path via {node7, node2} is channels {12, 13, 5}.
3874 // We already limited them to 200 sats (they are used twice for 100 sats).
3875 // Nothing to do here.
3878 // Now, attempt to route 180 sats.
3879 // Our algorithm should provide us with these 2 paths.
3880 let route = get_route(&our_id, &payee, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3881 assert_eq!(route.paths.len(), 2);
3883 let mut total_value_transferred_msat = 0;
3884 let mut total_paid_msat = 0;
3885 for path in &route.paths {
3886 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3887 total_value_transferred_msat += path.last().unwrap().fee_msat;
3889 total_paid_msat += hop.fee_msat;
3892 // If we paid fee, this would be higher.
3893 assert_eq!(total_value_transferred_msat, 180_000);
3894 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3895 assert_eq!(total_fees_paid, 0);
3900 fn fees_on_mpp_route_test() {
3901 // This test makes sure that MPP algorithm properly takes into account
3902 // fees charged on the channels, by making the fees impactful:
3903 // if the fee is not properly accounted for, the behavior is different.
3904 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3905 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3906 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3907 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3909 // We need a route consisting of 2 paths:
3910 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3911 // We will route 200 sats, Each path will have 100 sats capacity.
3913 // This test is not particularly stable: e.g.,
3914 // there's a way to route via {node0, node2, node4}.
3915 // It works while pathfinding is deterministic, but can be broken otherwise.
3916 // It's fine to ignore this concern for now.
3918 // Disable other potential paths.
3919 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3920 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3921 short_channel_id: 2,
3924 cltv_expiry_delta: 0,
3925 htlc_minimum_msat: 0,
3926 htlc_maximum_msat: OptionalField::Present(100_000),
3928 fee_proportional_millionths: 0,
3929 excess_data: Vec::new()
3932 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3933 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3934 short_channel_id: 7,
3937 cltv_expiry_delta: 0,
3938 htlc_minimum_msat: 0,
3939 htlc_maximum_msat: OptionalField::Present(100_000),
3941 fee_proportional_millionths: 0,
3942 excess_data: Vec::new()
3945 // Path via {node0, node2} is channels {1, 3, 5}.
3946 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3947 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3948 short_channel_id: 1,
3951 cltv_expiry_delta: 0,
3952 htlc_minimum_msat: 0,
3953 htlc_maximum_msat: OptionalField::Present(100_000),
3955 fee_proportional_millionths: 0,
3956 excess_data: Vec::new()
3958 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3959 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3960 short_channel_id: 3,
3963 cltv_expiry_delta: 0,
3964 htlc_minimum_msat: 0,
3965 htlc_maximum_msat: OptionalField::Present(100_000),
3967 fee_proportional_millionths: 0,
3968 excess_data: Vec::new()
3971 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3972 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3973 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3974 short_channel_id: 5,
3977 cltv_expiry_delta: 0,
3978 htlc_minimum_msat: 0,
3979 htlc_maximum_msat: OptionalField::Present(100_000),
3981 fee_proportional_millionths: 0,
3982 excess_data: Vec::new()
3985 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3986 // All channels should be 100 sats capacity. But for the fee experiment,
3987 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3988 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3989 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3990 // so no matter how large are other channels,
3991 // the whole path will be limited by 100 sats with just these 2 conditions:
3992 // - channel 12 capacity is 250 sats
3993 // - fee for channel 6 is 150 sats
3994 // Let's test this by enforcing these 2 conditions and removing other limits.
3995 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3996 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3997 short_channel_id: 12,
4000 cltv_expiry_delta: 0,
4001 htlc_minimum_msat: 0,
4002 htlc_maximum_msat: OptionalField::Present(250_000),
4004 fee_proportional_millionths: 0,
4005 excess_data: Vec::new()
4007 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4009 short_channel_id: 13,
4012 cltv_expiry_delta: 0,
4013 htlc_minimum_msat: 0,
4014 htlc_maximum_msat: OptionalField::Absent,
4016 fee_proportional_millionths: 0,
4017 excess_data: Vec::new()
4020 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4021 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4022 short_channel_id: 6,
4025 cltv_expiry_delta: 0,
4026 htlc_minimum_msat: 0,
4027 htlc_maximum_msat: OptionalField::Absent,
4028 fee_base_msat: 150_000,
4029 fee_proportional_millionths: 0,
4030 excess_data: Vec::new()
4032 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4033 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4034 short_channel_id: 11,
4037 cltv_expiry_delta: 0,
4038 htlc_minimum_msat: 0,
4039 htlc_maximum_msat: OptionalField::Absent,
4041 fee_proportional_millionths: 0,
4042 excess_data: Vec::new()
4046 // Attempt to route more than available results in a failure.
4047 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4048 &our_id, &payee, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4049 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4050 } else { panic!(); }
4054 // Now, attempt to route 200 sats (exact amount we can route).
4055 let route = get_route(&our_id, &payee, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4056 assert_eq!(route.paths.len(), 2);
4058 let mut total_amount_paid_msat = 0;
4059 for path in &route.paths {
4060 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4061 total_amount_paid_msat += path.last().unwrap().fee_msat;
4063 assert_eq!(total_amount_paid_msat, 200_000);
4064 assert_eq!(route.get_total_fees(), 150_000);
4069 fn mpp_with_last_hops() {
4070 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4071 // via a single last-hop route hint, we'd fail to route if we first collected routes
4072 // totaling close but not quite enough to fund the full payment.
4074 // This was because we considered last-hop hints to have exactly the sought payment amount
4075 // instead of the amount we were trying to collect, needlessly limiting our path searching
4076 // at the very first hop.
4078 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4079 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4080 // to only have the remaining to-collect amount in available liquidity.
4082 // This bug appeared in production in some specific channel configurations.
4083 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4084 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4085 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4086 let payee = Payee::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4087 .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4088 src_node_id: nodes[2],
4089 short_channel_id: 42,
4090 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4091 cltv_expiry_delta: 42,
4092 htlc_minimum_msat: None,
4093 htlc_maximum_msat: None,
4096 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4097 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4098 // would first use the no-fee route and then fail to find a path along the second route as
4099 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4100 // under 5% of our payment amount.
4101 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4102 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4103 short_channel_id: 1,
4106 cltv_expiry_delta: u16::max_value(),
4107 htlc_minimum_msat: 0,
4108 htlc_maximum_msat: OptionalField::Present(99_000),
4109 fee_base_msat: u32::max_value(),
4110 fee_proportional_millionths: u32::max_value(),
4111 excess_data: Vec::new()
4113 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4115 short_channel_id: 2,
4118 cltv_expiry_delta: u16::max_value(),
4119 htlc_minimum_msat: 0,
4120 htlc_maximum_msat: OptionalField::Present(99_000),
4121 fee_base_msat: u32::max_value(),
4122 fee_proportional_millionths: u32::max_value(),
4123 excess_data: Vec::new()
4125 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4127 short_channel_id: 4,
4130 cltv_expiry_delta: (4 << 8) | 1,
4131 htlc_minimum_msat: 0,
4132 htlc_maximum_msat: OptionalField::Absent,
4134 fee_proportional_millionths: 0,
4135 excess_data: Vec::new()
4137 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4139 short_channel_id: 13,
4141 flags: 0|2, // Channel disabled
4142 cltv_expiry_delta: (13 << 8) | 1,
4143 htlc_minimum_msat: 0,
4144 htlc_maximum_msat: OptionalField::Absent,
4146 fee_proportional_millionths: 2000000,
4147 excess_data: Vec::new()
4150 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4152 let route = get_route(&our_id, &payee, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4153 assert_eq!(route.paths.len(), 2);
4154 // Paths are somewhat randomly ordered, but:
4155 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4156 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4157 assert_eq!(route.paths[0][0].short_channel_id, 2);
4158 assert_eq!(route.paths[0][0].fee_msat, 1);
4159 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4160 assert_eq!(route.paths[1][0].short_channel_id, 1);
4161 assert_eq!(route.paths[1][0].fee_msat, 0);
4162 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4163 assert_eq!(route.get_total_fees(), 1);
4164 assert_eq!(route.get_total_amount(), 100_000);
4168 fn drop_lowest_channel_mpp_route_test() {
4169 // This test checks that low-capacity channel is dropped when after
4170 // path finding we realize that we found more capacity than we need.
4171 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4172 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4173 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4174 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4176 // We need a route consisting of 3 paths:
4177 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4179 // The first and the second paths should be sufficient, but the third should be
4180 // cheaper, so that we select it but drop later.
4182 // First, we set limits on these (previously unlimited) channels.
4183 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4185 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4186 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4187 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4188 short_channel_id: 1,
4191 cltv_expiry_delta: 0,
4192 htlc_minimum_msat: 0,
4193 htlc_maximum_msat: OptionalField::Present(100_000),
4195 fee_proportional_millionths: 0,
4196 excess_data: Vec::new()
4198 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4200 short_channel_id: 3,
4203 cltv_expiry_delta: 0,
4204 htlc_minimum_msat: 0,
4205 htlc_maximum_msat: OptionalField::Present(50_000),
4207 fee_proportional_millionths: 0,
4208 excess_data: Vec::new()
4211 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4212 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4213 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4214 short_channel_id: 12,
4217 cltv_expiry_delta: 0,
4218 htlc_minimum_msat: 0,
4219 htlc_maximum_msat: OptionalField::Present(60_000),
4221 fee_proportional_millionths: 0,
4222 excess_data: Vec::new()
4224 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4226 short_channel_id: 13,
4229 cltv_expiry_delta: 0,
4230 htlc_minimum_msat: 0,
4231 htlc_maximum_msat: OptionalField::Present(60_000),
4233 fee_proportional_millionths: 0,
4234 excess_data: Vec::new()
4237 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4238 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4239 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4240 short_channel_id: 2,
4243 cltv_expiry_delta: 0,
4244 htlc_minimum_msat: 0,
4245 htlc_maximum_msat: OptionalField::Present(20_000),
4247 fee_proportional_millionths: 0,
4248 excess_data: Vec::new()
4250 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4251 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4252 short_channel_id: 4,
4255 cltv_expiry_delta: 0,
4256 htlc_minimum_msat: 0,
4257 htlc_maximum_msat: OptionalField::Present(20_000),
4259 fee_proportional_millionths: 0,
4260 excess_data: Vec::new()
4264 // Attempt to route more than available results in a failure.
4265 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4266 &our_id, &payee, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4267 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4268 } else { panic!(); }
4272 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4273 // Our algorithm should provide us with these 3 paths.
4274 let route = get_route(&our_id, &payee, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4275 assert_eq!(route.paths.len(), 3);
4276 let mut total_amount_paid_msat = 0;
4277 for path in &route.paths {
4278 assert_eq!(path.len(), 2);
4279 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4280 total_amount_paid_msat += path.last().unwrap().fee_msat;
4282 assert_eq!(total_amount_paid_msat, 125_000);
4286 // Attempt to route without the last small cheap channel
4287 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4288 assert_eq!(route.paths.len(), 2);
4289 let mut total_amount_paid_msat = 0;
4290 for path in &route.paths {
4291 assert_eq!(path.len(), 2);
4292 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4293 total_amount_paid_msat += path.last().unwrap().fee_msat;
4295 assert_eq!(total_amount_paid_msat, 90_000);
4300 fn min_criteria_consistency() {
4301 // Test that we don't use an inconsistent metric between updating and walking nodes during
4302 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4303 // was updated with a different criterion from the heap sorting, resulting in loops in
4304 // calculated paths. We test for that specific case here.
4306 // We construct a network that looks like this:
4308 // node2 -1(3)2- node3
4312 // node1 -1(5)2- node4 -1(1)2- node6
4318 // We create a loop on the side of our real path - our destination is node 6, with a
4319 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4320 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4321 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4322 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4323 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4324 // "previous hop" being set to node 3, creating a loop in the path.
4325 let secp_ctx = Secp256k1::new();
4326 let logger = Arc::new(test_utils::TestLogger::new());
4327 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4328 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4329 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4330 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4331 let payee = Payee::from_node_id(nodes[6]);
4333 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4334 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4336 short_channel_id: 6,
4339 cltv_expiry_delta: (6 << 8) | 0,
4340 htlc_minimum_msat: 0,
4341 htlc_maximum_msat: OptionalField::Absent,
4343 fee_proportional_millionths: 0,
4344 excess_data: Vec::new()
4346 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4348 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4349 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4351 short_channel_id: 5,
4354 cltv_expiry_delta: (5 << 8) | 0,
4355 htlc_minimum_msat: 0,
4356 htlc_maximum_msat: OptionalField::Absent,
4358 fee_proportional_millionths: 0,
4359 excess_data: Vec::new()
4361 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4363 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4364 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4365 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4366 short_channel_id: 4,
4369 cltv_expiry_delta: (4 << 8) | 0,
4370 htlc_minimum_msat: 0,
4371 htlc_maximum_msat: OptionalField::Absent,
4373 fee_proportional_millionths: 0,
4374 excess_data: Vec::new()
4376 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4378 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4379 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4381 short_channel_id: 3,
4384 cltv_expiry_delta: (3 << 8) | 0,
4385 htlc_minimum_msat: 0,
4386 htlc_maximum_msat: OptionalField::Absent,
4388 fee_proportional_millionths: 0,
4389 excess_data: Vec::new()
4391 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4393 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4394 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4396 short_channel_id: 2,
4399 cltv_expiry_delta: (2 << 8) | 0,
4400 htlc_minimum_msat: 0,
4401 htlc_maximum_msat: OptionalField::Absent,
4403 fee_proportional_millionths: 0,
4404 excess_data: Vec::new()
4407 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4408 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4410 short_channel_id: 1,
4413 cltv_expiry_delta: (1 << 8) | 0,
4414 htlc_minimum_msat: 100,
4415 htlc_maximum_msat: OptionalField::Absent,
4417 fee_proportional_millionths: 0,
4418 excess_data: Vec::new()
4420 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4423 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4424 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4425 assert_eq!(route.paths.len(), 1);
4426 assert_eq!(route.paths[0].len(), 3);
4428 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4429 assert_eq!(route.paths[0][0].short_channel_id, 6);
4430 assert_eq!(route.paths[0][0].fee_msat, 100);
4431 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4432 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4433 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4435 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4436 assert_eq!(route.paths[0][1].short_channel_id, 5);
4437 assert_eq!(route.paths[0][1].fee_msat, 0);
4438 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4439 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4440 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4442 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4443 assert_eq!(route.paths[0][2].short_channel_id, 1);
4444 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4445 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4446 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4447 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4453 fn exact_fee_liquidity_limit() {
4454 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4455 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4456 // we calculated fees on a higher value, resulting in us ignoring such paths.
4457 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4458 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4459 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4460 let payee = Payee::from_node_id(nodes[2]);
4462 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4464 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4466 short_channel_id: 2,
4469 cltv_expiry_delta: 0,
4470 htlc_minimum_msat: 0,
4471 htlc_maximum_msat: OptionalField::Present(85_000),
4473 fee_proportional_millionths: 0,
4474 excess_data: Vec::new()
4477 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4478 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4479 short_channel_id: 12,
4482 cltv_expiry_delta: (4 << 8) | 1,
4483 htlc_minimum_msat: 0,
4484 htlc_maximum_msat: OptionalField::Present(270_000),
4486 fee_proportional_millionths: 1000000,
4487 excess_data: Vec::new()
4491 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4492 // 200% fee charged channel 13 in the 1-to-2 direction.
4493 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4494 assert_eq!(route.paths.len(), 1);
4495 assert_eq!(route.paths[0].len(), 2);
4497 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4498 assert_eq!(route.paths[0][0].short_channel_id, 12);
4499 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4500 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4501 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4502 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4504 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4505 assert_eq!(route.paths[0][1].short_channel_id, 13);
4506 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4507 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4508 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4509 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4514 fn htlc_max_reduction_below_min() {
4515 // Test that if, while walking the graph, we reduce the value being sent to meet an
4516 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4517 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4518 // resulting in us thinking there is no possible path, even if other paths exist.
4519 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4520 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4521 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4522 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4524 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4525 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4526 // then try to send 90_000.
4527 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4529 short_channel_id: 2,
4532 cltv_expiry_delta: 0,
4533 htlc_minimum_msat: 0,
4534 htlc_maximum_msat: OptionalField::Present(80_000),
4536 fee_proportional_millionths: 0,
4537 excess_data: Vec::new()
4539 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4540 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4541 short_channel_id: 4,
4544 cltv_expiry_delta: (4 << 8) | 1,
4545 htlc_minimum_msat: 90_000,
4546 htlc_maximum_msat: OptionalField::Absent,
4548 fee_proportional_millionths: 0,
4549 excess_data: Vec::new()
4553 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4554 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4555 // expensive) channels 12-13 path.
4556 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4557 assert_eq!(route.paths.len(), 1);
4558 assert_eq!(route.paths[0].len(), 2);
4560 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4561 assert_eq!(route.paths[0][0].short_channel_id, 12);
4562 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4563 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4564 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4565 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4567 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4568 assert_eq!(route.paths[0][1].short_channel_id, 13);
4569 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4570 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4571 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4572 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4577 fn multiple_direct_first_hops() {
4578 // Previously we'd only ever considered one first hop path per counterparty.
4579 // However, as we don't restrict users to one channel per peer, we really need to support
4580 // looking at all first hop paths.
4581 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4582 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4583 // route over multiple channels with the same first hop.
4584 let secp_ctx = Secp256k1::new();
4585 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4586 let logger = Arc::new(test_utils::TestLogger::new());
4587 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4588 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4589 let payee = Payee::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4592 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4593 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4594 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4595 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4596 assert_eq!(route.paths.len(), 1);
4597 assert_eq!(route.paths[0].len(), 1);
4599 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4600 assert_eq!(route.paths[0][0].short_channel_id, 3);
4601 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4604 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4605 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4606 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4607 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4608 assert_eq!(route.paths.len(), 2);
4609 assert_eq!(route.paths[0].len(), 1);
4610 assert_eq!(route.paths[1].len(), 1);
4612 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4613 assert_eq!(route.paths[0][0].short_channel_id, 3);
4614 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4616 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4617 assert_eq!(route.paths[1][0].short_channel_id, 2);
4618 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4623 fn prefers_shorter_route_with_higher_fees() {
4624 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4625 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4626 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4628 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4629 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4630 let route = get_route(
4631 &our_id, &payee, &network_graph, None, 100, 42,
4632 Arc::clone(&logger), &scorer
4634 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4636 assert_eq!(route.get_total_fees(), 100);
4637 assert_eq!(route.get_total_amount(), 100);
4638 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4640 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4641 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4642 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4643 let route = get_route(
4644 &our_id, &payee, &network_graph, None, 100, 42,
4645 Arc::clone(&logger), &scorer
4647 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4649 assert_eq!(route.get_total_fees(), 300);
4650 assert_eq!(route.get_total_amount(), 100);
4651 assert_eq!(path, vec![2, 4, 7, 10]);
4654 struct BadChannelScorer {
4655 short_channel_id: u64,
4659 impl Writeable for BadChannelScorer {
4660 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4662 impl Score for BadChannelScorer {
4663 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId) -> u64 {
4664 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4667 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4670 struct BadNodeScorer {
4675 impl Writeable for BadNodeScorer {
4676 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4679 impl Score for BadNodeScorer {
4680 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, target: &NodeId) -> u64 {
4681 if *target == self.node_id { u64::max_value() } else { 0 }
4684 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4688 fn avoids_routing_through_bad_channels_and_nodes() {
4689 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4690 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4691 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4693 // A path to nodes[6] exists when no penalties are applied to any channel.
4694 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4695 let route = get_route(
4696 &our_id, &payee, &network_graph, None, 100, 42,
4697 Arc::clone(&logger), &scorer
4699 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4701 assert_eq!(route.get_total_fees(), 100);
4702 assert_eq!(route.get_total_amount(), 100);
4703 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4705 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4706 let scorer = BadChannelScorer { short_channel_id: 6 };
4707 let route = get_route(
4708 &our_id, &payee, &network_graph, None, 100, 42,
4709 Arc::clone(&logger), &scorer
4711 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4713 assert_eq!(route.get_total_fees(), 300);
4714 assert_eq!(route.get_total_amount(), 100);
4715 assert_eq!(path, vec![2, 4, 7, 10]);
4717 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4718 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4720 &our_id, &payee, &network_graph, None, 100, 42,
4721 Arc::clone(&logger), &scorer
4723 Err(LightningError { err, .. } ) => {
4724 assert_eq!(err, "Failed to find a path to the given destination");
4726 Ok(_) => panic!("Expected error"),
4731 fn total_fees_single_path() {
4735 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4736 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4737 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4740 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4741 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4742 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4745 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4746 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4747 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4753 assert_eq!(route.get_total_fees(), 250);
4754 assert_eq!(route.get_total_amount(), 225);
4758 fn total_fees_multi_path() {
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
4773 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4774 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4775 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4778 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4779 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4780 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4786 assert_eq!(route.get_total_fees(), 200);
4787 assert_eq!(route.get_total_amount(), 300);
4791 fn total_empty_route_no_panic() {
4792 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4793 // would both panic if the route was completely empty. We test to ensure they return 0
4794 // here, even though its somewhat nonsensical as a route.
4795 let route = Route { paths: Vec::new(), payee: None };
4797 assert_eq!(route.get_total_fees(), 0);
4798 assert_eq!(route.get_total_amount(), 0);
4801 #[cfg(not(feature = "no-std"))]
4802 pub(super) fn random_init_seed() -> u64 {
4803 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4804 use core::hash::{BuildHasher, Hasher};
4805 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4806 println!("Using seed of {}", seed);
4809 #[cfg(not(feature = "no-std"))]
4810 use util::ser::Readable;
4813 #[cfg(not(feature = "no-std"))]
4814 fn generate_routes() {
4815 let mut d = match super::test_utils::get_route_file() {
4822 let graph = NetworkGraph::read(&mut d).unwrap();
4823 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4825 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4826 let mut seed = random_init_seed() as usize;
4827 let nodes = graph.read_only().nodes().clone();
4828 'load_endpoints: for _ in 0..10 {
4830 seed = seed.overflowing_mul(0xdeadbeef).0;
4831 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4832 seed = seed.overflowing_mul(0xdeadbeef).0;
4833 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4834 let payee = Payee::from_node_id(dst);
4835 let amt = seed as u64 % 200_000_000;
4836 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4837 continue 'load_endpoints;
4844 #[cfg(not(feature = "no-std"))]
4845 fn generate_routes_mpp() {
4846 let mut d = match super::test_utils::get_route_file() {
4853 let graph = NetworkGraph::read(&mut d).unwrap();
4854 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4856 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4857 let mut seed = random_init_seed() as usize;
4858 let nodes = graph.read_only().nodes().clone();
4859 'load_endpoints: for _ in 0..10 {
4861 seed = seed.overflowing_mul(0xdeadbeef).0;
4862 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4863 seed = seed.overflowing_mul(0xdeadbeef).0;
4864 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4865 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4866 let amt = seed as u64 % 200_000_000;
4867 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4868 continue 'load_endpoints;
4875 #[cfg(all(test, not(feature = "no-std")))]
4876 pub(crate) mod test_utils {
4878 /// Tries to open a network graph file, or panics with a URL to fetch it.
4879 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4880 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4881 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4882 .or_else(|_| { // Fall back to guessing based on the binary location
4883 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4884 let mut path = std::env::current_exe().unwrap();
4885 path.pop(); // lightning-...
4887 path.pop(); // debug
4888 path.pop(); // target
4889 path.push("lightning");
4890 path.push("net_graph-2021-05-31.bin");
4891 eprintln!("{}", path.to_str().unwrap());
4894 .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");
4895 #[cfg(require_route_graph_test)]
4896 return Ok(res.unwrap());
4897 #[cfg(not(require_route_graph_test))]
4902 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4905 use routing::scoring::Scorer;
4906 use util::logger::{Logger, Record};
4910 struct DummyLogger {}
4911 impl Logger for DummyLogger {
4912 fn log(&self, _record: &Record) {}
4916 fn generate_routes(bench: &mut Bencher) {
4917 let mut d = test_utils::get_route_file().unwrap();
4918 let graph = NetworkGraph::read(&mut d).unwrap();
4919 let nodes = graph.read_only().nodes().clone();
4920 let scorer = Scorer::with_fixed_penalty(0);
4922 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4923 let mut path_endpoints = Vec::new();
4924 let mut seed: usize = 0xdeadbeef;
4925 'load_endpoints: for _ in 0..100 {
4928 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4930 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4931 let payee = Payee::from_node_id(dst);
4932 let amt = seed as u64 % 1_000_000;
4933 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4934 path_endpoints.push((src, dst, amt));
4935 continue 'load_endpoints;
4940 // ...then benchmark finding paths between the nodes we learned.
4943 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4944 let payee = Payee::from_node_id(dst);
4945 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4951 fn generate_mpp_routes(bench: &mut Bencher) {
4952 let mut d = test_utils::get_route_file().unwrap();
4953 let graph = NetworkGraph::read(&mut d).unwrap();
4954 let nodes = graph.read_only().nodes().clone();
4955 let scorer = Scorer::with_fixed_penalty(0);
4957 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4958 let mut path_endpoints = Vec::new();
4959 let mut seed: usize = 0xdeadbeef;
4960 'load_endpoints: for _ in 0..100 {
4963 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4965 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4966 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4967 let amt = seed as u64 % 1_000_000;
4968 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4969 path_endpoints.push((src, dst, amt));
4970 continue 'load_endpoints;
4975 // ...then benchmark finding paths between the nodes we learned.
4978 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4979 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4980 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());