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};
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>,
82 /// Returns the total amount of fees paid on this [`Route`].
84 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
85 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
86 pub fn get_total_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 return self.paths.iter()
89 .flat_map(|path| path.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[]))
90 .map(|hop| &hop.fee_msat)
94 /// Returns the total amount paid on this [`Route`], excluding the fees.
95 pub fn get_total_amount(&self) -> u64 {
96 return self.paths.iter()
97 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
102 const SERIALIZATION_VERSION: u8 = 1;
103 const MIN_SERIALIZATION_VERSION: u8 = 1;
105 impl Writeable for Route {
106 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
107 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
108 (self.paths.len() as u64).write(writer)?;
109 for hops in self.paths.iter() {
110 (hops.len() as u8).write(writer)?;
111 for hop in hops.iter() {
115 write_tlv_fields!(writer, {
116 (1, self.payee, option),
122 impl Readable for Route {
123 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
124 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
125 let path_count: u64 = Readable::read(reader)?;
126 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
127 for _ in 0..path_count {
128 let hop_count: u8 = Readable::read(reader)?;
129 let mut hops = Vec::with_capacity(hop_count as usize);
130 for _ in 0..hop_count {
131 hops.push(Readable::read(reader)?);
135 let mut payee = None;
136 read_tlv_fields!(reader, {
139 Ok(Route { paths, payee })
143 /// Parameters needed to find a [`Route`] for paying a [`Payee`].
145 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
148 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
149 #[derive(Clone, Debug)]
150 pub struct RouteParameters {
151 /// The recipient of the failed payment path.
154 /// The amount in msats sent on the failed payment path.
155 pub final_value_msat: u64,
157 /// The CLTV on the final hop of the failed payment path.
158 pub final_cltv_expiry_delta: u32,
161 impl_writeable_tlv_based!(RouteParameters, {
162 (0, payee, required),
163 (2, final_value_msat, required),
164 (4, final_cltv_expiry_delta, required),
167 /// The recipient of a payment.
168 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
170 /// The node id of the payee.
171 pub pubkey: PublicKey,
173 /// Features supported by the payee.
175 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
176 /// does not contain any features.
178 /// [`for_keysend`]: Self::for_keysend
179 pub features: Option<InvoiceFeatures>,
181 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
182 pub route_hints: Vec<RouteHint>,
184 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
185 pub expiry_time: Option<u64>,
188 impl_writeable_tlv_based!(Payee, {
189 (0, pubkey, required),
190 (2, features, option),
191 (4, route_hints, vec_type),
192 (6, expiry_time, option),
196 /// Creates a payee with the node id of the given `pubkey`.
197 pub fn new(pubkey: PublicKey) -> Self {
206 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
207 pub fn for_keysend(pubkey: PublicKey) -> Self {
208 Self::new(pubkey).with_features(InvoiceFeatures::for_keysend())
211 /// Includes the payee's features.
213 /// (C-not exported) since bindings don't support move semantics
214 pub fn with_features(self, features: InvoiceFeatures) -> Self {
215 Self { features: Some(features), ..self }
218 /// Includes hints for routing to the payee.
220 /// (C-not exported) since bindings don't support move semantics
221 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
222 Self { route_hints, ..self }
225 /// Includes a payment expiration in seconds relative to the UNIX epoch.
226 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
227 Self { expiry_time: Some(expiry_time), ..self }
231 /// A list of hops along a payment path terminating with a channel to the recipient.
232 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
233 pub struct RouteHint(pub Vec<RouteHintHop>);
236 impl Writeable for RouteHint {
237 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
238 (self.0.len() as u64).write(writer)?;
239 for hop in self.0.iter() {
246 impl Readable for RouteHint {
247 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
248 let hop_count: u64 = Readable::read(reader)?;
249 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
250 for _ in 0..hop_count {
251 hops.push(Readable::read(reader)?);
257 /// A channel descriptor for a hop along a payment path.
258 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
259 pub struct RouteHintHop {
260 /// The node_id of the non-target end of the route
261 pub src_node_id: PublicKey,
262 /// The short_channel_id of this channel
263 pub short_channel_id: u64,
264 /// The fees which must be paid to use this channel
265 pub fees: RoutingFees,
266 /// The difference in CLTV values between this node and the next node.
267 pub cltv_expiry_delta: u16,
268 /// The minimum value, in msat, which must be relayed to the next hop.
269 pub htlc_minimum_msat: Option<u64>,
270 /// The maximum value in msat available for routing with a single HTLC.
271 pub htlc_maximum_msat: Option<u64>,
274 impl_writeable_tlv_based!(RouteHintHop, {
275 (0, src_node_id, required),
276 (1, htlc_minimum_msat, option),
277 (2, short_channel_id, required),
278 (3, htlc_maximum_msat, option),
280 (6, cltv_expiry_delta, required),
283 #[derive(Eq, PartialEq)]
284 struct RouteGraphNode {
286 lowest_fee_to_peer_through_node: u64,
287 lowest_fee_to_node: u64,
288 // The maximum value a yet-to-be-constructed payment path might flow through this node.
289 // This value is upper-bounded by us by:
290 // - how much is needed for a path being constructed
291 // - how much value can channels following this node (up to the destination) can contribute,
292 // considering their capacity and fees
293 value_contribution_msat: u64,
294 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
295 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
296 path_htlc_minimum_msat: u64,
297 /// All penalties incurred from this hop on the way to the destination, as calculated using
299 path_penalty_msat: u64,
302 impl cmp::Ord for RouteGraphNode {
303 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
304 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
305 .checked_add(other.path_penalty_msat)
306 .unwrap_or_else(|| u64::max_value());
307 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
308 .checked_add(self.path_penalty_msat)
309 .unwrap_or_else(|| u64::max_value());
310 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
314 impl cmp::PartialOrd for RouteGraphNode {
315 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
316 Some(self.cmp(other))
320 struct DummyDirectionalChannelInfo {
321 cltv_expiry_delta: u32,
322 htlc_minimum_msat: u64,
323 htlc_maximum_msat: Option<u64>,
327 /// It's useful to keep track of the hops associated with the fees required to use them,
328 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
329 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
330 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
331 #[derive(Clone, Debug)]
332 struct PathBuildingHop<'a> {
333 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
334 // Note that node_features is calculated separately after our initial graph walk.
336 short_channel_id: u64,
337 channel_features: &'a ChannelFeatures,
339 cltv_expiry_delta: u32,
341 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
342 src_lowest_inbound_fees: RoutingFees,
343 /// Fees of the channel used in this hop.
344 channel_fees: RoutingFees,
345 /// All the fees paid *after* this channel on the way to the destination
346 next_hops_fee_msat: u64,
347 /// Fee paid for the use of the current channel (see channel_fees).
348 /// The value will be actually deducted from the counterparty balance on the previous link.
349 hop_use_fee_msat: u64,
350 /// Used to compare channels when choosing the for routing.
351 /// Includes paying for the use of a hop and the following hops, as well as
352 /// an estimated cost of reaching this hop.
353 /// Might get stale when fees are recomputed. Primarily for internal use.
355 /// This is useful for update_value_and_recompute_fees to make sure
356 /// we don't fall below the minimum. Should not be updated manually and
357 /// generally should not be accessed.
358 htlc_minimum_msat: u64,
359 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
360 /// walk and may be invalid thereafter.
361 path_htlc_minimum_msat: u64,
362 /// All penalties incurred from this channel on the way to the destination, as calculated using
364 path_penalty_msat: u64,
365 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
366 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
367 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
368 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
369 /// avoid processing them again.
371 #[cfg(any(test, feature = "fuzztarget"))]
372 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
373 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
374 // value_contribution_msat, which requires tracking it here. See comments below where it is
375 // used for more info.
376 value_contribution_msat: u64,
379 // Instantiated with a list of hops with correct data in them collected during path finding,
380 // an instance of this struct should be further modified only via given methods.
382 struct PaymentPath<'a> {
383 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
386 impl<'a> PaymentPath<'a> {
387 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
388 fn get_value_msat(&self) -> u64 {
389 self.hops.last().unwrap().0.fee_msat
392 fn get_total_fee_paid_msat(&self) -> u64 {
393 if self.hops.len() < 1 {
397 // Can't use next_hops_fee_msat because it gets outdated.
398 for (i, (hop, _)) in self.hops.iter().enumerate() {
399 if i != self.hops.len() - 1 {
400 result += hop.fee_msat;
406 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
407 // to change fees may result in an inconsistency.
409 // Sometimes we call this function right after constructing a path which is inconsistent in
410 // that it the value being transferred has decreased while we were doing path finding, leading
411 // to the fees being paid not lining up with the actual limits.
413 // Note that this function is not aware of the available_liquidity limit, and thus does not
414 // support increasing the value being transferred.
415 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
416 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
418 let mut total_fee_paid_msat = 0 as u64;
419 for i in (0..self.hops.len()).rev() {
420 let last_hop = i == self.hops.len() - 1;
422 // For non-last-hop, this value will represent the fees paid on the current hop. It
423 // will consist of the fees for the use of the next hop, and extra fees to match
424 // htlc_minimum_msat of the current channel. Last hop is handled separately.
425 let mut cur_hop_fees_msat = 0;
427 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
430 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
431 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
432 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
433 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
434 // set it too high just to maliciously take more fees by exploiting this
435 // match htlc_minimum_msat logic.
436 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
437 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
438 // Note that there is a risk that *previous hops* (those closer to us, as we go
439 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
441 // This might make us end up with a broken route, although this should be super-rare
442 // in practice, both because of how healthy channels look like, and how we pick
443 // channels in add_entry.
444 // Also, this can't be exploited more heavily than *announce a free path and fail
446 cur_hop_transferred_amount_msat += extra_fees_msat;
447 total_fee_paid_msat += extra_fees_msat;
448 cur_hop_fees_msat += extra_fees_msat;
452 // Final hop is a special case: it usually has just value_msat (by design), but also
453 // it still could overpay for the htlc_minimum_msat.
454 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
456 // Propagate updated fees for the use of the channels to one hop back, where they
457 // will be actually paid (fee_msat). The last hop is handled above separately.
458 cur_hop.fee_msat = cur_hop_fees_msat;
461 // Fee for the use of the current hop which will be deducted on the previous hop.
462 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
463 // this channel is free for us.
465 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
466 cur_hop.hop_use_fee_msat = new_fee;
467 total_fee_paid_msat += new_fee;
469 // It should not be possible because this function is called only to reduce the
470 // value. In that case, compute_fee was already called with the same fees for
471 // larger amount and there was no overflow.
479 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
480 let proportional_fee_millions =
481 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
482 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
483 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
487 // This function may be (indirectly) called without any verification,
488 // with channel_fees provided by a caller. We should handle it gracefully.
493 /// Finds a route from us (payer) to the given target node (payee).
495 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
496 /// Without this, MPP will only be used if the payee's features are available in the network graph.
498 /// Private routing paths between a public node and the target may be included in `params.payee`.
500 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
501 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
502 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
504 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
505 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
506 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
510 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
511 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
516 /// Panics if first_hops contains channels without short_channel_ids;
517 /// [`ChannelManager::list_usable_channels`] will never include such channels.
519 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
520 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
521 pub fn find_route<L: Deref, S: routing::Score>(
522 our_node_pubkey: &PublicKey, params: &RouteParameters, network: &NetworkGraph,
523 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
524 ) -> Result<Route, LightningError>
525 where L::Target: Logger {
527 our_node_pubkey, ¶ms.payee, network, first_hops, params.final_value_msat,
528 params.final_cltv_expiry_delta, logger, scorer
532 pub(crate) fn get_route<L: Deref, S: routing::Score>(
533 our_node_pubkey: &PublicKey, payee: &Payee, network: &NetworkGraph,
534 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
535 logger: L, scorer: &S
536 ) -> Result<Route, LightningError>
537 where L::Target: Logger {
538 let payee_node_id = NodeId::from_pubkey(&payee.pubkey);
539 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
541 if payee_node_id == our_node_id {
542 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
545 if final_value_msat > MAX_VALUE_MSAT {
546 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
549 if final_value_msat == 0 {
550 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
553 for route in payee.route_hints.iter() {
554 for hop in &route.0 {
555 if hop.src_node_id == payee.pubkey {
556 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
561 // The general routing idea is the following:
562 // 1. Fill first/last hops communicated by the caller.
563 // 2. Attempt to construct a path from payer to payee for transferring
564 // any ~sufficient (described later) value.
565 // If succeed, remember which channels were used and how much liquidity they have available,
566 // so that future paths don't rely on the same liquidity.
567 // 3. Prooceed to the next step if:
568 // - we hit the recommended target value;
569 // - OR if we could not construct a new path. Any next attempt will fail too.
570 // Otherwise, repeat step 2.
571 // 4. See if we managed to collect paths which aggregately are able to transfer target value
572 // (not recommended value). If yes, proceed. If not, fail routing.
573 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
574 // 6. Of all the found paths, select only those with the lowest total fee.
575 // 7. The last path in every selected route is likely to be more than we need.
576 // Reduce its value-to-transfer and recompute fees.
577 // 8. Choose the best route by the lowest total fee.
579 // As for the actual search algorithm,
580 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
581 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
583 // We are not a faithful Dijkstra's implementation because we can change values which impact
584 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
585 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
586 // the value we are currently attempting to send over a path, we simply reduce the value being
587 // sent along the path for any hops after that channel. This may imply that later fees (which
588 // we've already tabulated) are lower because a smaller value is passing through the channels
589 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
590 // channels which were selected earlier (and which may still be used for other paths without a
591 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
594 // One potentially problematic case for this algorithm would be if there are many
595 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
596 // graph walking), we may never find a path which is not liquidity-limited and has lower
597 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
598 // Because we only consider paths with at least 5% of the total value being sent, the damage
599 // from such a case should be limited, however this could be further reduced in the future by
600 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
601 // limits for the purposes of fee calculation.
603 // Alternatively, we could store more detailed path information in the heap (targets, below)
604 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
605 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
606 // and practically (as we would need to store dynamically-allocated path information in heap
607 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
608 // results of such an algorithm would likely be biased towards lower-value paths.
610 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
611 // outside of our current search value, running a path search more times to gather candidate
612 // paths at different values. While this may be acceptable, further path searches may increase
613 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
614 // graph for candidate paths, calculating the maximum value which can realistically be sent at
615 // the same time, remaining generic across different payment values.
617 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
618 // to use as the A* heuristic beyond just the cost to get one node further than the current
621 let network_graph = network.read_only();
622 let network_channels = network_graph.channels();
623 let network_nodes = network_graph.nodes();
624 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
625 cltv_expiry_delta: 0,
626 htlc_minimum_msat: 0,
627 htlc_maximum_msat: None,
630 proportional_millionths: 0,
634 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
635 // it. If the payee supports it they're supposed to include it in the invoice, so that should
637 let allow_mpp = if let Some(features) = &payee.features {
638 features.supports_basic_mpp()
639 } else if let Some(node) = network_nodes.get(&payee_node_id) {
640 if let Some(node_info) = node.announcement_info.as_ref() {
641 node_info.features.supports_basic_mpp()
644 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
645 payee.pubkey, if allow_mpp { "with" } else { "without" });
648 // Prepare the data we'll use for payee-to-payer search by
649 // inserting first hops suggested by the caller as targets.
650 // Our search will then attempt to reach them while traversing from the payee node.
651 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
652 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
653 if let Some(hops) = first_hops {
655 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
656 if chan.counterparty.node_id == *our_node_pubkey {
657 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
659 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
660 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
662 if first_hop_targets.is_empty() {
663 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
667 let empty_channel_features = ChannelFeatures::empty();
669 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
670 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
671 // adding duplicate entries when we find a better path to a given node.
672 let mut targets = BinaryHeap::new();
674 // Map from node_id to information about the best current path to that node, including feerate
676 let mut dist = HashMap::with_capacity(network_nodes.len());
678 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
679 // indicating that we may wish to try again with a higher value, potentially paying to meet an
680 // htlc_minimum with extra fees while still finding a cheaper path.
681 let mut hit_minimum_limit;
683 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
684 // We start with a path_value of the exact amount we want, and if that generates a route we may
685 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
686 // amount we want in total across paths, selecting the best subset at the end.
687 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
688 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
689 let mut path_value_msat = final_value_msat;
691 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
692 // This map allows paths to be aware of the channel use by other paths in the same call.
693 // This would help to make a better path finding decisions and not "overbook" channels.
694 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
695 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
697 // Keeping track of how much value we already collected across other paths. Helps to decide:
698 // - how much a new path should be transferring (upper bound);
699 // - whether a channel should be disregarded because
700 // it's available liquidity is too small comparing to how much more we need to collect;
701 // - when we want to stop looking for new paths.
702 let mut already_collected_value_msat = 0;
704 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee.pubkey, our_node_pubkey, final_value_msat);
706 macro_rules! add_entry {
707 // Adds entry which goes from $src_node_id to $dest_node_id
708 // over the channel with id $chan_id with fees described in
709 // $directional_info.
710 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
711 // since that value has to be transferred over this channel.
712 // Returns whether this channel caused an update to `targets`.
713 ( $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,
714 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => { {
715 // We "return" whether we updated the path at the end, via this:
716 let mut did_add_update_path_to_src_node = false;
717 // Channels to self should not be used. This is more of belt-and-suspenders, because in
718 // practice these cases should be caught earlier:
719 // - for regular channels at channel announcement (TODO)
720 // - for first and last hops early in get_route
721 if $src_node_id != $dest_node_id.clone() {
722 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
723 let mut initial_liquidity_available_msat = None;
724 if let Some(capacity_sats) = $capacity_sats {
725 initial_liquidity_available_msat = Some(capacity_sats * 1000);
728 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
729 if let Some(available_msat) = initial_liquidity_available_msat {
730 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
732 initial_liquidity_available_msat = Some(htlc_maximum_msat);
736 match initial_liquidity_available_msat {
737 Some(available_msat) => available_msat,
738 // We assume channels with unknown balance have
739 // a capacity of 0.0025 BTC (or 250_000 sats).
740 None => 250_000 * 1000
744 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
745 // It may be misleading because we might later choose to reduce the value transferred
746 // over these channels, and the channel which was insufficient might become sufficient.
747 // Worst case: we drop a good channel here because it can't cover the high following
748 // fees caused by one expensive channel, but then this channel could have been used
749 // if the amount being transferred over this path is lower.
750 // We do this for now, but this is a subject for removal.
751 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
753 // Routing Fragmentation Mitigation heuristic:
755 // Routing fragmentation across many payment paths increases the overall routing
756 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
757 // Taking too many smaller paths also increases the chance of payment failure.
758 // Thus to avoid this effect, we require from our collected links to provide
759 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
761 // This requirement is currently 5% of the remaining-to-be-collected value.
762 // This means as we successfully advance in our collection,
763 // the absolute liquidity contribution is lowered,
764 // thus increasing the number of potential channels to be selected.
766 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
767 // or 100% if we're not allowed to do multipath payments.
768 let minimal_value_contribution_msat: u64 = if allow_mpp {
769 (recommended_value_msat - already_collected_value_msat + 19) / 20
773 // Verify the liquidity offered by this channel complies to the minimal contribution.
774 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
776 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
777 // Includes paying fees for the use of the following channels.
778 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
779 Some(result) => result,
780 // Can't overflow due to how the values were computed right above.
781 None => unreachable!(),
783 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
784 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
785 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
787 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
788 // bother considering this channel.
789 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
790 // be only reduced later (not increased), so this channel should just be skipped
791 // as not sufficient.
792 if !over_path_minimum_msat {
793 hit_minimum_limit = true;
794 } else if contributes_sufficient_value {
795 // Note that low contribution here (limited by available_liquidity_msat)
796 // might violate htlc_minimum_msat on the hops which are next along the
797 // payment path (upstream to the payee). To avoid that, we recompute path
798 // path fees knowing the final path contribution after constructing it.
799 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
800 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
801 .map(|fee_msat| cmp::max(fee_msat, $directional_info.htlc_minimum_msat))
802 .unwrap_or_else(|| u64::max_value());
803 let hm_entry = dist.entry($src_node_id);
804 let old_entry = hm_entry.or_insert_with(|| {
805 // If there was previously no known way to access
806 // the source node (recall it goes payee-to-payer) of $chan_id, first add
807 // a semi-dummy record just to compute the fees to reach the source node.
808 // This will affect our decision on selecting $chan_id
809 // as a way to reach the $dest_node_id.
810 let mut fee_base_msat = u32::max_value();
811 let mut fee_proportional_millionths = u32::max_value();
812 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
813 fee_base_msat = fees.base_msat;
814 fee_proportional_millionths = fees.proportional_millionths;
817 node_id: $dest_node_id.clone(),
819 channel_features: $chan_features,
821 cltv_expiry_delta: 0,
822 src_lowest_inbound_fees: RoutingFees {
823 base_msat: fee_base_msat,
824 proportional_millionths: fee_proportional_millionths,
826 channel_fees: $directional_info.fees,
827 next_hops_fee_msat: u64::max_value(),
828 hop_use_fee_msat: u64::max_value(),
829 total_fee_msat: u64::max_value(),
830 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
831 path_htlc_minimum_msat,
832 path_penalty_msat: u64::max_value(),
833 was_processed: false,
834 #[cfg(any(test, feature = "fuzztarget"))]
835 value_contribution_msat,
839 #[allow(unused_mut)] // We only use the mut in cfg(test)
840 let mut should_process = !old_entry.was_processed;
841 #[cfg(any(test, feature = "fuzztarget"))]
843 // In test/fuzzing builds, we do extra checks to make sure the skipping
844 // of already-seen nodes only happens in cases we expect (see below).
845 if !should_process { should_process = true; }
849 let mut hop_use_fee_msat = 0;
850 let mut total_fee_msat = $next_hops_fee_msat;
852 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
853 // will have the same effective-fee
854 if $src_node_id != our_node_id {
855 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
856 // max_value means we'll always fail
857 // the old_entry.total_fee_msat > total_fee_msat check
858 None => total_fee_msat = u64::max_value(),
860 hop_use_fee_msat = fee_msat;
861 total_fee_msat += hop_use_fee_msat;
862 // When calculating the lowest inbound fees to a node, we
863 // calculate fees here not based on the actual value we think
864 // will flow over this channel, but on the minimum value that
865 // we'll accept flowing over it. The minimum accepted value
866 // is a constant through each path collection run, ensuring
867 // consistent basis. Otherwise we may later find a
868 // different path to the source node that is more expensive,
869 // but which we consider to be cheaper because we are capacity
870 // constrained and the relative fee becomes lower.
871 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
872 .map(|a| a.checked_add(total_fee_msat)) {
877 total_fee_msat = u64::max_value();
884 let path_penalty_msat = $next_hops_path_penalty_msat
885 .checked_add(scorer.channel_penalty_msat($chan_id.clone(), &$src_node_id, &$dest_node_id))
886 .unwrap_or_else(|| u64::max_value());
887 let new_graph_node = RouteGraphNode {
888 node_id: $src_node_id,
889 lowest_fee_to_peer_through_node: total_fee_msat,
890 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
891 value_contribution_msat: value_contribution_msat,
892 path_htlc_minimum_msat,
896 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
897 // if this way is cheaper than the already known
898 // (considering the cost to "reach" this channel from the route destination,
899 // the cost of using this channel,
900 // and the cost of routing to the source node of this channel).
901 // Also, consider that htlc_minimum_msat_difference, because we might end up
902 // paying it. Consider the following exploit:
903 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
904 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
905 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
906 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
908 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
909 // but it may require additional tracking - we don't want to double-count
910 // the fees included in $next_hops_path_htlc_minimum_msat, but also
911 // can't use something that may decrease on future hops.
912 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
913 .checked_add(old_entry.path_penalty_msat)
914 .unwrap_or_else(|| u64::max_value());
915 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
916 .checked_add(path_penalty_msat)
917 .unwrap_or_else(|| u64::max_value());
919 if !old_entry.was_processed && new_cost < old_cost {
920 targets.push(new_graph_node);
921 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
922 old_entry.hop_use_fee_msat = hop_use_fee_msat;
923 old_entry.total_fee_msat = total_fee_msat;
924 old_entry.node_id = $dest_node_id.clone();
925 old_entry.short_channel_id = $chan_id.clone();
926 old_entry.channel_features = $chan_features;
927 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
928 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
929 old_entry.channel_fees = $directional_info.fees;
930 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
931 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
932 old_entry.path_penalty_msat = path_penalty_msat;
933 #[cfg(any(test, feature = "fuzztarget"))]
935 old_entry.value_contribution_msat = value_contribution_msat;
937 did_add_update_path_to_src_node = true;
938 } else if old_entry.was_processed && new_cost < old_cost {
939 #[cfg(any(test, feature = "fuzztarget"))]
941 // If we're skipping processing a node which was previously
942 // processed even though we found another path to it with a
943 // cheaper fee, check that it was because the second path we
944 // found (which we are processing now) has a lower value
945 // contribution due to an HTLC minimum limit.
947 // e.g. take a graph with two paths from node 1 to node 2, one
948 // through channel A, and one through channel B. Channel A and
949 // B are both in the to-process heap, with their scores set by
950 // a higher htlc_minimum than fee.
951 // Channel A is processed first, and the channels onwards from
952 // node 1 are added to the to-process heap. Thereafter, we pop
953 // Channel B off of the heap, note that it has a much more
954 // restrictive htlc_maximum_msat, and recalculate the fees for
955 // all of node 1's channels using the new, reduced, amount.
957 // This would be bogus - we'd be selecting a higher-fee path
958 // with a lower htlc_maximum_msat instead of the one we'd
959 // already decided to use.
960 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
962 value_contribution_msat + path_penalty_msat <
963 old_entry.value_contribution_msat + old_entry.path_penalty_msat
971 did_add_update_path_to_src_node
975 let empty_node_features = NodeFeatures::empty();
976 // Find ways (channels with destination) to reach a given node and store them
977 // in the corresponding data structures (routing graph etc).
978 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
979 // meaning how much will be paid in fees after this node (to the best of our knowledge).
980 // This data can later be helpful to optimize routing (pay lower fees).
981 macro_rules! add_entries_to_cheapest_to_target_node {
982 ( $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 ) => {
983 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
984 let was_processed = elem.was_processed;
985 elem.was_processed = true;
988 // Entries are added to dist in add_entry!() when there is a channel from a node.
989 // Because there are no channels from payee, it will not have a dist entry at this point.
990 // If we're processing any other node, it is always be the result of a channel from it.
991 assert_eq!($node_id, payee_node_id);
996 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
997 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
998 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);
1002 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1005 &empty_node_features
1008 if !features.requires_unknown_bits() {
1009 for chan_id in $node.channels.iter() {
1010 let chan = network_channels.get(chan_id).unwrap();
1011 if !chan.features.requires_unknown_bits() {
1012 if chan.node_one == $node_id {
1013 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
1014 if first_hops.is_none() || chan.node_two != our_node_id {
1015 if let Some(two_to_one) = chan.two_to_one.as_ref() {
1016 if two_to_one.enabled {
1017 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);
1022 if first_hops.is_none() || chan.node_one != our_node_id{
1023 if let Some(one_to_two) = chan.one_to_two.as_ref() {
1024 if one_to_two.enabled {
1025 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);
1037 let mut payment_paths = Vec::<PaymentPath>::new();
1039 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1040 'paths_collection: loop {
1041 // For every new path, start from scratch, except
1042 // bookkeeped_channels_liquidity_available_msat, which will improve
1043 // the further iterations of path finding. Also don't erase first_hop_targets.
1046 hit_minimum_limit = false;
1048 // If first hop is a private channel and the only way to reach the payee, this is the only
1049 // place where it could be added.
1050 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1051 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1052 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);
1053 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
1057 // Add the payee as a target, so that the payee-to-payer
1058 // search algorithm knows what to start with.
1059 match network_nodes.get(&payee_node_id) {
1060 // The payee is not in our network graph, so nothing to add here.
1061 // There is still a chance of reaching them via last_hops though,
1062 // so don't yet fail the payment here.
1063 // If not, targets.pop() will not even let us enter the loop in step 2.
1066 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64);
1071 // If a caller provided us with last hops, add them to routing targets. Since this happens
1072 // earlier than general path finding, they will be somewhat prioritized, although currently
1073 // it matters only if the fees are exactly the same.
1074 for route in payee.route_hints.iter().filter(|route| !route.0.is_empty()) {
1075 let first_hop_in_route = &(route.0)[0];
1076 let have_hop_src_in_graph =
1077 // Only add the hops in this route to our candidate set if either
1078 // we have a direct channel to the first hop or the first hop is
1079 // in the regular network graph.
1080 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1081 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1082 if have_hop_src_in_graph {
1083 // We start building the path from reverse, i.e., from payee
1084 // to the first RouteHintHop in the path.
1085 let hop_iter = route.0.iter().rev();
1086 let prev_hop_iter = core::iter::once(&payee.pubkey).chain(
1087 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1088 let mut hop_used = true;
1089 let mut aggregate_next_hops_fee_msat: u64 = 0;
1090 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1091 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1093 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1094 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
1095 // really sucks, cause we're gonna need that eventually.
1096 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
1098 let directional_info = DummyDirectionalChannelInfo {
1099 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
1100 htlc_minimum_msat: hop_htlc_minimum_msat,
1101 htlc_maximum_msat: hop.htlc_maximum_msat,
1105 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
1107 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
1108 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
1110 let src_node_id = NodeId::from_pubkey(&hop.src_node_id);
1111 let dest_node_id = NodeId::from_pubkey(&prev_hop_id);
1112 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1113 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, &src_node_id, &dest_node_id))
1114 .unwrap_or_else(|| u64::max_value());
1116 // We assume that the recipient only included route hints for routes which had
1117 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
1118 // invoices where the invoice does not specify value this may not be the case, but
1119 // better to include the hints than not.
1120 if !add_entry!(hop.short_channel_id, src_node_id, dest_node_id, directional_info, reqd_channel_cap, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat) {
1121 // If this hop was not used then there is no use checking the preceding hops
1122 // in the RouteHint. We can break by just searching for a direct channel between
1123 // last checked hop and first_hop_targets
1127 // Searching for a direct channel between last checked hop and first_hop_targets
1128 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1129 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1130 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);
1138 // In the next values of the iterator, the aggregate fees already reflects
1139 // the sum of value sent from payer (final_value_msat) and routing fees
1140 // for the last node in the RouteHint. We need to just add the fees to
1141 // route through the current node so that the preceeding node (next iteration)
1143 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1144 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1145 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1147 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1148 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1149 .checked_add(hop_htlc_minimum_msat_inc);
1150 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1152 if idx == route.0.len() - 1 {
1153 // The last hop in this iterator is the first hop in
1154 // overall RouteHint.
1155 // If this hop connects to a node with which we have a direct channel,
1156 // ignore the network graph and, if the last hop was added, add our
1157 // direct channel to the candidate set.
1159 // Note that we *must* check if the last hop was added as `add_entry`
1160 // always assumes that the third argument is a node to which we have a
1162 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1163 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1164 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);
1172 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1174 // At this point, targets are filled with the data from first and
1175 // last hops communicated by the caller, and the payment receiver.
1176 let mut found_new_path = false;
1179 // If this loop terminates due the exhaustion of targets, two situations are possible:
1180 // - not enough outgoing liquidity:
1181 // 0 < already_collected_value_msat < final_value_msat
1182 // - enough outgoing liquidity:
1183 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1184 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1185 // paths_collection will be stopped because found_new_path==false.
1186 // This is not necessarily a routing failure.
1187 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1189 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1190 // traversing the graph and arrange the path out of what we found.
1191 if node_id == our_node_id {
1192 let mut new_entry = dist.remove(&our_node_id).unwrap();
1193 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1196 let mut features_set = false;
1197 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1198 for (scid, _, _, ref features) in first_channels {
1199 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1200 ordered_hops.last_mut().unwrap().1 = features.clone();
1201 features_set = true;
1207 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1208 if let Some(node_info) = node.announcement_info.as_ref() {
1209 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1211 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1214 // We should be able to fill in features for everything except the last
1215 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1216 // should be able to extend it further as BOLT 11 does have feature
1217 // flags for the last hop node itself).
1218 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1222 // Means we succesfully traversed from the payer to the payee, now
1223 // save this path for the payment route. Also, update the liquidity
1224 // remaining on the used hops, so that we take them into account
1225 // while looking for more paths.
1226 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1230 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1231 Some(payment_hop) => payment_hop,
1232 // We can't arrive at None because, if we ever add an entry to targets,
1233 // we also fill in the entry in dist (see add_entry!).
1234 None => unreachable!(),
1236 // We "propagate" the fees one hop backward (topologically) here,
1237 // so that fees paid for a HTLC forwarding on the current channel are
1238 // associated with the previous channel (where they will be subtracted).
1239 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1240 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1241 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1243 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1244 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1245 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv_expiry_delta;
1247 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1248 ordered_hops.len(), value_contribution_msat, ordered_hops);
1250 let mut payment_path = PaymentPath {hops: ordered_hops};
1252 // We could have possibly constructed a slightly inconsistent path: since we reduce
1253 // value being transferred along the way, we could have violated htlc_minimum_msat
1254 // on some channels we already passed (assuming dest->source direction). Here, we
1255 // recompute the fees again, so that if that's the case, we match the currently
1256 // underpaid htlc_minimum_msat with fees.
1257 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1259 // Since a path allows to transfer as much value as
1260 // the smallest channel it has ("bottleneck"), we should recompute
1261 // the fees so sender HTLC don't overpay fees when traversing
1262 // larger channels than the bottleneck. This may happen because
1263 // when we were selecting those channels we were not aware how much value
1264 // this path will transfer, and the relative fee for them
1265 // might have been computed considering a larger value.
1266 // Remember that we used these channels so that we don't rely
1267 // on the same liquidity in future paths.
1268 let mut prevented_redundant_path_selection = false;
1269 for (payment_hop, _) in payment_path.hops.iter() {
1270 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1271 let mut spent_on_hop_msat = value_contribution_msat;
1272 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1273 spent_on_hop_msat += next_hops_fee_msat;
1274 if spent_on_hop_msat == *channel_liquidity_available_msat {
1275 // If this path used all of this channel's available liquidity, we know
1276 // this path will not be selected again in the next loop iteration.
1277 prevented_redundant_path_selection = true;
1279 *channel_liquidity_available_msat -= spent_on_hop_msat;
1281 if !prevented_redundant_path_selection {
1282 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1283 // we'll probably end up picking the same path again on the next iteration.
1284 // Decrease the available liquidity of a hop in the middle of the path.
1285 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1286 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1287 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1288 *victim_liquidity = 0;
1291 // Track the total amount all our collected paths allow to send so that we:
1292 // - know when to stop looking for more paths
1293 // - know which of the hops are useless considering how much more sats we need
1294 // (contributes_sufficient_value)
1295 already_collected_value_msat += value_contribution_msat;
1297 payment_paths.push(payment_path);
1298 found_new_path = true;
1299 break 'path_construction;
1302 // If we found a path back to the payee, we shouldn't try to process it again. This is
1303 // the equivalent of the `elem.was_processed` check in
1304 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1305 if node_id == payee_node_id { continue 'path_construction; }
1307 // Otherwise, since the current target node is not us,
1308 // keep "unrolling" the payment graph from payee to payer by
1309 // finding a way to reach the current target from the payer side.
1310 match network_nodes.get(&node_id) {
1313 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1319 // If we don't support MPP, no use trying to gather more value ever.
1320 break 'paths_collection;
1324 // Stop either when the recommended value is reached or if no new path was found in this
1326 // In the latter case, making another path finding attempt won't help,
1327 // because we deterministically terminated the search due to low liquidity.
1328 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1329 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1330 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1331 break 'paths_collection;
1332 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1333 // Further, if this was our first walk of the graph, and we weren't limited by an
1334 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1335 // limited by an htlc_minimum_msat value, find another path with a higher value,
1336 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1337 // still keeping a lower total fee than this path.
1338 if !hit_minimum_limit {
1339 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1340 break 'paths_collection;
1342 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1343 path_value_msat = recommended_value_msat;
1348 if payment_paths.len() == 0 {
1349 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1352 if already_collected_value_msat < final_value_msat {
1353 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1356 // Sort by total fees and take the best paths.
1357 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1358 if payment_paths.len() > 50 {
1359 payment_paths.truncate(50);
1362 // Draw multiple sufficient routes by randomly combining the selected paths.
1363 let mut drawn_routes = Vec::new();
1364 for i in 0..payment_paths.len() {
1365 let mut cur_route = Vec::<PaymentPath>::new();
1366 let mut aggregate_route_value_msat = 0;
1369 // TODO: real random shuffle
1370 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1371 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1374 for payment_path in cur_payment_paths {
1375 cur_route.push(payment_path.clone());
1376 aggregate_route_value_msat += payment_path.get_value_msat();
1377 if aggregate_route_value_msat > final_value_msat {
1378 // Last path likely overpaid. Substract it from the most expensive
1379 // (in terms of proportional fee) path in this route and recompute fees.
1380 // This might be not the most economically efficient way, but fewer paths
1381 // also makes routing more reliable.
1382 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1384 // First, drop some expensive low-value paths entirely if possible.
1385 // Sort by value so that we drop many really-low values first, since
1386 // fewer paths is better: the payment is less likely to fail.
1387 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1388 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1389 cur_route.sort_by_key(|path| path.get_value_msat());
1390 // We should make sure that at least 1 path left.
1391 let mut paths_left = cur_route.len();
1392 cur_route.retain(|path| {
1393 if paths_left == 1 {
1396 let mut keep = true;
1397 let path_value_msat = path.get_value_msat();
1398 if path_value_msat <= overpaid_value_msat {
1400 overpaid_value_msat -= path_value_msat;
1406 if overpaid_value_msat == 0 {
1410 assert!(cur_route.len() > 0);
1413 // Now, substract the overpaid value from the most-expensive path.
1414 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1415 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1416 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1417 let expensive_payment_path = cur_route.first_mut().unwrap();
1418 // We already dropped all the small channels above, meaning all the
1419 // remaining channels are larger than remaining overpaid_value_msat.
1420 // Thus, this can't be negative.
1421 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1422 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1426 drawn_routes.push(cur_route);
1430 // Select the best route by lowest total fee.
1431 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1432 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1433 for payment_path in drawn_routes.first().unwrap() {
1434 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1436 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)})?,
1437 node_features: node_features.clone(),
1438 short_channel_id: payment_hop.short_channel_id,
1439 channel_features: payment_hop.channel_features.clone(),
1440 fee_msat: payment_hop.fee_msat,
1441 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1446 if let Some(features) = &payee.features {
1447 for path in selected_paths.iter_mut() {
1448 if let Ok(route_hop) = path.last_mut().unwrap() {
1449 route_hop.node_features = features.to_context();
1455 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1456 payee: Some(payee.clone()),
1458 log_info!(logger, "Got route to {}: {}", payee.pubkey, log_route!(route));
1465 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1466 use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1467 use routing::scorer::Scorer;
1468 use chain::transaction::OutPoint;
1469 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1470 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1471 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1472 use ln::channelmanager;
1473 use util::test_utils;
1474 use util::ser::Writeable;
1476 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1477 use bitcoin::hashes::Hash;
1478 use bitcoin::network::constants::Network;
1479 use bitcoin::blockdata::constants::genesis_block;
1480 use bitcoin::blockdata::script::Builder;
1481 use bitcoin::blockdata::opcodes;
1482 use bitcoin::blockdata::transaction::TxOut;
1486 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1487 use bitcoin::secp256k1::{Secp256k1, All};
1490 use sync::{self, Arc};
1492 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1493 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1494 channelmanager::ChannelDetails {
1495 channel_id: [0; 32],
1496 counterparty: channelmanager::ChannelCounterparty {
1499 unspendable_punishment_reserve: 0,
1500 forwarding_info: None,
1502 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1504 channel_value_satoshis: 0,
1506 outbound_capacity_msat,
1507 inbound_capacity_msat: 42,
1508 unspendable_punishment_reserve: None,
1509 confirmations_required: None,
1510 force_close_spend_delay: None,
1511 is_outbound: true, is_funding_locked: true,
1512 is_usable: true, is_public: true,
1516 // Using the same keys for LN and BTC ids
1518 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1519 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1521 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1522 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1524 let unsigned_announcement = UnsignedChannelAnnouncement {
1526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1530 bitcoin_key_1: node_id_1,
1531 bitcoin_key_2: node_id_2,
1532 excess_data: Vec::new(),
1535 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1536 let valid_announcement = ChannelAnnouncement {
1537 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1538 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1539 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1540 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1541 contents: unsigned_announcement.clone(),
1543 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1544 Ok(res) => assert!(res),
1550 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1551 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1553 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1554 let valid_channel_update = ChannelUpdate {
1555 signature: secp_ctx.sign(&msghash, node_privkey),
1556 contents: update.clone()
1559 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1560 Ok(res) => assert!(res),
1565 fn add_or_update_node(
1566 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1567 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1569 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1570 let unsigned_announcement = UnsignedNodeAnnouncement {
1576 addresses: Vec::new(),
1577 excess_address_data: Vec::new(),
1578 excess_data: Vec::new(),
1580 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1581 let valid_announcement = NodeAnnouncement {
1582 signature: secp_ctx.sign(&msghash, node_privkey),
1583 contents: unsigned_announcement.clone()
1586 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1592 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1593 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1594 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1597 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1599 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1600 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1602 (our_privkey, our_id, privkeys, pubkeys)
1605 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1606 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1607 // test for it later.
1608 let idx = (id - 1) * 2 + 1;
1610 vec![1 << (idx - 8*3), 0, 0, 0]
1611 } else if idx > 8*2 {
1612 vec![1 << (idx - 8*2), 0, 0]
1613 } else if idx > 8*1 {
1614 vec![1 << (idx - 8*1), 0]
1620 fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>) {
1621 let secp_ctx = Secp256k1::new();
1622 let logger = Arc::new(test_utils::TestLogger::new());
1623 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1624 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1625 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1626 // Build network from our_id to node6:
1628 // -1(1)2- node0 -1(3)2-
1630 // our_id -1(12)2- node7 -1(13)2--- node2
1632 // -1(2)2- node1 -1(4)2-
1635 // chan1 1-to-2: disabled
1636 // chan1 2-to-1: enabled, 0 fee
1638 // chan2 1-to-2: enabled, ignored fee
1639 // chan2 2-to-1: enabled, 0 fee
1641 // chan3 1-to-2: enabled, 0 fee
1642 // chan3 2-to-1: enabled, 100 msat fee
1644 // chan4 1-to-2: enabled, 100% fee
1645 // chan4 2-to-1: enabled, 0 fee
1647 // chan12 1-to-2: enabled, ignored fee
1648 // chan12 2-to-1: enabled, 0 fee
1650 // chan13 1-to-2: enabled, 200% fee
1651 // chan13 2-to-1: enabled, 0 fee
1654 // -1(5)2- node3 -1(8)2--
1658 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1660 // -1(7)2- node5 -1(10)2-
1662 // Channels 5, 8, 9 and 10 are private channels.
1664 // chan5 1-to-2: enabled, 100 msat fee
1665 // chan5 2-to-1: enabled, 0 fee
1667 // chan6 1-to-2: enabled, 0 fee
1668 // chan6 2-to-1: enabled, 0 fee
1670 // chan7 1-to-2: enabled, 100% fee
1671 // chan7 2-to-1: enabled, 0 fee
1673 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1674 // chan8 2-to-1: enabled, 0 fee
1676 // chan9 1-to-2: enabled, 1001 msat fee
1677 // chan9 2-to-1: enabled, 0 fee
1679 // chan10 1-to-2: enabled, 0 fee
1680 // chan10 2-to-1: enabled, 0 fee
1682 // chan11 1-to-2: enabled, 0 fee
1683 // chan11 2-to-1: enabled, 0 fee
1685 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1687 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1688 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1689 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1690 short_channel_id: 1,
1693 cltv_expiry_delta: 0,
1694 htlc_minimum_msat: 0,
1695 htlc_maximum_msat: OptionalField::Absent,
1697 fee_proportional_millionths: 0,
1698 excess_data: Vec::new()
1701 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1703 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1704 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1705 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1706 short_channel_id: 2,
1709 cltv_expiry_delta: u16::max_value(),
1710 htlc_minimum_msat: 0,
1711 htlc_maximum_msat: OptionalField::Absent,
1712 fee_base_msat: u32::max_value(),
1713 fee_proportional_millionths: u32::max_value(),
1714 excess_data: Vec::new()
1716 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1718 short_channel_id: 2,
1721 cltv_expiry_delta: 0,
1722 htlc_minimum_msat: 0,
1723 htlc_maximum_msat: OptionalField::Absent,
1725 fee_proportional_millionths: 0,
1726 excess_data: Vec::new()
1729 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1731 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1732 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1733 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1734 short_channel_id: 12,
1737 cltv_expiry_delta: u16::max_value(),
1738 htlc_minimum_msat: 0,
1739 htlc_maximum_msat: OptionalField::Absent,
1740 fee_base_msat: u32::max_value(),
1741 fee_proportional_millionths: u32::max_value(),
1742 excess_data: Vec::new()
1744 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1746 short_channel_id: 12,
1749 cltv_expiry_delta: 0,
1750 htlc_minimum_msat: 0,
1751 htlc_maximum_msat: OptionalField::Absent,
1753 fee_proportional_millionths: 0,
1754 excess_data: Vec::new()
1757 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1759 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1760 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1761 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1762 short_channel_id: 3,
1765 cltv_expiry_delta: (3 << 8) | 1,
1766 htlc_minimum_msat: 0,
1767 htlc_maximum_msat: OptionalField::Absent,
1769 fee_proportional_millionths: 0,
1770 excess_data: Vec::new()
1772 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1773 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1774 short_channel_id: 3,
1777 cltv_expiry_delta: (3 << 8) | 2,
1778 htlc_minimum_msat: 0,
1779 htlc_maximum_msat: OptionalField::Absent,
1781 fee_proportional_millionths: 0,
1782 excess_data: Vec::new()
1785 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1786 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1787 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1788 short_channel_id: 4,
1791 cltv_expiry_delta: (4 << 8) | 1,
1792 htlc_minimum_msat: 0,
1793 htlc_maximum_msat: OptionalField::Absent,
1795 fee_proportional_millionths: 1000000,
1796 excess_data: Vec::new()
1798 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1799 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1800 short_channel_id: 4,
1803 cltv_expiry_delta: (4 << 8) | 2,
1804 htlc_minimum_msat: 0,
1805 htlc_maximum_msat: OptionalField::Absent,
1807 fee_proportional_millionths: 0,
1808 excess_data: Vec::new()
1811 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1812 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1814 short_channel_id: 13,
1817 cltv_expiry_delta: (13 << 8) | 1,
1818 htlc_minimum_msat: 0,
1819 htlc_maximum_msat: OptionalField::Absent,
1821 fee_proportional_millionths: 2000000,
1822 excess_data: Vec::new()
1824 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1826 short_channel_id: 13,
1829 cltv_expiry_delta: (13 << 8) | 2,
1830 htlc_minimum_msat: 0,
1831 htlc_maximum_msat: OptionalField::Absent,
1833 fee_proportional_millionths: 0,
1834 excess_data: Vec::new()
1837 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1839 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1840 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1841 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1842 short_channel_id: 6,
1845 cltv_expiry_delta: (6 << 8) | 1,
1846 htlc_minimum_msat: 0,
1847 htlc_maximum_msat: OptionalField::Absent,
1849 fee_proportional_millionths: 0,
1850 excess_data: Vec::new()
1852 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1853 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1854 short_channel_id: 6,
1857 cltv_expiry_delta: (6 << 8) | 2,
1858 htlc_minimum_msat: 0,
1859 htlc_maximum_msat: OptionalField::Absent,
1861 fee_proportional_millionths: 0,
1862 excess_data: Vec::new(),
1865 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1866 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1868 short_channel_id: 11,
1871 cltv_expiry_delta: (11 << 8) | 1,
1872 htlc_minimum_msat: 0,
1873 htlc_maximum_msat: OptionalField::Absent,
1875 fee_proportional_millionths: 0,
1876 excess_data: Vec::new()
1878 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1879 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1880 short_channel_id: 11,
1883 cltv_expiry_delta: (11 << 8) | 2,
1884 htlc_minimum_msat: 0,
1885 htlc_maximum_msat: OptionalField::Absent,
1887 fee_proportional_millionths: 0,
1888 excess_data: Vec::new()
1891 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1893 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1895 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1896 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1897 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1898 short_channel_id: 7,
1901 cltv_expiry_delta: (7 << 8) | 1,
1902 htlc_minimum_msat: 0,
1903 htlc_maximum_msat: OptionalField::Absent,
1905 fee_proportional_millionths: 1000000,
1906 excess_data: Vec::new()
1908 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1909 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1910 short_channel_id: 7,
1913 cltv_expiry_delta: (7 << 8) | 2,
1914 htlc_minimum_msat: 0,
1915 htlc_maximum_msat: OptionalField::Absent,
1917 fee_proportional_millionths: 0,
1918 excess_data: Vec::new()
1921 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1923 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1927 fn simple_route_test() {
1928 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1929 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1930 let payee = Payee::new(nodes[2]);
1931 let scorer = Scorer::new(0);
1933 // Simple route to 2 via 1
1935 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
1936 assert_eq!(err, "Cannot send a payment of 0 msat");
1937 } else { panic!(); }
1939 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1940 assert_eq!(route.paths[0].len(), 2);
1942 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1943 assert_eq!(route.paths[0][0].short_channel_id, 2);
1944 assert_eq!(route.paths[0][0].fee_msat, 100);
1945 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1946 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1947 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1949 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1950 assert_eq!(route.paths[0][1].short_channel_id, 4);
1951 assert_eq!(route.paths[0][1].fee_msat, 100);
1952 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1953 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1954 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1958 fn invalid_first_hop_test() {
1959 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1960 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1961 let payee = Payee::new(nodes[2]);
1962 let scorer = Scorer::new(0);
1964 // Simple route to 2 via 1
1966 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1968 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
1969 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1970 } else { panic!(); }
1972 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1973 assert_eq!(route.paths[0].len(), 2);
1977 fn htlc_minimum_test() {
1978 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1979 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1980 let payee = Payee::new(nodes[2]);
1981 let scorer = Scorer::new(0);
1983 // Simple route to 2 via 1
1985 // Disable other paths
1986 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1987 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1988 short_channel_id: 12,
1990 flags: 2, // to disable
1991 cltv_expiry_delta: 0,
1992 htlc_minimum_msat: 0,
1993 htlc_maximum_msat: OptionalField::Absent,
1995 fee_proportional_millionths: 0,
1996 excess_data: Vec::new()
1998 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1999 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2000 short_channel_id: 3,
2002 flags: 2, // to disable
2003 cltv_expiry_delta: 0,
2004 htlc_minimum_msat: 0,
2005 htlc_maximum_msat: OptionalField::Absent,
2007 fee_proportional_millionths: 0,
2008 excess_data: Vec::new()
2010 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2012 short_channel_id: 13,
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[2], UnsignedChannelUpdate {
2023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2024 short_channel_id: 6,
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[2], UnsignedChannelUpdate {
2035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2036 short_channel_id: 7,
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()
2047 // Check against amount_to_transfer_over_msat.
2048 // Set minimal HTLC of 200_000_000 msat.
2049 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2050 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2051 short_channel_id: 2,
2054 cltv_expiry_delta: 0,
2055 htlc_minimum_msat: 200_000_000,
2056 htlc_maximum_msat: OptionalField::Absent,
2058 fee_proportional_millionths: 0,
2059 excess_data: Vec::new()
2062 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2064 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2065 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2066 short_channel_id: 4,
2069 cltv_expiry_delta: 0,
2070 htlc_minimum_msat: 0,
2071 htlc_maximum_msat: OptionalField::Present(199_999_999),
2073 fee_proportional_millionths: 0,
2074 excess_data: Vec::new()
2077 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2078 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2079 assert_eq!(err, "Failed to find a path to the given destination");
2080 } else { panic!(); }
2082 // Lift the restriction on the first hop.
2083 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2084 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2085 short_channel_id: 2,
2088 cltv_expiry_delta: 0,
2089 htlc_minimum_msat: 0,
2090 htlc_maximum_msat: OptionalField::Absent,
2092 fee_proportional_millionths: 0,
2093 excess_data: Vec::new()
2096 // A payment above the minimum should pass
2097 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2098 assert_eq!(route.paths[0].len(), 2);
2102 fn htlc_minimum_overpay_test() {
2103 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2104 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2105 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2106 let scorer = Scorer::new(0);
2108 // A route to node#2 via two paths.
2109 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2110 // Thus, they can't send 60 without overpaying.
2111 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2112 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2113 short_channel_id: 2,
2116 cltv_expiry_delta: 0,
2117 htlc_minimum_msat: 35_000,
2118 htlc_maximum_msat: OptionalField::Present(40_000),
2120 fee_proportional_millionths: 0,
2121 excess_data: Vec::new()
2123 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2124 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2125 short_channel_id: 12,
2128 cltv_expiry_delta: 0,
2129 htlc_minimum_msat: 35_000,
2130 htlc_maximum_msat: OptionalField::Present(40_000),
2132 fee_proportional_millionths: 0,
2133 excess_data: Vec::new()
2137 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2139 short_channel_id: 13,
2142 cltv_expiry_delta: 0,
2143 htlc_minimum_msat: 0,
2144 htlc_maximum_msat: OptionalField::Absent,
2146 fee_proportional_millionths: 0,
2147 excess_data: Vec::new()
2149 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2150 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2151 short_channel_id: 4,
2154 cltv_expiry_delta: 0,
2155 htlc_minimum_msat: 0,
2156 htlc_maximum_msat: OptionalField::Absent,
2158 fee_proportional_millionths: 0,
2159 excess_data: Vec::new()
2162 // Disable other paths
2163 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2165 short_channel_id: 1,
2167 flags: 2, // to disable
2168 cltv_expiry_delta: 0,
2169 htlc_minimum_msat: 0,
2170 htlc_maximum_msat: OptionalField::Absent,
2172 fee_proportional_millionths: 0,
2173 excess_data: Vec::new()
2176 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2177 // Overpay fees to hit htlc_minimum_msat.
2178 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2179 // TODO: this could be better balanced to overpay 10k and not 15k.
2180 assert_eq!(overpaid_fees, 15_000);
2182 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2183 // while taking even more fee to match htlc_minimum_msat.
2184 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2186 short_channel_id: 12,
2189 cltv_expiry_delta: 0,
2190 htlc_minimum_msat: 65_000,
2191 htlc_maximum_msat: OptionalField::Present(80_000),
2193 fee_proportional_millionths: 0,
2194 excess_data: Vec::new()
2196 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2198 short_channel_id: 2,
2201 cltv_expiry_delta: 0,
2202 htlc_minimum_msat: 0,
2203 htlc_maximum_msat: OptionalField::Absent,
2205 fee_proportional_millionths: 0,
2206 excess_data: Vec::new()
2208 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210 short_channel_id: 4,
2213 cltv_expiry_delta: 0,
2214 htlc_minimum_msat: 0,
2215 htlc_maximum_msat: OptionalField::Absent,
2217 fee_proportional_millionths: 100_000,
2218 excess_data: Vec::new()
2221 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2222 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2223 assert_eq!(route.paths.len(), 1);
2224 assert_eq!(route.paths[0][0].short_channel_id, 12);
2225 let fees = route.paths[0][0].fee_msat;
2226 assert_eq!(fees, 5_000);
2228 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2229 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2230 // the other channel.
2231 assert_eq!(route.paths.len(), 1);
2232 assert_eq!(route.paths[0][0].short_channel_id, 2);
2233 let fees = route.paths[0][0].fee_msat;
2234 assert_eq!(fees, 5_000);
2238 fn disable_channels_test() {
2239 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2240 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2241 let payee = Payee::new(nodes[2]);
2242 let scorer = Scorer::new(0);
2244 // // Disable channels 4 and 12 by flags=2
2245 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2246 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2247 short_channel_id: 4,
2249 flags: 2, // to disable
2250 cltv_expiry_delta: 0,
2251 htlc_minimum_msat: 0,
2252 htlc_maximum_msat: OptionalField::Absent,
2254 fee_proportional_millionths: 0,
2255 excess_data: Vec::new()
2257 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2259 short_channel_id: 12,
2261 flags: 2, // to disable
2262 cltv_expiry_delta: 0,
2263 htlc_minimum_msat: 0,
2264 htlc_maximum_msat: OptionalField::Absent,
2266 fee_proportional_millionths: 0,
2267 excess_data: Vec::new()
2270 // If all the channels require some features we don't understand, route should fail
2271 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2272 assert_eq!(err, "Failed to find a path to the given destination");
2273 } else { panic!(); }
2275 // If we specify a channel to node7, that overrides our local channel view and that gets used
2276 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2277 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2278 assert_eq!(route.paths[0].len(), 2);
2280 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2281 assert_eq!(route.paths[0][0].short_channel_id, 42);
2282 assert_eq!(route.paths[0][0].fee_msat, 200);
2283 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2284 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2285 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2287 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2288 assert_eq!(route.paths[0][1].short_channel_id, 13);
2289 assert_eq!(route.paths[0][1].fee_msat, 100);
2290 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2291 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2292 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2296 fn disable_node_test() {
2297 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2298 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2299 let payee = Payee::new(nodes[2]);
2300 let scorer = Scorer::new(0);
2302 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2303 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2304 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2305 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2306 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2308 // If all nodes require some features we don't understand, route should fail
2309 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2310 assert_eq!(err, "Failed to find a path to the given destination");
2311 } else { panic!(); }
2313 // If we specify a channel to node7, that overrides our local channel view and that gets used
2314 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2315 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2316 assert_eq!(route.paths[0].len(), 2);
2318 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2319 assert_eq!(route.paths[0][0].short_channel_id, 42);
2320 assert_eq!(route.paths[0][0].fee_msat, 200);
2321 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2322 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2323 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2325 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2326 assert_eq!(route.paths[0][1].short_channel_id, 13);
2327 assert_eq!(route.paths[0][1].fee_msat, 100);
2328 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2329 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2330 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2332 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2333 // naively) assume that the user checked the feature bits on the invoice, which override
2334 // the node_announcement.
2338 fn our_chans_test() {
2339 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2340 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2341 let scorer = Scorer::new(0);
2343 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2344 let payee = Payee::new(nodes[0]);
2345 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2346 assert_eq!(route.paths[0].len(), 3);
2348 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2349 assert_eq!(route.paths[0][0].short_channel_id, 2);
2350 assert_eq!(route.paths[0][0].fee_msat, 200);
2351 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2352 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2353 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2355 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2356 assert_eq!(route.paths[0][1].short_channel_id, 4);
2357 assert_eq!(route.paths[0][1].fee_msat, 100);
2358 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2359 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2360 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2362 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2363 assert_eq!(route.paths[0][2].short_channel_id, 3);
2364 assert_eq!(route.paths[0][2].fee_msat, 100);
2365 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2366 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2367 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2369 // If we specify a channel to node7, that overrides our local channel view and that gets used
2370 let payee = Payee::new(nodes[2]);
2371 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2372 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2373 assert_eq!(route.paths[0].len(), 2);
2375 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2376 assert_eq!(route.paths[0][0].short_channel_id, 42);
2377 assert_eq!(route.paths[0][0].fee_msat, 200);
2378 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2379 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2380 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2382 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2383 assert_eq!(route.paths[0][1].short_channel_id, 13);
2384 assert_eq!(route.paths[0][1].fee_msat, 100);
2385 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2386 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2387 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2390 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2391 let zero_fees = RoutingFees {
2393 proportional_millionths: 0,
2395 vec![RouteHint(vec![RouteHintHop {
2396 src_node_id: nodes[3],
2397 short_channel_id: 8,
2399 cltv_expiry_delta: (8 << 8) | 1,
2400 htlc_minimum_msat: None,
2401 htlc_maximum_msat: None,
2403 ]), RouteHint(vec![RouteHintHop {
2404 src_node_id: nodes[4],
2405 short_channel_id: 9,
2408 proportional_millionths: 0,
2410 cltv_expiry_delta: (9 << 8) | 1,
2411 htlc_minimum_msat: None,
2412 htlc_maximum_msat: None,
2413 }]), RouteHint(vec![RouteHintHop {
2414 src_node_id: nodes[5],
2415 short_channel_id: 10,
2417 cltv_expiry_delta: (10 << 8) | 1,
2418 htlc_minimum_msat: None,
2419 htlc_maximum_msat: None,
2423 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2424 let zero_fees = RoutingFees {
2426 proportional_millionths: 0,
2428 vec![RouteHint(vec![RouteHintHop {
2429 src_node_id: nodes[2],
2430 short_channel_id: 5,
2433 proportional_millionths: 0,
2435 cltv_expiry_delta: (5 << 8) | 1,
2436 htlc_minimum_msat: None,
2437 htlc_maximum_msat: None,
2439 src_node_id: nodes[3],
2440 short_channel_id: 8,
2442 cltv_expiry_delta: (8 << 8) | 1,
2443 htlc_minimum_msat: None,
2444 htlc_maximum_msat: None,
2446 ]), RouteHint(vec![RouteHintHop {
2447 src_node_id: nodes[4],
2448 short_channel_id: 9,
2451 proportional_millionths: 0,
2453 cltv_expiry_delta: (9 << 8) | 1,
2454 htlc_minimum_msat: None,
2455 htlc_maximum_msat: None,
2456 }]), RouteHint(vec![RouteHintHop {
2457 src_node_id: nodes[5],
2458 short_channel_id: 10,
2460 cltv_expiry_delta: (10 << 8) | 1,
2461 htlc_minimum_msat: None,
2462 htlc_maximum_msat: None,
2467 fn partial_route_hint_test() {
2468 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2469 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2470 let scorer = Scorer::new(0);
2472 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2473 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2474 // RouteHint may be partially used by the algo to build the best path.
2476 // First check that last hop can't have its source as the payee.
2477 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2478 src_node_id: nodes[6],
2479 short_channel_id: 8,
2482 proportional_millionths: 0,
2484 cltv_expiry_delta: (8 << 8) | 1,
2485 htlc_minimum_msat: None,
2486 htlc_maximum_msat: None,
2489 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2490 invalid_last_hops.push(invalid_last_hop);
2492 let payee = Payee::new(nodes[6]).with_route_hints(invalid_last_hops);
2493 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2494 assert_eq!(err, "Route hint cannot have the payee as the source.");
2495 } else { panic!(); }
2498 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2499 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2500 assert_eq!(route.paths[0].len(), 5);
2502 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2503 assert_eq!(route.paths[0][0].short_channel_id, 2);
2504 assert_eq!(route.paths[0][0].fee_msat, 100);
2505 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2506 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2507 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2509 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2510 assert_eq!(route.paths[0][1].short_channel_id, 4);
2511 assert_eq!(route.paths[0][1].fee_msat, 0);
2512 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2513 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2514 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2516 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2517 assert_eq!(route.paths[0][2].short_channel_id, 6);
2518 assert_eq!(route.paths[0][2].fee_msat, 0);
2519 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2520 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2521 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2523 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2524 assert_eq!(route.paths[0][3].short_channel_id, 11);
2525 assert_eq!(route.paths[0][3].fee_msat, 0);
2526 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2527 // If we have a peer in the node map, we'll use their features here since we don't have
2528 // a way of figuring out their features from the invoice:
2529 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2530 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2532 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2533 assert_eq!(route.paths[0][4].short_channel_id, 8);
2534 assert_eq!(route.paths[0][4].fee_msat, 100);
2535 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2536 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2537 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2540 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2541 let zero_fees = RoutingFees {
2543 proportional_millionths: 0,
2545 vec![RouteHint(vec![RouteHintHop {
2546 src_node_id: nodes[3],
2547 short_channel_id: 8,
2549 cltv_expiry_delta: (8 << 8) | 1,
2550 htlc_minimum_msat: None,
2551 htlc_maximum_msat: None,
2552 }]), RouteHint(vec![
2554 ]), RouteHint(vec![RouteHintHop {
2555 src_node_id: nodes[5],
2556 short_channel_id: 10,
2558 cltv_expiry_delta: (10 << 8) | 1,
2559 htlc_minimum_msat: None,
2560 htlc_maximum_msat: None,
2565 fn ignores_empty_last_hops_test() {
2566 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2567 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2568 let payee = Payee::new(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2569 let scorer = Scorer::new(0);
2571 // Test handling of an empty RouteHint passed in Invoice.
2573 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2574 assert_eq!(route.paths[0].len(), 5);
2576 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2577 assert_eq!(route.paths[0][0].short_channel_id, 2);
2578 assert_eq!(route.paths[0][0].fee_msat, 100);
2579 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2580 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2581 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2583 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2584 assert_eq!(route.paths[0][1].short_channel_id, 4);
2585 assert_eq!(route.paths[0][1].fee_msat, 0);
2586 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2587 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2588 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2590 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2591 assert_eq!(route.paths[0][2].short_channel_id, 6);
2592 assert_eq!(route.paths[0][2].fee_msat, 0);
2593 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2594 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2595 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2597 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2598 assert_eq!(route.paths[0][3].short_channel_id, 11);
2599 assert_eq!(route.paths[0][3].fee_msat, 0);
2600 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2601 // If we have a peer in the node map, we'll use their features here since we don't have
2602 // a way of figuring out their features from the invoice:
2603 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2604 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2606 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2607 assert_eq!(route.paths[0][4].short_channel_id, 8);
2608 assert_eq!(route.paths[0][4].fee_msat, 100);
2609 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2610 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2611 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2614 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2615 let zero_fees = RoutingFees {
2617 proportional_millionths: 0,
2619 vec![RouteHint(vec![RouteHintHop {
2620 src_node_id: nodes[2],
2621 short_channel_id: 5,
2624 proportional_millionths: 0,
2626 cltv_expiry_delta: (5 << 8) | 1,
2627 htlc_minimum_msat: None,
2628 htlc_maximum_msat: None,
2630 src_node_id: nodes[3],
2631 short_channel_id: 8,
2633 cltv_expiry_delta: (8 << 8) | 1,
2634 htlc_minimum_msat: None,
2635 htlc_maximum_msat: None,
2636 }]), RouteHint(vec![RouteHintHop {
2637 src_node_id: nodes[5],
2638 short_channel_id: 10,
2640 cltv_expiry_delta: (10 << 8) | 1,
2641 htlc_minimum_msat: None,
2642 htlc_maximum_msat: None,
2647 fn multi_hint_last_hops_test() {
2648 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2649 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2650 let payee = Payee::new(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2651 let scorer = Scorer::new(0);
2652 // Test through channels 2, 3, 5, 8.
2653 // Test shows that multiple hop hints are considered.
2655 // Disabling channels 6 & 7 by flags=2
2656 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2657 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2658 short_channel_id: 6,
2660 flags: 2, // to disable
2661 cltv_expiry_delta: 0,
2662 htlc_minimum_msat: 0,
2663 htlc_maximum_msat: OptionalField::Absent,
2665 fee_proportional_millionths: 0,
2666 excess_data: Vec::new()
2668 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2669 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2670 short_channel_id: 7,
2672 flags: 2, // to disable
2673 cltv_expiry_delta: 0,
2674 htlc_minimum_msat: 0,
2675 htlc_maximum_msat: OptionalField::Absent,
2677 fee_proportional_millionths: 0,
2678 excess_data: Vec::new()
2681 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2682 assert_eq!(route.paths[0].len(), 4);
2684 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2685 assert_eq!(route.paths[0][0].short_channel_id, 2);
2686 assert_eq!(route.paths[0][0].fee_msat, 200);
2687 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2688 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2689 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2691 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2692 assert_eq!(route.paths[0][1].short_channel_id, 4);
2693 assert_eq!(route.paths[0][1].fee_msat, 100);
2694 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2695 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2696 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2698 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2699 assert_eq!(route.paths[0][2].short_channel_id, 5);
2700 assert_eq!(route.paths[0][2].fee_msat, 0);
2701 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2702 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2703 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2705 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2706 assert_eq!(route.paths[0][3].short_channel_id, 8);
2707 assert_eq!(route.paths[0][3].fee_msat, 100);
2708 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2709 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2710 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2713 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2714 let zero_fees = RoutingFees {
2716 proportional_millionths: 0,
2718 vec![RouteHint(vec![RouteHintHop {
2719 src_node_id: nodes[4],
2720 short_channel_id: 11,
2722 cltv_expiry_delta: (11 << 8) | 1,
2723 htlc_minimum_msat: None,
2724 htlc_maximum_msat: None,
2726 src_node_id: nodes[3],
2727 short_channel_id: 8,
2729 cltv_expiry_delta: (8 << 8) | 1,
2730 htlc_minimum_msat: None,
2731 htlc_maximum_msat: None,
2732 }]), RouteHint(vec![RouteHintHop {
2733 src_node_id: nodes[4],
2734 short_channel_id: 9,
2737 proportional_millionths: 0,
2739 cltv_expiry_delta: (9 << 8) | 1,
2740 htlc_minimum_msat: None,
2741 htlc_maximum_msat: None,
2742 }]), RouteHint(vec![RouteHintHop {
2743 src_node_id: nodes[5],
2744 short_channel_id: 10,
2746 cltv_expiry_delta: (10 << 8) | 1,
2747 htlc_minimum_msat: None,
2748 htlc_maximum_msat: None,
2753 fn last_hops_with_public_channel_test() {
2754 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2755 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2756 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2757 let scorer = Scorer::new(0);
2758 // This test shows that public routes can be present in the invoice
2759 // which would be handled in the same manner.
2761 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2762 assert_eq!(route.paths[0].len(), 5);
2764 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2765 assert_eq!(route.paths[0][0].short_channel_id, 2);
2766 assert_eq!(route.paths[0][0].fee_msat, 100);
2767 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2768 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2769 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2771 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2772 assert_eq!(route.paths[0][1].short_channel_id, 4);
2773 assert_eq!(route.paths[0][1].fee_msat, 0);
2774 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2775 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2776 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2778 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2779 assert_eq!(route.paths[0][2].short_channel_id, 6);
2780 assert_eq!(route.paths[0][2].fee_msat, 0);
2781 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2782 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2783 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2785 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2786 assert_eq!(route.paths[0][3].short_channel_id, 11);
2787 assert_eq!(route.paths[0][3].fee_msat, 0);
2788 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2789 // If we have a peer in the node map, we'll use their features here since we don't have
2790 // a way of figuring out their features from the invoice:
2791 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2792 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2794 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2795 assert_eq!(route.paths[0][4].short_channel_id, 8);
2796 assert_eq!(route.paths[0][4].fee_msat, 100);
2797 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2798 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2799 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2803 fn our_chans_last_hop_connect_test() {
2804 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2805 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2806 let scorer = Scorer::new(0);
2808 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2809 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2810 let mut last_hops = last_hops(&nodes);
2811 let payee = Payee::new(nodes[6]).with_route_hints(last_hops.clone());
2812 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2813 assert_eq!(route.paths[0].len(), 2);
2815 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2816 assert_eq!(route.paths[0][0].short_channel_id, 42);
2817 assert_eq!(route.paths[0][0].fee_msat, 0);
2818 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2819 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2820 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2822 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2823 assert_eq!(route.paths[0][1].short_channel_id, 8);
2824 assert_eq!(route.paths[0][1].fee_msat, 100);
2825 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2826 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2827 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2829 last_hops[0].0[0].fees.base_msat = 1000;
2831 // Revert to via 6 as the fee on 8 goes up
2832 let payee = Payee::new(nodes[6]).with_route_hints(last_hops);
2833 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2834 assert_eq!(route.paths[0].len(), 4);
2836 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2837 assert_eq!(route.paths[0][0].short_channel_id, 2);
2838 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2839 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2840 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2841 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2843 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2844 assert_eq!(route.paths[0][1].short_channel_id, 4);
2845 assert_eq!(route.paths[0][1].fee_msat, 100);
2846 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2847 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2848 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2850 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2851 assert_eq!(route.paths[0][2].short_channel_id, 7);
2852 assert_eq!(route.paths[0][2].fee_msat, 0);
2853 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2854 // If we have a peer in the node map, we'll use their features here since we don't have
2855 // a way of figuring out their features from the invoice:
2856 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2857 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2859 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2860 assert_eq!(route.paths[0][3].short_channel_id, 10);
2861 assert_eq!(route.paths[0][3].fee_msat, 100);
2862 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2863 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2864 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2866 // ...but still use 8 for larger payments as 6 has a variable feerate
2867 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2868 assert_eq!(route.paths[0].len(), 5);
2870 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2871 assert_eq!(route.paths[0][0].short_channel_id, 2);
2872 assert_eq!(route.paths[0][0].fee_msat, 3000);
2873 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2874 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2875 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2877 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2878 assert_eq!(route.paths[0][1].short_channel_id, 4);
2879 assert_eq!(route.paths[0][1].fee_msat, 0);
2880 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2881 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2882 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2884 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2885 assert_eq!(route.paths[0][2].short_channel_id, 6);
2886 assert_eq!(route.paths[0][2].fee_msat, 0);
2887 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2888 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2889 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2891 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2892 assert_eq!(route.paths[0][3].short_channel_id, 11);
2893 assert_eq!(route.paths[0][3].fee_msat, 1000);
2894 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2895 // If we have a peer in the node map, we'll use their features here since we don't have
2896 // a way of figuring out their features from the invoice:
2897 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2898 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2900 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2901 assert_eq!(route.paths[0][4].short_channel_id, 8);
2902 assert_eq!(route.paths[0][4].fee_msat, 2000);
2903 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2904 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2905 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2908 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> {
2909 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2910 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2911 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2913 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2914 let last_hops = RouteHint(vec![RouteHintHop {
2915 src_node_id: middle_node_id,
2916 short_channel_id: 8,
2919 proportional_millionths: last_hop_fee_prop,
2921 cltv_expiry_delta: (8 << 8) | 1,
2922 htlc_minimum_msat: None,
2923 htlc_maximum_msat: last_hop_htlc_max,
2925 let payee = Payee::new(target_node_id).with_route_hints(vec![last_hops]);
2926 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2927 let scorer = Scorer::new(0);
2928 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)
2932 fn unannounced_path_test() {
2933 // We should be able to send a payment to a destination without any help of a routing graph
2934 // if we have a channel with a common counterparty that appears in the first and last hop
2936 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2938 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2939 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2940 assert_eq!(route.paths[0].len(), 2);
2942 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2943 assert_eq!(route.paths[0][0].short_channel_id, 42);
2944 assert_eq!(route.paths[0][0].fee_msat, 1001);
2945 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2946 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2947 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2949 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2950 assert_eq!(route.paths[0][1].short_channel_id, 8);
2951 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2952 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2953 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2954 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2958 fn overflow_unannounced_path_test_liquidity_underflow() {
2959 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2960 // the last-hop had a fee which overflowed a u64, we'd panic.
2961 // This was due to us adding the first-hop from us unconditionally, causing us to think
2962 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2963 // In this test, we previously hit a subtraction underflow due to having less available
2964 // liquidity at the last hop than 0.
2965 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());
2969 fn overflow_unannounced_path_test_feerate_overflow() {
2970 // This tests for the same case as above, except instead of hitting a subtraction
2971 // underflow, we hit a case where the fee charged at a hop overflowed.
2972 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());
2976 fn available_amount_while_routing_test() {
2977 // Tests whether we choose the correct available channel amount while routing.
2979 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2980 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2981 let scorer = Scorer::new(0);
2982 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2984 // We will use a simple single-path route from
2985 // our node to node2 via node0: channels {1, 3}.
2987 // First disable all other paths.
2988 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2989 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2990 short_channel_id: 2,
2993 cltv_expiry_delta: 0,
2994 htlc_minimum_msat: 0,
2995 htlc_maximum_msat: OptionalField::Present(100_000),
2997 fee_proportional_millionths: 0,
2998 excess_data: Vec::new()
3000 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3002 short_channel_id: 12,
3005 cltv_expiry_delta: 0,
3006 htlc_minimum_msat: 0,
3007 htlc_maximum_msat: OptionalField::Present(100_000),
3009 fee_proportional_millionths: 0,
3010 excess_data: Vec::new()
3013 // Make the first channel (#1) very permissive,
3014 // and we will be testing all limits on the second channel.
3015 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3016 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3017 short_channel_id: 1,
3020 cltv_expiry_delta: 0,
3021 htlc_minimum_msat: 0,
3022 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3024 fee_proportional_millionths: 0,
3025 excess_data: Vec::new()
3028 // First, let's see if routing works if we have absolutely no idea about the available amount.
3029 // In this case, it should be set to 250_000 sats.
3030 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3031 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3032 short_channel_id: 3,
3035 cltv_expiry_delta: 0,
3036 htlc_minimum_msat: 0,
3037 htlc_maximum_msat: OptionalField::Absent,
3039 fee_proportional_millionths: 0,
3040 excess_data: Vec::new()
3044 // Attempt to route more than available results in a failure.
3045 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3046 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3047 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3048 } else { panic!(); }
3052 // Now, attempt to route an exact amount we have should be fine.
3053 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3054 assert_eq!(route.paths.len(), 1);
3055 let path = route.paths.last().unwrap();
3056 assert_eq!(path.len(), 2);
3057 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3058 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3061 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3062 // Disable channel #1 and use another first hop.
3063 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3065 short_channel_id: 1,
3068 cltv_expiry_delta: 0,
3069 htlc_minimum_msat: 0,
3070 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3072 fee_proportional_millionths: 0,
3073 excess_data: Vec::new()
3076 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3077 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3080 // Attempt to route more than available results in a failure.
3081 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3082 &our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3083 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3084 } else { panic!(); }
3088 // Now, attempt to route an exact amount we have should be fine.
3089 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3090 assert_eq!(route.paths.len(), 1);
3091 let path = route.paths.last().unwrap();
3092 assert_eq!(path.len(), 2);
3093 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3094 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3097 // Enable channel #1 back.
3098 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3099 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3100 short_channel_id: 1,
3103 cltv_expiry_delta: 0,
3104 htlc_minimum_msat: 0,
3105 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3107 fee_proportional_millionths: 0,
3108 excess_data: Vec::new()
3112 // Now let's see if routing works if we know only htlc_maximum_msat.
3113 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3114 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3115 short_channel_id: 3,
3118 cltv_expiry_delta: 0,
3119 htlc_minimum_msat: 0,
3120 htlc_maximum_msat: OptionalField::Present(15_000),
3122 fee_proportional_millionths: 0,
3123 excess_data: Vec::new()
3127 // Attempt to route more than available results in a failure.
3128 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3129 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3130 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3131 } else { panic!(); }
3135 // Now, attempt to route an exact amount we have should be fine.
3136 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3137 assert_eq!(route.paths.len(), 1);
3138 let path = route.paths.last().unwrap();
3139 assert_eq!(path.len(), 2);
3140 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3141 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3144 // Now let's see if routing works if we know only capacity from the UTXO.
3146 // We can't change UTXO capacity on the fly, so we'll disable
3147 // the existing channel and add another one with the capacity we need.
3148 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3149 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3150 short_channel_id: 3,
3153 cltv_expiry_delta: 0,
3154 htlc_minimum_msat: 0,
3155 htlc_maximum_msat: OptionalField::Absent,
3157 fee_proportional_millionths: 0,
3158 excess_data: Vec::new()
3161 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3162 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3163 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3164 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3165 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3167 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3168 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3170 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3171 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3172 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3173 short_channel_id: 333,
3176 cltv_expiry_delta: (3 << 8) | 1,
3177 htlc_minimum_msat: 0,
3178 htlc_maximum_msat: OptionalField::Absent,
3180 fee_proportional_millionths: 0,
3181 excess_data: Vec::new()
3183 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3184 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3185 short_channel_id: 333,
3188 cltv_expiry_delta: (3 << 8) | 2,
3189 htlc_minimum_msat: 0,
3190 htlc_maximum_msat: OptionalField::Absent,
3192 fee_proportional_millionths: 0,
3193 excess_data: Vec::new()
3197 // Attempt to route more than available results in a failure.
3198 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3199 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3200 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3201 } else { panic!(); }
3205 // Now, attempt to route an exact amount we have should be fine.
3206 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3207 assert_eq!(route.paths.len(), 1);
3208 let path = route.paths.last().unwrap();
3209 assert_eq!(path.len(), 2);
3210 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3211 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3214 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3215 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3216 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3217 short_channel_id: 333,
3220 cltv_expiry_delta: 0,
3221 htlc_minimum_msat: 0,
3222 htlc_maximum_msat: OptionalField::Present(10_000),
3224 fee_proportional_millionths: 0,
3225 excess_data: Vec::new()
3229 // Attempt to route more than available results in a failure.
3230 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3231 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3232 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3233 } else { panic!(); }
3237 // Now, attempt to route an exact amount we have should be fine.
3238 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3239 assert_eq!(route.paths.len(), 1);
3240 let path = route.paths.last().unwrap();
3241 assert_eq!(path.len(), 2);
3242 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3243 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3248 fn available_liquidity_last_hop_test() {
3249 // Check that available liquidity properly limits the path even when only
3250 // one of the latter hops is limited.
3251 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3252 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3253 let scorer = Scorer::new(0);
3254 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3256 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3257 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3258 // Total capacity: 50 sats.
3260 // Disable other potential paths.
3261 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3262 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3263 short_channel_id: 2,
3266 cltv_expiry_delta: 0,
3267 htlc_minimum_msat: 0,
3268 htlc_maximum_msat: OptionalField::Present(100_000),
3270 fee_proportional_millionths: 0,
3271 excess_data: Vec::new()
3273 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3274 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3275 short_channel_id: 7,
3278 cltv_expiry_delta: 0,
3279 htlc_minimum_msat: 0,
3280 htlc_maximum_msat: OptionalField::Present(100_000),
3282 fee_proportional_millionths: 0,
3283 excess_data: Vec::new()
3288 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3289 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3290 short_channel_id: 12,
3293 cltv_expiry_delta: 0,
3294 htlc_minimum_msat: 0,
3295 htlc_maximum_msat: OptionalField::Present(100_000),
3297 fee_proportional_millionths: 0,
3298 excess_data: Vec::new()
3300 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3302 short_channel_id: 13,
3305 cltv_expiry_delta: 0,
3306 htlc_minimum_msat: 0,
3307 htlc_maximum_msat: OptionalField::Present(100_000),
3309 fee_proportional_millionths: 0,
3310 excess_data: Vec::new()
3313 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3314 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3315 short_channel_id: 6,
3318 cltv_expiry_delta: 0,
3319 htlc_minimum_msat: 0,
3320 htlc_maximum_msat: OptionalField::Present(50_000),
3322 fee_proportional_millionths: 0,
3323 excess_data: Vec::new()
3325 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3326 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3327 short_channel_id: 11,
3330 cltv_expiry_delta: 0,
3331 htlc_minimum_msat: 0,
3332 htlc_maximum_msat: OptionalField::Present(100_000),
3334 fee_proportional_millionths: 0,
3335 excess_data: Vec::new()
3338 // Attempt to route more than available results in a failure.
3339 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3340 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3341 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3342 } else { panic!(); }
3346 // Now, attempt to route 49 sats (just a bit below the capacity).
3347 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3348 assert_eq!(route.paths.len(), 1);
3349 let mut total_amount_paid_msat = 0;
3350 for path in &route.paths {
3351 assert_eq!(path.len(), 4);
3352 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3353 total_amount_paid_msat += path.last().unwrap().fee_msat;
3355 assert_eq!(total_amount_paid_msat, 49_000);
3359 // Attempt to route an exact amount is also fine
3360 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3361 assert_eq!(route.paths.len(), 1);
3362 let mut total_amount_paid_msat = 0;
3363 for path in &route.paths {
3364 assert_eq!(path.len(), 4);
3365 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3366 total_amount_paid_msat += path.last().unwrap().fee_msat;
3368 assert_eq!(total_amount_paid_msat, 50_000);
3373 fn ignore_fee_first_hop_test() {
3374 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3375 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3376 let scorer = Scorer::new(0);
3377 let payee = Payee::new(nodes[2]);
3379 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3380 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3381 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3382 short_channel_id: 1,
3385 cltv_expiry_delta: 0,
3386 htlc_minimum_msat: 0,
3387 htlc_maximum_msat: OptionalField::Present(100_000),
3388 fee_base_msat: 1_000_000,
3389 fee_proportional_millionths: 0,
3390 excess_data: Vec::new()
3392 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3393 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3394 short_channel_id: 3,
3397 cltv_expiry_delta: 0,
3398 htlc_minimum_msat: 0,
3399 htlc_maximum_msat: OptionalField::Present(50_000),
3401 fee_proportional_millionths: 0,
3402 excess_data: Vec::new()
3406 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3407 assert_eq!(route.paths.len(), 1);
3408 let mut total_amount_paid_msat = 0;
3409 for path in &route.paths {
3410 assert_eq!(path.len(), 2);
3411 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3412 total_amount_paid_msat += path.last().unwrap().fee_msat;
3414 assert_eq!(total_amount_paid_msat, 50_000);
3419 fn simple_mpp_route_test() {
3420 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3421 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3422 let scorer = Scorer::new(0);
3423 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
3425 // We need a route consisting of 3 paths:
3426 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3427 // To achieve this, the amount being transferred should be around
3428 // the total capacity of these 3 paths.
3430 // First, we set limits on these (previously unlimited) channels.
3431 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3433 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3434 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3436 short_channel_id: 1,
3439 cltv_expiry_delta: 0,
3440 htlc_minimum_msat: 0,
3441 htlc_maximum_msat: OptionalField::Present(100_000),
3443 fee_proportional_millionths: 0,
3444 excess_data: Vec::new()
3446 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3447 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3448 short_channel_id: 3,
3451 cltv_expiry_delta: 0,
3452 htlc_minimum_msat: 0,
3453 htlc_maximum_msat: OptionalField::Present(50_000),
3455 fee_proportional_millionths: 0,
3456 excess_data: Vec::new()
3459 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3460 // (total limit 60).
3461 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3463 short_channel_id: 12,
3466 cltv_expiry_delta: 0,
3467 htlc_minimum_msat: 0,
3468 htlc_maximum_msat: OptionalField::Present(60_000),
3470 fee_proportional_millionths: 0,
3471 excess_data: Vec::new()
3473 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3475 short_channel_id: 13,
3478 cltv_expiry_delta: 0,
3479 htlc_minimum_msat: 0,
3480 htlc_maximum_msat: OptionalField::Present(60_000),
3482 fee_proportional_millionths: 0,
3483 excess_data: Vec::new()
3486 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3487 // (total capacity 180 sats).
3488 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3489 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3490 short_channel_id: 2,
3493 cltv_expiry_delta: 0,
3494 htlc_minimum_msat: 0,
3495 htlc_maximum_msat: OptionalField::Present(200_000),
3497 fee_proportional_millionths: 0,
3498 excess_data: Vec::new()
3500 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3502 short_channel_id: 4,
3505 cltv_expiry_delta: 0,
3506 htlc_minimum_msat: 0,
3507 htlc_maximum_msat: OptionalField::Present(180_000),
3509 fee_proportional_millionths: 0,
3510 excess_data: Vec::new()
3514 // Attempt to route more than available results in a failure.
3515 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3516 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3517 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3518 } else { panic!(); }
3522 // Now, attempt to route 250 sats (just a bit below the capacity).
3523 // Our algorithm should provide us with these 3 paths.
3524 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3525 assert_eq!(route.paths.len(), 3);
3526 let mut total_amount_paid_msat = 0;
3527 for path in &route.paths {
3528 assert_eq!(path.len(), 2);
3529 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3530 total_amount_paid_msat += path.last().unwrap().fee_msat;
3532 assert_eq!(total_amount_paid_msat, 250_000);
3536 // Attempt to route an exact amount is also fine
3537 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3538 assert_eq!(route.paths.len(), 3);
3539 let mut total_amount_paid_msat = 0;
3540 for path in &route.paths {
3541 assert_eq!(path.len(), 2);
3542 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3543 total_amount_paid_msat += path.last().unwrap().fee_msat;
3545 assert_eq!(total_amount_paid_msat, 290_000);
3550 fn long_mpp_route_test() {
3551 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3552 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3553 let scorer = Scorer::new(0);
3554 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3556 // We need a route consisting of 3 paths:
3557 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3558 // Note that these paths overlap (channels 5, 12, 13).
3559 // We will route 300 sats.
3560 // Each path will have 100 sats capacity, those channels which
3561 // are used twice will have 200 sats capacity.
3563 // Disable other potential paths.
3564 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3565 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3566 short_channel_id: 2,
3569 cltv_expiry_delta: 0,
3570 htlc_minimum_msat: 0,
3571 htlc_maximum_msat: OptionalField::Present(100_000),
3573 fee_proportional_millionths: 0,
3574 excess_data: Vec::new()
3576 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3577 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3578 short_channel_id: 7,
3581 cltv_expiry_delta: 0,
3582 htlc_minimum_msat: 0,
3583 htlc_maximum_msat: OptionalField::Present(100_000),
3585 fee_proportional_millionths: 0,
3586 excess_data: Vec::new()
3589 // Path via {node0, node2} is channels {1, 3, 5}.
3590 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3592 short_channel_id: 1,
3595 cltv_expiry_delta: 0,
3596 htlc_minimum_msat: 0,
3597 htlc_maximum_msat: OptionalField::Present(100_000),
3599 fee_proportional_millionths: 0,
3600 excess_data: Vec::new()
3602 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3603 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3604 short_channel_id: 3,
3607 cltv_expiry_delta: 0,
3608 htlc_minimum_msat: 0,
3609 htlc_maximum_msat: OptionalField::Present(100_000),
3611 fee_proportional_millionths: 0,
3612 excess_data: Vec::new()
3615 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3616 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3617 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3618 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3619 short_channel_id: 5,
3622 cltv_expiry_delta: 0,
3623 htlc_minimum_msat: 0,
3624 htlc_maximum_msat: OptionalField::Present(200_000),
3626 fee_proportional_millionths: 0,
3627 excess_data: Vec::new()
3630 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3631 // Add 100 sats to the capacities of {12, 13}, because these channels
3632 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3633 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3634 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3635 short_channel_id: 12,
3638 cltv_expiry_delta: 0,
3639 htlc_minimum_msat: 0,
3640 htlc_maximum_msat: OptionalField::Present(200_000),
3642 fee_proportional_millionths: 0,
3643 excess_data: Vec::new()
3645 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3646 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3647 short_channel_id: 13,
3650 cltv_expiry_delta: 0,
3651 htlc_minimum_msat: 0,
3652 htlc_maximum_msat: OptionalField::Present(200_000),
3654 fee_proportional_millionths: 0,
3655 excess_data: Vec::new()
3658 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3659 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3660 short_channel_id: 6,
3663 cltv_expiry_delta: 0,
3664 htlc_minimum_msat: 0,
3665 htlc_maximum_msat: OptionalField::Present(100_000),
3667 fee_proportional_millionths: 0,
3668 excess_data: Vec::new()
3670 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3672 short_channel_id: 11,
3675 cltv_expiry_delta: 0,
3676 htlc_minimum_msat: 0,
3677 htlc_maximum_msat: OptionalField::Present(100_000),
3679 fee_proportional_millionths: 0,
3680 excess_data: Vec::new()
3683 // Path via {node7, node2} is channels {12, 13, 5}.
3684 // We already limited them to 200 sats (they are used twice for 100 sats).
3685 // Nothing to do here.
3688 // Attempt to route more than available results in a failure.
3689 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3690 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3691 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3692 } else { panic!(); }
3696 // Now, attempt to route 300 sats (exact amount we can route).
3697 // Our algorithm should provide us with these 3 paths, 100 sats each.
3698 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3699 assert_eq!(route.paths.len(), 3);
3701 let mut total_amount_paid_msat = 0;
3702 for path in &route.paths {
3703 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3704 total_amount_paid_msat += path.last().unwrap().fee_msat;
3706 assert_eq!(total_amount_paid_msat, 300_000);
3712 fn mpp_cheaper_route_test() {
3713 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3714 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3715 let scorer = Scorer::new(0);
3716 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3718 // This test checks that if we have two cheaper paths and one more expensive path,
3719 // so that liquidity-wise any 2 of 3 combination is sufficient,
3720 // two cheaper paths will be taken.
3721 // These paths have equal available liquidity.
3723 // We need a combination of 3 paths:
3724 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3725 // Note that these paths overlap (channels 5, 12, 13).
3726 // Each path will have 100 sats capacity, those channels which
3727 // are used twice will have 200 sats capacity.
3729 // Disable other potential paths.
3730 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3731 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3732 short_channel_id: 2,
3735 cltv_expiry_delta: 0,
3736 htlc_minimum_msat: 0,
3737 htlc_maximum_msat: OptionalField::Present(100_000),
3739 fee_proportional_millionths: 0,
3740 excess_data: Vec::new()
3742 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3743 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3744 short_channel_id: 7,
3747 cltv_expiry_delta: 0,
3748 htlc_minimum_msat: 0,
3749 htlc_maximum_msat: OptionalField::Present(100_000),
3751 fee_proportional_millionths: 0,
3752 excess_data: Vec::new()
3755 // Path via {node0, node2} is channels {1, 3, 5}.
3756 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3758 short_channel_id: 1,
3761 cltv_expiry_delta: 0,
3762 htlc_minimum_msat: 0,
3763 htlc_maximum_msat: OptionalField::Present(100_000),
3765 fee_proportional_millionths: 0,
3766 excess_data: Vec::new()
3768 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3769 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3770 short_channel_id: 3,
3773 cltv_expiry_delta: 0,
3774 htlc_minimum_msat: 0,
3775 htlc_maximum_msat: OptionalField::Present(100_000),
3777 fee_proportional_millionths: 0,
3778 excess_data: Vec::new()
3781 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3782 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3783 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3784 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3785 short_channel_id: 5,
3788 cltv_expiry_delta: 0,
3789 htlc_minimum_msat: 0,
3790 htlc_maximum_msat: OptionalField::Present(200_000),
3792 fee_proportional_millionths: 0,
3793 excess_data: Vec::new()
3796 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3797 // Add 100 sats to the capacities of {12, 13}, because these channels
3798 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3799 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3800 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3801 short_channel_id: 12,
3804 cltv_expiry_delta: 0,
3805 htlc_minimum_msat: 0,
3806 htlc_maximum_msat: OptionalField::Present(200_000),
3808 fee_proportional_millionths: 0,
3809 excess_data: Vec::new()
3811 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3812 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3813 short_channel_id: 13,
3816 cltv_expiry_delta: 0,
3817 htlc_minimum_msat: 0,
3818 htlc_maximum_msat: OptionalField::Present(200_000),
3820 fee_proportional_millionths: 0,
3821 excess_data: Vec::new()
3824 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3825 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3826 short_channel_id: 6,
3829 cltv_expiry_delta: 0,
3830 htlc_minimum_msat: 0,
3831 htlc_maximum_msat: OptionalField::Present(100_000),
3832 fee_base_msat: 1_000,
3833 fee_proportional_millionths: 0,
3834 excess_data: Vec::new()
3836 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3837 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3838 short_channel_id: 11,
3841 cltv_expiry_delta: 0,
3842 htlc_minimum_msat: 0,
3843 htlc_maximum_msat: OptionalField::Present(100_000),
3845 fee_proportional_millionths: 0,
3846 excess_data: Vec::new()
3849 // Path via {node7, node2} is channels {12, 13, 5}.
3850 // We already limited them to 200 sats (they are used twice for 100 sats).
3851 // Nothing to do here.
3854 // Now, attempt to route 180 sats.
3855 // Our algorithm should provide us with these 2 paths.
3856 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3857 assert_eq!(route.paths.len(), 2);
3859 let mut total_value_transferred_msat = 0;
3860 let mut total_paid_msat = 0;
3861 for path in &route.paths {
3862 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3863 total_value_transferred_msat += path.last().unwrap().fee_msat;
3865 total_paid_msat += hop.fee_msat;
3868 // If we paid fee, this would be higher.
3869 assert_eq!(total_value_transferred_msat, 180_000);
3870 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3871 assert_eq!(total_fees_paid, 0);
3876 fn fees_on_mpp_route_test() {
3877 // This test makes sure that MPP algorithm properly takes into account
3878 // fees charged on the channels, by making the fees impactful:
3879 // if the fee is not properly accounted for, the behavior is different.
3880 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3881 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3882 let scorer = Scorer::new(0);
3883 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3885 // We need a route consisting of 2 paths:
3886 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3887 // We will route 200 sats, Each path will have 100 sats capacity.
3889 // This test is not particularly stable: e.g.,
3890 // there's a way to route via {node0, node2, node4}.
3891 // It works while pathfinding is deterministic, but can be broken otherwise.
3892 // It's fine to ignore this concern for now.
3894 // Disable other potential paths.
3895 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3896 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3897 short_channel_id: 2,
3900 cltv_expiry_delta: 0,
3901 htlc_minimum_msat: 0,
3902 htlc_maximum_msat: OptionalField::Present(100_000),
3904 fee_proportional_millionths: 0,
3905 excess_data: Vec::new()
3908 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3909 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3910 short_channel_id: 7,
3913 cltv_expiry_delta: 0,
3914 htlc_minimum_msat: 0,
3915 htlc_maximum_msat: OptionalField::Present(100_000),
3917 fee_proportional_millionths: 0,
3918 excess_data: Vec::new()
3921 // Path via {node0, node2} is channels {1, 3, 5}.
3922 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3924 short_channel_id: 1,
3927 cltv_expiry_delta: 0,
3928 htlc_minimum_msat: 0,
3929 htlc_maximum_msat: OptionalField::Present(100_000),
3931 fee_proportional_millionths: 0,
3932 excess_data: Vec::new()
3934 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3935 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3936 short_channel_id: 3,
3939 cltv_expiry_delta: 0,
3940 htlc_minimum_msat: 0,
3941 htlc_maximum_msat: OptionalField::Present(100_000),
3943 fee_proportional_millionths: 0,
3944 excess_data: Vec::new()
3947 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3948 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3949 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3950 short_channel_id: 5,
3953 cltv_expiry_delta: 0,
3954 htlc_minimum_msat: 0,
3955 htlc_maximum_msat: OptionalField::Present(100_000),
3957 fee_proportional_millionths: 0,
3958 excess_data: Vec::new()
3961 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3962 // All channels should be 100 sats capacity. But for the fee experiment,
3963 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3964 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3965 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3966 // so no matter how large are other channels,
3967 // the whole path will be limited by 100 sats with just these 2 conditions:
3968 // - channel 12 capacity is 250 sats
3969 // - fee for channel 6 is 150 sats
3970 // Let's test this by enforcing these 2 conditions and removing other limits.
3971 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3972 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3973 short_channel_id: 12,
3976 cltv_expiry_delta: 0,
3977 htlc_minimum_msat: 0,
3978 htlc_maximum_msat: OptionalField::Present(250_000),
3980 fee_proportional_millionths: 0,
3981 excess_data: Vec::new()
3983 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3984 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3985 short_channel_id: 13,
3988 cltv_expiry_delta: 0,
3989 htlc_minimum_msat: 0,
3990 htlc_maximum_msat: OptionalField::Absent,
3992 fee_proportional_millionths: 0,
3993 excess_data: Vec::new()
3996 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3997 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3998 short_channel_id: 6,
4001 cltv_expiry_delta: 0,
4002 htlc_minimum_msat: 0,
4003 htlc_maximum_msat: OptionalField::Absent,
4004 fee_base_msat: 150_000,
4005 fee_proportional_millionths: 0,
4006 excess_data: Vec::new()
4008 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4009 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4010 short_channel_id: 11,
4013 cltv_expiry_delta: 0,
4014 htlc_minimum_msat: 0,
4015 htlc_maximum_msat: OptionalField::Absent,
4017 fee_proportional_millionths: 0,
4018 excess_data: Vec::new()
4022 // Attempt to route more than available results in a failure.
4023 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4024 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4025 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4026 } else { panic!(); }
4030 // Now, attempt to route 200 sats (exact amount we can route).
4031 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4032 assert_eq!(route.paths.len(), 2);
4034 let mut total_amount_paid_msat = 0;
4035 for path in &route.paths {
4036 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4037 total_amount_paid_msat += path.last().unwrap().fee_msat;
4039 assert_eq!(total_amount_paid_msat, 200_000);
4040 assert_eq!(route.get_total_fees(), 150_000);
4046 fn drop_lowest_channel_mpp_route_test() {
4047 // This test checks that low-capacity channel is dropped when after
4048 // path finding we realize that we found more capacity than we need.
4049 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4050 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4051 let scorer = Scorer::new(0);
4052 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4054 // We need a route consisting of 3 paths:
4055 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4057 // The first and the second paths should be sufficient, but the third should be
4058 // cheaper, so that we select it but drop later.
4060 // First, we set limits on these (previously unlimited) channels.
4061 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4063 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4064 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4065 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4066 short_channel_id: 1,
4069 cltv_expiry_delta: 0,
4070 htlc_minimum_msat: 0,
4071 htlc_maximum_msat: OptionalField::Present(100_000),
4073 fee_proportional_millionths: 0,
4074 excess_data: Vec::new()
4076 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4077 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4078 short_channel_id: 3,
4081 cltv_expiry_delta: 0,
4082 htlc_minimum_msat: 0,
4083 htlc_maximum_msat: OptionalField::Present(50_000),
4085 fee_proportional_millionths: 0,
4086 excess_data: Vec::new()
4089 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4090 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4092 short_channel_id: 12,
4095 cltv_expiry_delta: 0,
4096 htlc_minimum_msat: 0,
4097 htlc_maximum_msat: OptionalField::Present(60_000),
4099 fee_proportional_millionths: 0,
4100 excess_data: Vec::new()
4102 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4104 short_channel_id: 13,
4107 cltv_expiry_delta: 0,
4108 htlc_minimum_msat: 0,
4109 htlc_maximum_msat: OptionalField::Present(60_000),
4111 fee_proportional_millionths: 0,
4112 excess_data: Vec::new()
4115 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4116 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4118 short_channel_id: 2,
4121 cltv_expiry_delta: 0,
4122 htlc_minimum_msat: 0,
4123 htlc_maximum_msat: OptionalField::Present(20_000),
4125 fee_proportional_millionths: 0,
4126 excess_data: Vec::new()
4128 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4129 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4130 short_channel_id: 4,
4133 cltv_expiry_delta: 0,
4134 htlc_minimum_msat: 0,
4135 htlc_maximum_msat: OptionalField::Present(20_000),
4137 fee_proportional_millionths: 0,
4138 excess_data: Vec::new()
4142 // Attempt to route more than available results in a failure.
4143 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4144 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4145 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4146 } else { panic!(); }
4150 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4151 // Our algorithm should provide us with these 3 paths.
4152 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4153 assert_eq!(route.paths.len(), 3);
4154 let mut total_amount_paid_msat = 0;
4155 for path in &route.paths {
4156 assert_eq!(path.len(), 2);
4157 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4158 total_amount_paid_msat += path.last().unwrap().fee_msat;
4160 assert_eq!(total_amount_paid_msat, 125_000);
4164 // Attempt to route without the last small cheap channel
4165 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4166 assert_eq!(route.paths.len(), 2);
4167 let mut total_amount_paid_msat = 0;
4168 for path in &route.paths {
4169 assert_eq!(path.len(), 2);
4170 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4171 total_amount_paid_msat += path.last().unwrap().fee_msat;
4173 assert_eq!(total_amount_paid_msat, 90_000);
4178 fn min_criteria_consistency() {
4179 // Test that we don't use an inconsistent metric between updating and walking nodes during
4180 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4181 // was updated with a different criterion from the heap sorting, resulting in loops in
4182 // calculated paths. We test for that specific case here.
4184 // We construct a network that looks like this:
4186 // node2 -1(3)2- node3
4190 // node1 -1(5)2- node4 -1(1)2- node6
4196 // We create a loop on the side of our real path - our destination is node 6, with a
4197 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4198 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4199 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4200 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4201 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4202 // "previous hop" being set to node 3, creating a loop in the path.
4203 let secp_ctx = Secp256k1::new();
4204 let logger = Arc::new(test_utils::TestLogger::new());
4205 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4206 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
4207 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4208 let scorer = Scorer::new(0);
4209 let payee = Payee::new(nodes[6]);
4211 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
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: 6,
4217 cltv_expiry_delta: (6 << 8) | 0,
4218 htlc_minimum_msat: 0,
4219 htlc_maximum_msat: OptionalField::Absent,
4221 fee_proportional_millionths: 0,
4222 excess_data: Vec::new()
4224 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4226 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4227 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4229 short_channel_id: 5,
4232 cltv_expiry_delta: (5 << 8) | 0,
4233 htlc_minimum_msat: 0,
4234 htlc_maximum_msat: OptionalField::Absent,
4236 fee_proportional_millionths: 0,
4237 excess_data: Vec::new()
4239 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4241 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4242 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4243 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4244 short_channel_id: 4,
4247 cltv_expiry_delta: (4 << 8) | 0,
4248 htlc_minimum_msat: 0,
4249 htlc_maximum_msat: OptionalField::Absent,
4251 fee_proportional_millionths: 0,
4252 excess_data: Vec::new()
4254 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4256 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4257 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4259 short_channel_id: 3,
4262 cltv_expiry_delta: (3 << 8) | 0,
4263 htlc_minimum_msat: 0,
4264 htlc_maximum_msat: OptionalField::Absent,
4266 fee_proportional_millionths: 0,
4267 excess_data: Vec::new()
4269 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4271 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4272 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4273 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4274 short_channel_id: 2,
4277 cltv_expiry_delta: (2 << 8) | 0,
4278 htlc_minimum_msat: 0,
4279 htlc_maximum_msat: OptionalField::Absent,
4281 fee_proportional_millionths: 0,
4282 excess_data: Vec::new()
4285 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4286 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4288 short_channel_id: 1,
4291 cltv_expiry_delta: (1 << 8) | 0,
4292 htlc_minimum_msat: 100,
4293 htlc_maximum_msat: OptionalField::Absent,
4295 fee_proportional_millionths: 0,
4296 excess_data: Vec::new()
4298 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4301 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4302 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4303 assert_eq!(route.paths.len(), 1);
4304 assert_eq!(route.paths[0].len(), 3);
4306 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4307 assert_eq!(route.paths[0][0].short_channel_id, 6);
4308 assert_eq!(route.paths[0][0].fee_msat, 100);
4309 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4310 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4311 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4313 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4314 assert_eq!(route.paths[0][1].short_channel_id, 5);
4315 assert_eq!(route.paths[0][1].fee_msat, 0);
4316 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4317 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4318 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4320 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4321 assert_eq!(route.paths[0][2].short_channel_id, 1);
4322 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4323 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4324 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4325 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4331 fn exact_fee_liquidity_limit() {
4332 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4333 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4334 // we calculated fees on a higher value, resulting in us ignoring such paths.
4335 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4336 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4337 let scorer = Scorer::new(0);
4338 let payee = Payee::new(nodes[2]);
4340 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4342 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4343 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4344 short_channel_id: 2,
4347 cltv_expiry_delta: 0,
4348 htlc_minimum_msat: 0,
4349 htlc_maximum_msat: OptionalField::Present(85_000),
4351 fee_proportional_millionths: 0,
4352 excess_data: Vec::new()
4355 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4356 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4357 short_channel_id: 12,
4360 cltv_expiry_delta: (4 << 8) | 1,
4361 htlc_minimum_msat: 0,
4362 htlc_maximum_msat: OptionalField::Present(270_000),
4364 fee_proportional_millionths: 1000000,
4365 excess_data: Vec::new()
4369 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4370 // 200% fee charged channel 13 in the 1-to-2 direction.
4371 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4372 assert_eq!(route.paths.len(), 1);
4373 assert_eq!(route.paths[0].len(), 2);
4375 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4376 assert_eq!(route.paths[0][0].short_channel_id, 12);
4377 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4378 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4379 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4380 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4382 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4383 assert_eq!(route.paths[0][1].short_channel_id, 13);
4384 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4385 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4386 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4387 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4392 fn htlc_max_reduction_below_min() {
4393 // Test that if, while walking the graph, we reduce the value being sent to meet an
4394 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4395 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4396 // resulting in us thinking there is no possible path, even if other paths exist.
4397 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4398 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4399 let scorer = Scorer::new(0);
4400 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4402 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4403 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4404 // then try to send 90_000.
4405 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4406 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4407 short_channel_id: 2,
4410 cltv_expiry_delta: 0,
4411 htlc_minimum_msat: 0,
4412 htlc_maximum_msat: OptionalField::Present(80_000),
4414 fee_proportional_millionths: 0,
4415 excess_data: Vec::new()
4417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4419 short_channel_id: 4,
4422 cltv_expiry_delta: (4 << 8) | 1,
4423 htlc_minimum_msat: 90_000,
4424 htlc_maximum_msat: OptionalField::Absent,
4426 fee_proportional_millionths: 0,
4427 excess_data: Vec::new()
4431 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4432 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4433 // expensive) channels 12-13 path.
4434 let route = get_route(&our_id, &payee, &net_graph_msg_handler.network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4435 assert_eq!(route.paths.len(), 1);
4436 assert_eq!(route.paths[0].len(), 2);
4438 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4439 assert_eq!(route.paths[0][0].short_channel_id, 12);
4440 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4441 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4442 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4443 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4445 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4446 assert_eq!(route.paths[0][1].short_channel_id, 13);
4447 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4448 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4449 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4450 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4455 fn multiple_direct_first_hops() {
4456 // Previously we'd only ever considered one first hop path per counterparty.
4457 // However, as we don't restrict users to one channel per peer, we really need to support
4458 // looking at all first hop paths.
4459 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4460 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4461 // route over multiple channels with the same first hop.
4462 let secp_ctx = Secp256k1::new();
4463 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4464 let logger = Arc::new(test_utils::TestLogger::new());
4465 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4466 let scorer = Scorer::new(0);
4467 let payee = Payee::new(nodes[0]).with_features(InvoiceFeatures::known());
4470 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4471 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4472 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4473 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4474 assert_eq!(route.paths.len(), 1);
4475 assert_eq!(route.paths[0].len(), 1);
4477 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4478 assert_eq!(route.paths[0][0].short_channel_id, 3);
4479 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4482 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4483 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4484 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4485 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4486 assert_eq!(route.paths.len(), 2);
4487 assert_eq!(route.paths[0].len(), 1);
4488 assert_eq!(route.paths[1].len(), 1);
4490 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4491 assert_eq!(route.paths[0][0].short_channel_id, 3);
4492 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4494 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4495 assert_eq!(route.paths[1][0].short_channel_id, 2);
4496 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4501 fn prefers_shorter_route_with_higher_fees() {
4502 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4503 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4504 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4506 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4507 let scorer = Scorer::new(0);
4508 let route = get_route(
4509 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4510 Arc::clone(&logger), &scorer
4512 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4514 assert_eq!(route.get_total_fees(), 100);
4515 assert_eq!(route.get_total_amount(), 100);
4516 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4518 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4519 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4520 let scorer = Scorer::new(100);
4521 let route = get_route(
4522 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4523 Arc::clone(&logger), &scorer
4525 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4527 assert_eq!(route.get_total_fees(), 300);
4528 assert_eq!(route.get_total_amount(), 100);
4529 assert_eq!(path, vec![2, 4, 7, 10]);
4532 struct BadChannelScorer {
4533 short_channel_id: u64,
4536 impl routing::Score for BadChannelScorer {
4537 fn channel_penalty_msat(&self, short_channel_id: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4538 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4541 fn payment_path_failed(&mut self, _path: &Vec<RouteHop>, _short_channel_id: u64) {}
4544 struct BadNodeScorer {
4548 impl routing::Score for BadNodeScorer {
4549 fn channel_penalty_msat(&self, _short_channel_id: u64, _source: &NodeId, target: &NodeId) -> u64 {
4550 if *target == self.node_id { u64::max_value() } else { 0 }
4553 fn payment_path_failed(&mut self, _path: &Vec<RouteHop>, _short_channel_id: u64) {}
4557 fn avoids_routing_through_bad_channels_and_nodes() {
4558 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4559 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4560 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4562 // A path to nodes[6] exists when no penalties are applied to any channel.
4563 let scorer = Scorer::new(0);
4564 let route = get_route(
4565 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4566 Arc::clone(&logger), &scorer
4568 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4570 assert_eq!(route.get_total_fees(), 100);
4571 assert_eq!(route.get_total_amount(), 100);
4572 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4574 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4575 let scorer = BadChannelScorer { short_channel_id: 6 };
4576 let route = get_route(
4577 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4578 Arc::clone(&logger), &scorer
4580 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4582 assert_eq!(route.get_total_fees(), 300);
4583 assert_eq!(route.get_total_amount(), 100);
4584 assert_eq!(path, vec![2, 4, 7, 10]);
4586 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4587 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4589 &our_id, &payee, &net_graph_msg_handler.network_graph, None, 100, 42,
4590 Arc::clone(&logger), &scorer
4592 Err(LightningError { err, .. } ) => {
4593 assert_eq!(err, "Failed to find a path to the given destination");
4595 Ok(_) => panic!("Expected error"),
4600 fn total_fees_single_path() {
4604 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4605 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4606 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4609 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4610 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4611 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4614 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4615 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4616 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4622 assert_eq!(route.get_total_fees(), 250);
4623 assert_eq!(route.get_total_amount(), 225);
4627 fn total_fees_multi_path() {
4631 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4632 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4633 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4636 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4637 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4638 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4642 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4643 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4644 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4647 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4648 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4649 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4655 assert_eq!(route.get_total_fees(), 200);
4656 assert_eq!(route.get_total_amount(), 300);
4660 fn total_empty_route_no_panic() {
4661 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4662 // would both panic if the route was completely empty. We test to ensure they return 0
4663 // here, even though its somewhat nonsensical as a route.
4664 let route = Route { paths: Vec::new(), payee: None };
4666 assert_eq!(route.get_total_fees(), 0);
4667 assert_eq!(route.get_total_amount(), 0);
4670 #[cfg(not(feature = "no-std"))]
4671 pub(super) fn random_init_seed() -> u64 {
4672 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4673 use core::hash::{BuildHasher, Hasher};
4674 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4675 println!("Using seed of {}", seed);
4678 #[cfg(not(feature = "no-std"))]
4679 use util::ser::Readable;
4682 #[cfg(not(feature = "no-std"))]
4683 fn generate_routes() {
4684 let mut d = match super::test_utils::get_route_file() {
4691 let graph = NetworkGraph::read(&mut d).unwrap();
4692 let scorer = Scorer::new(0);
4694 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4695 let mut seed = random_init_seed() as usize;
4696 let nodes = graph.read_only().nodes().clone();
4697 'load_endpoints: for _ in 0..10 {
4699 seed = seed.overflowing_mul(0xdeadbeef).0;
4700 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4701 seed = seed.overflowing_mul(0xdeadbeef).0;
4702 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4703 let payee = Payee::new(dst);
4704 let amt = seed as u64 % 200_000_000;
4705 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4706 continue 'load_endpoints;
4713 #[cfg(not(feature = "no-std"))]
4714 fn generate_routes_mpp() {
4715 let mut d = match super::test_utils::get_route_file() {
4722 let graph = NetworkGraph::read(&mut d).unwrap();
4723 let scorer = Scorer::new(0);
4725 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4726 let mut seed = random_init_seed() as usize;
4727 let nodes = graph.read_only().nodes().clone();
4728 'load_endpoints: for _ in 0..10 {
4730 seed = seed.overflowing_mul(0xdeadbeef).0;
4731 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4732 seed = seed.overflowing_mul(0xdeadbeef).0;
4733 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4734 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4735 let amt = seed as u64 % 200_000_000;
4736 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4737 continue 'load_endpoints;
4744 #[cfg(all(test, not(feature = "no-std")))]
4745 pub(crate) mod test_utils {
4747 /// Tries to open a network graph file, or panics with a URL to fetch it.
4748 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4749 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4750 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4751 .or_else(|_| { // Fall back to guessing based on the binary location
4752 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4753 let mut path = std::env::current_exe().unwrap();
4754 path.pop(); // lightning-...
4756 path.pop(); // debug
4757 path.pop(); // target
4758 path.push("lightning");
4759 path.push("net_graph-2021-05-31.bin");
4760 eprintln!("{}", path.to_str().unwrap());
4763 .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");
4764 #[cfg(require_route_graph_test)]
4765 return Ok(res.unwrap());
4766 #[cfg(not(require_route_graph_test))]
4771 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4774 use routing::scorer::Scorer;
4775 use util::logger::{Logger, Record};
4779 struct DummyLogger {}
4780 impl Logger for DummyLogger {
4781 fn log(&self, _record: &Record) {}
4785 fn generate_routes(bench: &mut Bencher) {
4786 let mut d = test_utils::get_route_file().unwrap();
4787 let graph = NetworkGraph::read(&mut d).unwrap();
4788 let nodes = graph.read_only().nodes().clone();
4789 let scorer = Scorer::new(0);
4791 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4792 let mut path_endpoints = Vec::new();
4793 let mut seed: usize = 0xdeadbeef;
4794 'load_endpoints: for _ in 0..100 {
4797 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4799 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4800 let payee = Payee::new(dst);
4801 let amt = seed as u64 % 1_000_000;
4802 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4803 path_endpoints.push((src, dst, amt));
4804 continue 'load_endpoints;
4809 // ...then benchmark finding paths between the nodes we learned.
4812 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4813 let payee = Payee::new(dst);
4814 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4820 fn generate_mpp_routes(bench: &mut Bencher) {
4821 let mut d = test_utils::get_route_file().unwrap();
4822 let graph = NetworkGraph::read(&mut d).unwrap();
4823 let nodes = graph.read_only().nodes().clone();
4824 let scorer = Scorer::new(0);
4826 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4827 let mut path_endpoints = Vec::new();
4828 let mut seed: usize = 0xdeadbeef;
4829 'load_endpoints: for _ in 0..100 {
4832 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4834 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4835 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4836 let amt = seed as u64 % 1_000_000;
4837 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4838 path_endpoints.push((src, dst, amt));
4839 continue 'load_endpoints;
4844 // ...then benchmark finding paths between the nodes we learned.
4847 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4848 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4849 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());