1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::network_graph::{NetworkGraph, RoutingFees};
21 use util::ser::{Writeable, Readable};
22 use util::logger::Logger;
25 use alloc::collections::BinaryHeap;
27 use std::collections::HashMap;
31 #[derive(Clone, PartialEq)]
33 /// The node_id of the node at this hop.
34 pub pubkey: PublicKey,
35 /// The node_announcement features of the node at this hop. For the last hop, these may be
36 /// amended to match the features present in the invoice this node generated.
37 pub node_features: NodeFeatures,
38 /// The channel that should be used from the previous hop to reach this node.
39 pub short_channel_id: u64,
40 /// The channel_announcement features of the channel that should be used from the previous hop
41 /// to reach this node.
42 pub channel_features: ChannelFeatures,
43 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
44 /// For the last hop, this should be the full value of the payment (might be more than
45 /// requested if we had to match htlc_minimum_msat).
47 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
48 /// expected at the destination, in excess of the current block height.
49 pub cltv_expiry_delta: u32,
52 impl_writeable_tlv_based!(RouteHop, {
55 (4, short_channel_id),
56 (6, channel_features),
58 (10, cltv_expiry_delta),
61 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
62 /// it can take multiple paths. Each path is composed of one or more hops through the network.
63 #[derive(Clone, PartialEq)]
65 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
66 /// last RouteHop in each path must be the same.
67 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
68 /// destination. Thus, this must always be at least length one. While the maximum length of any
69 /// given path is variable, keeping the length of any path to less than 20 should currently
70 /// ensure it is viable.
71 pub paths: Vec<Vec<RouteHop>>,
74 const SERIALIZATION_VERSION: u8 = 1;
75 const MIN_SERIALIZATION_VERSION: u8 = 1;
77 impl Writeable for Route {
78 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
79 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
80 (self.paths.len() as u64).write(writer)?;
81 for hops in self.paths.iter() {
82 (hops.len() as u8).write(writer)?;
83 for hop in hops.iter() {
87 write_tlv_fields!(writer, {}, {});
92 impl Readable for Route {
93 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
94 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
95 let path_count: u64 = Readable::read(reader)?;
96 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
97 for _ in 0..path_count {
98 let hop_count: u8 = Readable::read(reader)?;
99 let mut hops = Vec::with_capacity(hop_count as usize);
100 for _ in 0..hop_count {
101 hops.push(Readable::read(reader)?);
105 read_tlv_fields!(reader, {}, {});
110 /// A list of hops along a payment path terminating with a channel to the recipient.
111 #[derive(Eq, PartialEq, Debug, Clone)]
112 pub struct RouteHint(pub Vec<RouteHintHop>);
114 /// A channel descriptor for a hop along a payment path.
115 #[derive(Eq, PartialEq, Debug, Clone)]
116 pub struct RouteHintHop {
117 /// The node_id of the non-target end of the route
118 pub src_node_id: PublicKey,
119 /// The short_channel_id of this channel
120 pub short_channel_id: u64,
121 /// The fees which must be paid to use this channel
122 pub fees: RoutingFees,
123 /// The difference in CLTV values between this node and the next node.
124 pub cltv_expiry_delta: u16,
125 /// The minimum value, in msat, which must be relayed to the next hop.
126 pub htlc_minimum_msat: Option<u64>,
127 /// The maximum value in msat available for routing with a single HTLC.
128 pub htlc_maximum_msat: Option<u64>,
131 #[derive(Eq, PartialEq)]
132 struct RouteGraphNode {
134 lowest_fee_to_peer_through_node: u64,
135 lowest_fee_to_node: u64,
136 // The maximum value a yet-to-be-constructed payment path might flow through this node.
137 // This value is upper-bounded by us by:
138 // - how much is needed for a path being constructed
139 // - how much value can channels following this node (up to the destination) can contribute,
140 // considering their capacity and fees
141 value_contribution_msat: u64,
142 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
143 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
144 path_htlc_minimum_msat: u64,
147 impl cmp::Ord for RouteGraphNode {
148 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
149 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
150 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
151 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
155 impl cmp::PartialOrd for RouteGraphNode {
156 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
157 Some(self.cmp(other))
161 struct DummyDirectionalChannelInfo {
162 cltv_expiry_delta: u32,
163 htlc_minimum_msat: u64,
164 htlc_maximum_msat: Option<u64>,
168 /// It's useful to keep track of the hops associated with the fees required to use them,
169 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
170 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
171 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
173 struct PathBuildingHop<'a> {
174 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
175 // Note that node_features is calculated separately after our initial graph walk.
177 short_channel_id: u64,
178 channel_features: &'a ChannelFeatures,
180 cltv_expiry_delta: u32,
182 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
183 src_lowest_inbound_fees: RoutingFees,
184 /// Fees of the channel used in this hop.
185 channel_fees: RoutingFees,
186 /// All the fees paid *after* this channel on the way to the destination
187 next_hops_fee_msat: u64,
188 /// Fee paid for the use of the current channel (see channel_fees).
189 /// The value will be actually deducted from the counterparty balance on the previous link.
190 hop_use_fee_msat: u64,
191 /// Used to compare channels when choosing the for routing.
192 /// Includes paying for the use of a hop and the following hops, as well as
193 /// an estimated cost of reaching this hop.
194 /// Might get stale when fees are recomputed. Primarily for internal use.
196 /// This is useful for update_value_and_recompute_fees to make sure
197 /// we don't fall below the minimum. Should not be updated manually and
198 /// generally should not be accessed.
199 htlc_minimum_msat: u64,
200 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
201 /// walk and may be invalid thereafter.
202 path_htlc_minimum_msat: u64,
203 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
204 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
205 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
206 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
207 /// avoid processing them again.
209 #[cfg(any(test, feature = "fuzztarget"))]
210 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
211 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
212 // value_contribution_msat, which requires tracking it here. See comments below where it is
213 // used for more info.
214 value_contribution_msat: u64,
217 // Instantiated with a list of hops with correct data in them collected during path finding,
218 // an instance of this struct should be further modified only via given methods.
220 struct PaymentPath<'a> {
221 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
224 impl<'a> PaymentPath<'a> {
225 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
226 fn get_value_msat(&self) -> u64 {
227 self.hops.last().unwrap().0.fee_msat
230 fn get_total_fee_paid_msat(&self) -> u64 {
231 if self.hops.len() < 1 {
235 // Can't use next_hops_fee_msat because it gets outdated.
236 for (i, (hop, _)) in self.hops.iter().enumerate() {
237 if i != self.hops.len() - 1 {
238 result += hop.fee_msat;
244 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
245 // to change fees may result in an inconsistency.
247 // Sometimes we call this function right after constructing a path which is inconsistent in
248 // that it the value being transferred has decreased while we were doing path finding, leading
249 // to the fees being paid not lining up with the actual limits.
251 // Note that this function is not aware of the available_liquidity limit, and thus does not
252 // support increasing the value being transferred.
253 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
254 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
256 let mut total_fee_paid_msat = 0 as u64;
257 for i in (0..self.hops.len()).rev() {
258 let last_hop = i == self.hops.len() - 1;
260 // For non-last-hop, this value will represent the fees paid on the current hop. It
261 // will consist of the fees for the use of the next hop, and extra fees to match
262 // htlc_minimum_msat of the current channel. Last hop is handled separately.
263 let mut cur_hop_fees_msat = 0;
265 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
268 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
269 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
270 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
271 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
272 // set it too high just to maliciously take more fees by exploiting this
273 // match htlc_minimum_msat logic.
274 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
275 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
276 // Note that there is a risk that *previous hops* (those closer to us, as we go
277 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
279 // This might make us end up with a broken route, although this should be super-rare
280 // in practice, both because of how healthy channels look like, and how we pick
281 // channels in add_entry.
282 // Also, this can't be exploited more heavily than *announce a free path and fail
284 cur_hop_transferred_amount_msat += extra_fees_msat;
285 total_fee_paid_msat += extra_fees_msat;
286 cur_hop_fees_msat += extra_fees_msat;
290 // Final hop is a special case: it usually has just value_msat (by design), but also
291 // it still could overpay for the htlc_minimum_msat.
292 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
294 // Propagate updated fees for the use of the channels to one hop back, where they
295 // will be actually paid (fee_msat). The last hop is handled above separately.
296 cur_hop.fee_msat = cur_hop_fees_msat;
299 // Fee for the use of the current hop which will be deducted on the previous hop.
300 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
301 // this channel is free for us.
303 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
304 cur_hop.hop_use_fee_msat = new_fee;
305 total_fee_paid_msat += new_fee;
307 // It should not be possible because this function is called only to reduce the
308 // value. In that case, compute_fee was already called with the same fees for
309 // larger amount and there was no overflow.
317 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
318 let proportional_fee_millions =
319 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
320 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
321 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
325 // This function may be (indirectly) called without any verification,
326 // with channel_fees provided by a caller. We should handle it gracefully.
331 /// Gets a route from us (payer) to the given target node (payee).
333 /// If the payee provided features in their invoice, they should be provided via payee_features.
334 /// Without this, MPP will only be used if the payee's features are available in the network graph.
336 /// Private routing paths between a public node and the target may be included in `last_hops`.
337 /// Currently, only the last hop in each path is considered.
339 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
340 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
341 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
342 /// in first_hops will be used.
344 /// Panics if first_hops contains channels without short_channel_ids
345 /// (ChannelManager::list_usable_channels will never include such channels).
347 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
348 /// equal), however the enabled/disabled bit on such channels as well as the
349 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
350 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
351 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
352 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
353 // uptime/success in using a node in the past.
354 if *payee == *our_node_id {
355 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
358 if final_value_msat > MAX_VALUE_MSAT {
359 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
362 if final_value_msat == 0 {
363 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
366 let last_hops = last_hops.iter().filter_map(|hops| hops.0.last()).collect::<Vec<_>>();
367 for last_hop in last_hops.iter() {
368 if last_hop.src_node_id == *payee {
369 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
373 // The general routing idea is the following:
374 // 1. Fill first/last hops communicated by the caller.
375 // 2. Attempt to construct a path from payer to payee for transferring
376 // any ~sufficient (described later) value.
377 // If succeed, remember which channels were used and how much liquidity they have available,
378 // so that future paths don't rely on the same liquidity.
379 // 3. Prooceed to the next step if:
380 // - we hit the recommended target value;
381 // - OR if we could not construct a new path. Any next attempt will fail too.
382 // Otherwise, repeat step 2.
383 // 4. See if we managed to collect paths which aggregately are able to transfer target value
384 // (not recommended value). If yes, proceed. If not, fail routing.
385 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
386 // 6. Of all the found paths, select only those with the lowest total fee.
387 // 7. The last path in every selected route is likely to be more than we need.
388 // Reduce its value-to-transfer and recompute fees.
389 // 8. Choose the best route by the lowest total fee.
391 // As for the actual search algorithm,
392 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
393 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
395 // We are not a faithful Dijkstra's implementation because we can change values which impact
396 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
397 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
398 // the value we are currently attempting to send over a path, we simply reduce the value being
399 // sent along the path for any hops after that channel. This may imply that later fees (which
400 // we've already tabulated) are lower because a smaller value is passing through the channels
401 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
402 // channels which were selected earlier (and which may still be used for other paths without a
403 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
406 // One potentially problematic case for this algorithm would be if there are many
407 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
408 // graph walking), we may never find a path which is not liquidity-limited and has lower
409 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
410 // Because we only consider paths with at least 5% of the total value being sent, the damage
411 // from such a case should be limited, however this could be further reduced in the future by
412 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
413 // limits for the purposes of fee calculation.
415 // Alternatively, we could store more detailed path information in the heap (targets, below)
416 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
417 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
418 // and practically (as we would need to store dynamically-allocated path information in heap
419 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
420 // results of such an algorithm would likely be biased towards lower-value paths.
422 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
423 // outside of our current search value, running a path search more times to gather candidate
424 // paths at different values. While this may be acceptable, further path searches may increase
425 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
426 // graph for candidate paths, calculating the maximum value which can realistically be sent at
427 // the same time, remaining generic across different payment values.
429 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
430 // to use as the A* heuristic beyond just the cost to get one node further than the current
433 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
434 cltv_expiry_delta: 0,
435 htlc_minimum_msat: 0,
436 htlc_maximum_msat: None,
439 proportional_millionths: 0,
443 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
444 // it. If the payee supports it they're supposed to include it in the invoice, so that should
446 let allow_mpp = if let Some(features) = &payee_features {
447 features.supports_basic_mpp()
448 } else if let Some(node) = network.get_nodes().get(&payee) {
449 if let Some(node_info) = node.announcement_info.as_ref() {
450 node_info.features.supports_basic_mpp()
455 // Prepare the data we'll use for payee-to-payer search by
456 // inserting first hops suggested by the caller as targets.
457 // Our search will then attempt to reach them while traversing from the payee node.
458 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
459 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
460 if let Some(hops) = first_hops {
462 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
463 if chan.remote_network_id == *our_node_id {
464 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
466 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.to_context(), chan.outbound_capacity_msat, chan.counterparty_features.to_context()));
468 if first_hop_targets.is_empty() {
469 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
473 let empty_channel_features = ChannelFeatures::empty();
475 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
476 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
477 // adding duplicate entries when we find a better path to a given node.
478 let mut targets = BinaryHeap::new();
480 // Map from node_id to information about the best current path to that node, including feerate
482 let mut dist = HashMap::with_capacity(network.get_nodes().len());
484 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
485 // indicating that we may wish to try again with a higher value, potentially paying to meet an
486 // htlc_minimum with extra fees while still finding a cheaper path.
487 let mut hit_minimum_limit;
489 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
490 // We start with a path_value of the exact amount we want, and if that generates a route we may
491 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
492 // amount we want in total across paths, selecting the best subset at the end.
493 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
494 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
495 let mut path_value_msat = final_value_msat;
497 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
498 // This map allows paths to be aware of the channel use by other paths in the same call.
499 // This would help to make a better path finding decisions and not "overbook" channels.
500 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
501 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
503 // Keeping track of how much value we already collected across other paths. Helps to decide:
504 // - how much a new path should be transferring (upper bound);
505 // - whether a channel should be disregarded because
506 // it's available liquidity is too small comparing to how much more we need to collect;
507 // - when we want to stop looking for new paths.
508 let mut already_collected_value_msat = 0;
510 macro_rules! add_entry {
511 // Adds entry which goes from $src_node_id to $dest_node_id
512 // over the channel with id $chan_id with fees described in
513 // $directional_info.
514 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
515 // since that value has to be transferred over this channel.
516 ( $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,
517 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
518 // Channels to self should not be used. This is more of belt-and-suspenders, because in
519 // practice these cases should be caught earlier:
520 // - for regular channels at channel announcement (TODO)
521 // - for first and last hops early in get_route
522 if $src_node_id != $dest_node_id.clone() {
523 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
524 let mut initial_liquidity_available_msat = None;
525 if let Some(capacity_sats) = $capacity_sats {
526 initial_liquidity_available_msat = Some(capacity_sats * 1000);
529 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
530 if let Some(available_msat) = initial_liquidity_available_msat {
531 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
533 initial_liquidity_available_msat = Some(htlc_maximum_msat);
537 match initial_liquidity_available_msat {
538 Some(available_msat) => available_msat,
539 // We assume channels with unknown balance have
540 // a capacity of 0.0025 BTC (or 250_000 sats).
541 None => 250_000 * 1000
545 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
546 // It may be misleading because we might later choose to reduce the value transferred
547 // over these channels, and the channel which was insufficient might become sufficient.
548 // Worst case: we drop a good channel here because it can't cover the high following
549 // fees caused by one expensive channel, but then this channel could have been used
550 // if the amount being transferred over this path is lower.
551 // We do this for now, but this is a subject for removal.
552 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
554 // Routing Fragmentation Mitigation heuristic:
556 // Routing fragmentation across many payment paths increases the overall routing
557 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
558 // Taking too many smaller paths also increases the chance of payment failure.
559 // Thus to avoid this effect, we require from our collected links to provide
560 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
562 // This requirement is currently 5% of the remaining-to-be-collected value.
563 // This means as we successfully advance in our collection,
564 // the absolute liquidity contribution is lowered,
565 // thus increasing the number of potential channels to be selected.
567 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
568 // or 100% if we're not allowed to do multipath payments.
569 let minimal_value_contribution_msat: u64 = if allow_mpp {
570 (recommended_value_msat - already_collected_value_msat + 19) / 20
574 // Verify the liquidity offered by this channel complies to the minimal contribution.
575 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
577 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
578 // Includes paying fees for the use of the following channels.
579 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
580 Some(result) => result,
581 // Can't overflow due to how the values were computed right above.
582 None => unreachable!(),
584 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
585 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
586 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
588 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
589 // bother considering this channel.
590 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
591 // be only reduced later (not increased), so this channel should just be skipped
592 // as not sufficient.
593 if !over_path_minimum_msat {
594 hit_minimum_limit = true;
595 } else if contributes_sufficient_value {
596 // Note that low contribution here (limited by available_liquidity_msat)
597 // might violate htlc_minimum_msat on the hops which are next along the
598 // payment path (upstream to the payee). To avoid that, we recompute path
599 // path fees knowing the final path contribution after constructing it.
600 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
601 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
602 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
603 _ => u64::max_value()
605 let hm_entry = dist.entry(&$src_node_id);
606 let old_entry = hm_entry.or_insert_with(|| {
607 // If there was previously no known way to access
608 // the source node (recall it goes payee-to-payer) of $chan_id, first add
609 // a semi-dummy record just to compute the fees to reach the source node.
610 // This will affect our decision on selecting $chan_id
611 // as a way to reach the $dest_node_id.
612 let mut fee_base_msat = u32::max_value();
613 let mut fee_proportional_millionths = u32::max_value();
614 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
615 fee_base_msat = fees.base_msat;
616 fee_proportional_millionths = fees.proportional_millionths;
619 pubkey: $dest_node_id.clone(),
621 channel_features: $chan_features,
623 cltv_expiry_delta: 0,
624 src_lowest_inbound_fees: RoutingFees {
625 base_msat: fee_base_msat,
626 proportional_millionths: fee_proportional_millionths,
628 channel_fees: $directional_info.fees,
629 next_hops_fee_msat: u64::max_value(),
630 hop_use_fee_msat: u64::max_value(),
631 total_fee_msat: u64::max_value(),
632 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
633 path_htlc_minimum_msat,
634 was_processed: false,
635 #[cfg(any(test, feature = "fuzztarget"))]
636 value_contribution_msat,
640 #[allow(unused_mut)] // We only use the mut in cfg(test)
641 let mut should_process = !old_entry.was_processed;
642 #[cfg(any(test, feature = "fuzztarget"))]
644 // In test/fuzzing builds, we do extra checks to make sure the skipping
645 // of already-seen nodes only happens in cases we expect (see below).
646 if !should_process { should_process = true; }
650 let mut hop_use_fee_msat = 0;
651 let mut total_fee_msat = $next_hops_fee_msat;
653 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
654 // will have the same effective-fee
655 if $src_node_id != *our_node_id {
656 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
657 // max_value means we'll always fail
658 // the old_entry.total_fee_msat > total_fee_msat check
659 None => total_fee_msat = u64::max_value(),
661 hop_use_fee_msat = fee_msat;
662 total_fee_msat += hop_use_fee_msat;
663 // When calculating the lowest inbound fees to a node, we
664 // calculate fees here not based on the actual value we think
665 // will flow over this channel, but on the minimum value that
666 // we'll accept flowing over it. The minimum accepted value
667 // is a constant through each path collection run, ensuring
668 // consistent basis. Otherwise we may later find a
669 // different path to the source node that is more expensive,
670 // but which we consider to be cheaper because we are capacity
671 // constrained and the relative fee becomes lower.
672 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
673 .map(|a| a.checked_add(total_fee_msat)) {
678 total_fee_msat = u64::max_value();
685 let new_graph_node = RouteGraphNode {
686 pubkey: $src_node_id,
687 lowest_fee_to_peer_through_node: total_fee_msat,
688 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
689 value_contribution_msat: value_contribution_msat,
690 path_htlc_minimum_msat,
693 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
694 // if this way is cheaper than the already known
695 // (considering the cost to "reach" this channel from the route destination,
696 // the cost of using this channel,
697 // and the cost of routing to the source node of this channel).
698 // Also, consider that htlc_minimum_msat_difference, because we might end up
699 // paying it. Consider the following exploit:
700 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
701 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
702 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
703 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
705 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
706 // but it may require additional tracking - we don't want to double-count
707 // the fees included in $next_hops_path_htlc_minimum_msat, but also
708 // can't use something that may decrease on future hops.
709 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
710 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
712 if !old_entry.was_processed && new_cost < old_cost {
713 targets.push(new_graph_node);
714 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
715 old_entry.hop_use_fee_msat = hop_use_fee_msat;
716 old_entry.total_fee_msat = total_fee_msat;
717 old_entry.pubkey = $dest_node_id.clone();
718 old_entry.short_channel_id = $chan_id.clone();
719 old_entry.channel_features = $chan_features;
720 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
721 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
722 old_entry.channel_fees = $directional_info.fees;
723 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
724 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
725 #[cfg(any(test, feature = "fuzztarget"))]
727 old_entry.value_contribution_msat = value_contribution_msat;
729 } else if old_entry.was_processed && new_cost < old_cost {
730 #[cfg(any(test, feature = "fuzztarget"))]
732 // If we're skipping processing a node which was previously
733 // processed even though we found another path to it with a
734 // cheaper fee, check that it was because the second path we
735 // found (which we are processing now) has a lower value
736 // contribution due to an HTLC minimum limit.
738 // e.g. take a graph with two paths from node 1 to node 2, one
739 // through channel A, and one through channel B. Channel A and
740 // B are both in the to-process heap, with their scores set by
741 // a higher htlc_minimum than fee.
742 // Channel A is processed first, and the channels onwards from
743 // node 1 are added to the to-process heap. Thereafter, we pop
744 // Channel B off of the heap, note that it has a much more
745 // restrictive htlc_maximum_msat, and recalculate the fees for
746 // all of node 1's channels using the new, reduced, amount.
748 // This would be bogus - we'd be selecting a higher-fee path
749 // with a lower htlc_maximum_msat instead of the one we'd
750 // already decided to use.
751 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
752 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
762 let empty_node_features = NodeFeatures::empty();
763 // Find ways (channels with destination) to reach a given node and store them
764 // in the corresponding data structures (routing graph etc).
765 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
766 // meaning how much will be paid in fees after this node (to the best of our knowledge).
767 // This data can later be helpful to optimize routing (pay lower fees).
768 macro_rules! add_entries_to_cheapest_to_target_node {
769 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
770 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
771 let was_processed = elem.was_processed;
772 elem.was_processed = true;
775 // Entries are added to dist in add_entry!() when there is a channel from a node.
776 // Because there are no channels from payee, it will not have a dist entry at this point.
777 // If we're processing any other node, it is always be the result of a channel from it.
778 assert_eq!($node_id, payee);
783 if first_hops.is_some() {
784 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
785 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);
789 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
795 if !features.requires_unknown_bits() {
796 for chan_id in $node.channels.iter() {
797 let chan = network.get_channels().get(chan_id).unwrap();
798 if !chan.features.requires_unknown_bits() {
799 if chan.node_one == *$node_id {
800 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
801 if first_hops.is_none() || chan.node_two != *our_node_id {
802 if let Some(two_to_one) = chan.two_to_one.as_ref() {
803 if two_to_one.enabled {
804 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);
809 if first_hops.is_none() || chan.node_one != *our_node_id {
810 if let Some(one_to_two) = chan.one_to_two.as_ref() {
811 if one_to_two.enabled {
812 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);
824 let mut payment_paths = Vec::<PaymentPath>::new();
826 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
827 'paths_collection: loop {
828 // For every new path, start from scratch, except
829 // bookkeeped_channels_liquidity_available_msat, which will improve
830 // the further iterations of path finding. Also don't erase first_hop_targets.
833 hit_minimum_limit = false;
835 // If first hop is a private channel and the only way to reach the payee, this is the only
836 // place where it could be added.
837 if first_hops.is_some() {
838 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
839 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
843 // Add the payee as a target, so that the payee-to-payer
844 // search algorithm knows what to start with.
845 match network.get_nodes().get(payee) {
846 // The payee is not in our network graph, so nothing to add here.
847 // There is still a chance of reaching them via last_hops though,
848 // so don't yet fail the payment here.
849 // If not, targets.pop() will not even let us enter the loop in step 2.
852 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
857 // If a caller provided us with last hops, add them to routing targets. Since this happens
858 // earlier than general path finding, they will be somewhat prioritized, although currently
859 // it matters only if the fees are exactly the same.
860 for hop in last_hops.iter() {
861 let have_hop_src_in_graph =
862 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
863 // If this hop connects to a node with which we have a direct channel, ignore
864 // the network graph and add both the hop and our direct channel to
865 // the candidate set.
867 // Currently there are no channel-context features defined, so we are a
868 // bit lazy here. In the future, we should pull them out via our
869 // ChannelManager, but there's no reason to waste the space until we
871 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
874 // In any other case, only add the hop if the source is in the regular network
876 network.get_nodes().get(&hop.src_node_id).is_some()
878 if have_hop_src_in_graph {
879 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
880 // really sucks, cause we're gonna need that eventually.
881 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
882 Some(htlc_minimum_msat) => htlc_minimum_msat,
885 let directional_info = DummyDirectionalChannelInfo {
886 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
887 htlc_minimum_msat: last_hop_htlc_minimum_msat,
888 htlc_maximum_msat: hop.htlc_maximum_msat,
891 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, &empty_channel_features, 0, path_value_msat, 0);
895 // At this point, targets are filled with the data from first and
896 // last hops communicated by the caller, and the payment receiver.
897 let mut found_new_path = false;
900 // If this loop terminates due the exhaustion of targets, two situations are possible:
901 // - not enough outgoing liquidity:
902 // 0 < already_collected_value_msat < final_value_msat
903 // - enough outgoing liquidity:
904 // final_value_msat <= already_collected_value_msat < recommended_value_msat
905 // Both these cases (and other cases except reaching recommended_value_msat) mean that
906 // paths_collection will be stopped because found_new_path==false.
907 // This is not necessarily a routing failure.
908 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
910 // Since we're going payee-to-payer, hitting our node as a target means we should stop
911 // traversing the graph and arrange the path out of what we found.
912 if pubkey == *our_node_id {
913 let mut new_entry = dist.remove(&our_node_id).unwrap();
914 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
917 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
918 ordered_hops.last_mut().unwrap().1 = features.clone();
919 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
920 if let Some(node_info) = node.announcement_info.as_ref() {
921 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
923 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
926 // We should be able to fill in features for everything except the last
927 // hop, if the last hop was provided via a BOLT 11 invoice (though we
928 // should be able to extend it further as BOLT 11 does have feature
929 // flags for the last hop node itself).
930 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
933 // Means we succesfully traversed from the payer to the payee, now
934 // save this path for the payment route. Also, update the liquidity
935 // remaining on the used hops, so that we take them into account
936 // while looking for more paths.
937 if ordered_hops.last().unwrap().0.pubkey == *payee {
941 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
942 Some(payment_hop) => payment_hop,
943 // We can't arrive at None because, if we ever add an entry to targets,
944 // we also fill in the entry in dist (see add_entry!).
945 None => unreachable!(),
947 // We "propagate" the fees one hop backward (topologically) here,
948 // so that fees paid for a HTLC forwarding on the current channel are
949 // associated with the previous channel (where they will be subtracted).
950 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
951 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
952 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
954 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
955 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
956 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
958 let mut payment_path = PaymentPath {hops: ordered_hops};
960 // We could have possibly constructed a slightly inconsistent path: since we reduce
961 // value being transferred along the way, we could have violated htlc_minimum_msat
962 // on some channels we already passed (assuming dest->source direction). Here, we
963 // recompute the fees again, so that if that's the case, we match the currently
964 // underpaid htlc_minimum_msat with fees.
965 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
967 // Since a path allows to transfer as much value as
968 // the smallest channel it has ("bottleneck"), we should recompute
969 // the fees so sender HTLC don't overpay fees when traversing
970 // larger channels than the bottleneck. This may happen because
971 // when we were selecting those channels we were not aware how much value
972 // this path will transfer, and the relative fee for them
973 // might have been computed considering a larger value.
974 // Remember that we used these channels so that we don't rely
975 // on the same liquidity in future paths.
976 let mut prevented_redundant_path_selection = false;
977 for (payment_hop, _) in payment_path.hops.iter() {
978 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
979 let mut spent_on_hop_msat = value_contribution_msat;
980 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
981 spent_on_hop_msat += next_hops_fee_msat;
982 if spent_on_hop_msat == *channel_liquidity_available_msat {
983 // If this path used all of this channel's available liquidity, we know
984 // this path will not be selected again in the next loop iteration.
985 prevented_redundant_path_selection = true;
987 *channel_liquidity_available_msat -= spent_on_hop_msat;
989 if !prevented_redundant_path_selection {
990 // If we weren't capped by hitting a liquidity limit on a channel in the path,
991 // we'll probably end up picking the same path again on the next iteration.
992 // Decrease the available liquidity of a hop in the middle of the path.
993 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(
994 &payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id).unwrap();
995 *victim_liquidity = 0;
998 // Track the total amount all our collected paths allow to send so that we:
999 // - know when to stop looking for more paths
1000 // - know which of the hops are useless considering how much more sats we need
1001 // (contributes_sufficient_value)
1002 already_collected_value_msat += value_contribution_msat;
1004 payment_paths.push(payment_path);
1005 found_new_path = true;
1006 break 'path_construction;
1009 // If we found a path back to the payee, we shouldn't try to process it again. This is
1010 // the equivalent of the `elem.was_processed` check in
1011 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1012 if pubkey == *payee { continue 'path_construction; }
1014 // Otherwise, since the current target node is not us,
1015 // keep "unrolling" the payment graph from payee to payer by
1016 // finding a way to reach the current target from the payer side.
1017 match network.get_nodes().get(&pubkey) {
1020 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1026 // If we don't support MPP, no use trying to gather more value ever.
1027 break 'paths_collection;
1031 // Stop either when the recommended value is reached or if no new path was found in this
1033 // In the latter case, making another path finding attempt won't help,
1034 // because we deterministically terminated the search due to low liquidity.
1035 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1036 break 'paths_collection;
1037 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1038 // Further, if this was our first walk of the graph, and we weren't limited by an
1039 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1040 // limited by an htlc_minimum_msat value, find another path with a higher value,
1041 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1042 // still keeping a lower total fee than this path.
1043 if !hit_minimum_limit {
1044 break 'paths_collection;
1046 path_value_msat = recommended_value_msat;
1051 if payment_paths.len() == 0 {
1052 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1055 if already_collected_value_msat < final_value_msat {
1056 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1059 // Sort by total fees and take the best paths.
1060 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1061 if payment_paths.len() > 50 {
1062 payment_paths.truncate(50);
1065 // Draw multiple sufficient routes by randomly combining the selected paths.
1066 let mut drawn_routes = Vec::new();
1067 for i in 0..payment_paths.len() {
1068 let mut cur_route = Vec::<PaymentPath>::new();
1069 let mut aggregate_route_value_msat = 0;
1072 // TODO: real random shuffle
1073 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1074 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1077 for payment_path in cur_payment_paths {
1078 cur_route.push(payment_path.clone());
1079 aggregate_route_value_msat += payment_path.get_value_msat();
1080 if aggregate_route_value_msat > final_value_msat {
1081 // Last path likely overpaid. Substract it from the most expensive
1082 // (in terms of proportional fee) path in this route and recompute fees.
1083 // This might be not the most economically efficient way, but fewer paths
1084 // also makes routing more reliable.
1085 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1087 // First, drop some expensive low-value paths entirely if possible.
1088 // Sort by value so that we drop many really-low values first, since
1089 // fewer paths is better: the payment is less likely to fail.
1090 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1091 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1092 cur_route.sort_by_key(|path| path.get_value_msat());
1093 // We should make sure that at least 1 path left.
1094 let mut paths_left = cur_route.len();
1095 cur_route.retain(|path| {
1096 if paths_left == 1 {
1099 let mut keep = true;
1100 let path_value_msat = path.get_value_msat();
1101 if path_value_msat <= overpaid_value_msat {
1103 overpaid_value_msat -= path_value_msat;
1109 if overpaid_value_msat == 0 {
1113 assert!(cur_route.len() > 0);
1116 // Now, substract the overpaid value from the most-expensive path.
1117 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1118 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1119 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1120 let expensive_payment_path = cur_route.first_mut().unwrap();
1121 // We already dropped all the small channels above, meaning all the
1122 // remaining channels are larger than remaining overpaid_value_msat.
1123 // Thus, this can't be negative.
1124 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1125 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1129 drawn_routes.push(cur_route);
1133 // Select the best route by lowest total fee.
1134 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1135 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1136 for payment_path in drawn_routes.first().unwrap() {
1137 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1139 pubkey: payment_hop.pubkey,
1140 node_features: node_features.clone(),
1141 short_channel_id: payment_hop.short_channel_id,
1142 channel_features: payment_hop.channel_features.clone(),
1143 fee_msat: payment_hop.fee_msat,
1144 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1149 if let Some(features) = &payee_features {
1150 for path in selected_paths.iter_mut() {
1151 path.last_mut().unwrap().node_features = features.to_context();
1155 let route = Route { paths: selected_paths };
1156 log_trace!(logger, "Got route: {}", log_route!(route));
1162 use routing::router::{get_route, RouteHint, RouteHintHop, RoutingFees};
1163 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1164 use chain::transaction::OutPoint;
1165 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1166 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1167 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1168 use ln::channelmanager;
1169 use util::test_utils;
1170 use util::ser::Writeable;
1172 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1173 use bitcoin::hashes::Hash;
1174 use bitcoin::network::constants::Network;
1175 use bitcoin::blockdata::constants::genesis_block;
1176 use bitcoin::blockdata::script::Builder;
1177 use bitcoin::blockdata::opcodes;
1178 use bitcoin::blockdata::transaction::TxOut;
1182 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1183 use bitcoin::secp256k1::{Secp256k1, All};
1188 // Using the same keys for LN and BTC ids
1189 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1190 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1191 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1192 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1194 let unsigned_announcement = UnsignedChannelAnnouncement {
1196 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1200 bitcoin_key_1: node_id_1,
1201 bitcoin_key_2: node_id_2,
1202 excess_data: Vec::new(),
1205 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1206 let valid_announcement = ChannelAnnouncement {
1207 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1208 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1209 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1210 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1211 contents: unsigned_announcement.clone(),
1213 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1214 Ok(res) => assert!(res),
1219 fn update_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate) {
1220 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1221 let valid_channel_update = ChannelUpdate {
1222 signature: secp_ctx.sign(&msghash, node_privkey),
1223 contents: update.clone()
1226 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1227 Ok(res) => assert!(res),
1232 fn add_or_update_node(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey,
1233 features: NodeFeatures, timestamp: u32) {
1234 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1235 let unsigned_announcement = UnsignedNodeAnnouncement {
1241 addresses: Vec::new(),
1242 excess_address_data: Vec::new(),
1243 excess_data: Vec::new(),
1245 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1246 let valid_announcement = NodeAnnouncement {
1247 signature: secp_ctx.sign(&msghash, node_privkey),
1248 contents: unsigned_announcement.clone()
1251 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1257 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1258 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1259 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1262 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1264 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1265 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1267 (our_privkey, our_id, privkeys, pubkeys)
1270 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1271 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1272 // test for it later.
1273 let idx = (id - 1) * 2 + 1;
1275 vec![1 << (idx - 8*3), 0, 0, 0]
1276 } else if idx > 8*2 {
1277 vec![1 << (idx - 8*2), 0, 0]
1278 } else if idx > 8*1 {
1279 vec![1 << (idx - 8*1), 0]
1285 fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<std::sync::Arc<test_utils::TestChainSource>, std::sync::Arc<crate::util::test_utils::TestLogger>>, std::sync::Arc<test_utils::TestChainSource>, std::sync::Arc<test_utils::TestLogger>) {
1286 let secp_ctx = Secp256k1::new();
1287 let logger = Arc::new(test_utils::TestLogger::new());
1288 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1289 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1290 // Build network from our_id to node7:
1292 // -1(1)2- node0 -1(3)2-
1294 // our_id -1(12)2- node7 -1(13)2--- node2
1296 // -1(2)2- node1 -1(4)2-
1299 // chan1 1-to-2: disabled
1300 // chan1 2-to-1: enabled, 0 fee
1302 // chan2 1-to-2: enabled, ignored fee
1303 // chan2 2-to-1: enabled, 0 fee
1305 // chan3 1-to-2: enabled, 0 fee
1306 // chan3 2-to-1: enabled, 100 msat fee
1308 // chan4 1-to-2: enabled, 100% fee
1309 // chan4 2-to-1: enabled, 0 fee
1311 // chan12 1-to-2: enabled, ignored fee
1312 // chan12 2-to-1: enabled, 0 fee
1314 // chan13 1-to-2: enabled, 200% fee
1315 // chan13 2-to-1: enabled, 0 fee
1318 // -1(5)2- node3 -1(8)2--
1322 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1324 // -1(7)2- node5 -1(10)2-
1326 // chan5 1-to-2: enabled, 100 msat fee
1327 // chan5 2-to-1: enabled, 0 fee
1329 // chan6 1-to-2: enabled, 0 fee
1330 // chan6 2-to-1: enabled, 0 fee
1332 // chan7 1-to-2: enabled, 100% fee
1333 // chan7 2-to-1: enabled, 0 fee
1335 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1336 // chan8 2-to-1: enabled, 0 fee
1338 // chan9 1-to-2: enabled, 1001 msat fee
1339 // chan9 2-to-1: enabled, 0 fee
1341 // chan10 1-to-2: enabled, 0 fee
1342 // chan10 2-to-1: enabled, 0 fee
1344 // chan11 1-to-2: enabled, 0 fee
1345 // chan11 2-to-1: enabled, 0 fee
1347 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1349 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1350 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1351 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1352 short_channel_id: 1,
1355 cltv_expiry_delta: 0,
1356 htlc_minimum_msat: 0,
1357 htlc_maximum_msat: OptionalField::Absent,
1359 fee_proportional_millionths: 0,
1360 excess_data: Vec::new()
1363 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1365 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1366 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1367 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1368 short_channel_id: 2,
1371 cltv_expiry_delta: u16::max_value(),
1372 htlc_minimum_msat: 0,
1373 htlc_maximum_msat: OptionalField::Absent,
1374 fee_base_msat: u32::max_value(),
1375 fee_proportional_millionths: u32::max_value(),
1376 excess_data: Vec::new()
1378 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1379 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1380 short_channel_id: 2,
1383 cltv_expiry_delta: 0,
1384 htlc_minimum_msat: 0,
1385 htlc_maximum_msat: OptionalField::Absent,
1387 fee_proportional_millionths: 0,
1388 excess_data: Vec::new()
1391 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1393 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1394 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1396 short_channel_id: 12,
1399 cltv_expiry_delta: u16::max_value(),
1400 htlc_minimum_msat: 0,
1401 htlc_maximum_msat: OptionalField::Absent,
1402 fee_base_msat: u32::max_value(),
1403 fee_proportional_millionths: u32::max_value(),
1404 excess_data: Vec::new()
1406 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1407 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1408 short_channel_id: 12,
1411 cltv_expiry_delta: 0,
1412 htlc_minimum_msat: 0,
1413 htlc_maximum_msat: OptionalField::Absent,
1415 fee_proportional_millionths: 0,
1416 excess_data: Vec::new()
1419 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1421 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1422 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1423 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1424 short_channel_id: 3,
1427 cltv_expiry_delta: (3 << 8) | 1,
1428 htlc_minimum_msat: 0,
1429 htlc_maximum_msat: OptionalField::Absent,
1431 fee_proportional_millionths: 0,
1432 excess_data: Vec::new()
1434 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1435 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1436 short_channel_id: 3,
1439 cltv_expiry_delta: (3 << 8) | 2,
1440 htlc_minimum_msat: 0,
1441 htlc_maximum_msat: OptionalField::Absent,
1443 fee_proportional_millionths: 0,
1444 excess_data: Vec::new()
1447 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1448 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1450 short_channel_id: 4,
1453 cltv_expiry_delta: (4 << 8) | 1,
1454 htlc_minimum_msat: 0,
1455 htlc_maximum_msat: OptionalField::Absent,
1457 fee_proportional_millionths: 1000000,
1458 excess_data: Vec::new()
1460 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1462 short_channel_id: 4,
1465 cltv_expiry_delta: (4 << 8) | 2,
1466 htlc_minimum_msat: 0,
1467 htlc_maximum_msat: OptionalField::Absent,
1469 fee_proportional_millionths: 0,
1470 excess_data: Vec::new()
1473 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1474 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1475 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1476 short_channel_id: 13,
1479 cltv_expiry_delta: (13 << 8) | 1,
1480 htlc_minimum_msat: 0,
1481 htlc_maximum_msat: OptionalField::Absent,
1483 fee_proportional_millionths: 2000000,
1484 excess_data: Vec::new()
1486 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1487 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1488 short_channel_id: 13,
1491 cltv_expiry_delta: (13 << 8) | 2,
1492 htlc_minimum_msat: 0,
1493 htlc_maximum_msat: OptionalField::Absent,
1495 fee_proportional_millionths: 0,
1496 excess_data: Vec::new()
1499 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1501 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1502 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1503 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1504 short_channel_id: 6,
1507 cltv_expiry_delta: (6 << 8) | 1,
1508 htlc_minimum_msat: 0,
1509 htlc_maximum_msat: OptionalField::Absent,
1511 fee_proportional_millionths: 0,
1512 excess_data: Vec::new()
1514 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1516 short_channel_id: 6,
1519 cltv_expiry_delta: (6 << 8) | 2,
1520 htlc_minimum_msat: 0,
1521 htlc_maximum_msat: OptionalField::Absent,
1523 fee_proportional_millionths: 0,
1524 excess_data: Vec::new(),
1527 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1528 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1529 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1530 short_channel_id: 11,
1533 cltv_expiry_delta: (11 << 8) | 1,
1534 htlc_minimum_msat: 0,
1535 htlc_maximum_msat: OptionalField::Absent,
1537 fee_proportional_millionths: 0,
1538 excess_data: Vec::new()
1540 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1541 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1542 short_channel_id: 11,
1545 cltv_expiry_delta: (11 << 8) | 2,
1546 htlc_minimum_msat: 0,
1547 htlc_maximum_msat: OptionalField::Absent,
1549 fee_proportional_millionths: 0,
1550 excess_data: Vec::new()
1553 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1555 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1557 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1558 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1560 short_channel_id: 7,
1563 cltv_expiry_delta: (7 << 8) | 1,
1564 htlc_minimum_msat: 0,
1565 htlc_maximum_msat: OptionalField::Absent,
1567 fee_proportional_millionths: 1000000,
1568 excess_data: Vec::new()
1570 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1572 short_channel_id: 7,
1575 cltv_expiry_delta: (7 << 8) | 2,
1576 htlc_minimum_msat: 0,
1577 htlc_maximum_msat: OptionalField::Absent,
1579 fee_proportional_millionths: 0,
1580 excess_data: Vec::new()
1583 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1585 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1589 fn simple_route_test() {
1590 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1591 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1593 // Simple route to 2 via 1
1595 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 0, 42, Arc::clone(&logger)) {
1596 assert_eq!(err, "Cannot send a payment of 0 msat");
1597 } else { panic!(); }
1599 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1600 assert_eq!(route.paths[0].len(), 2);
1602 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1603 assert_eq!(route.paths[0][0].short_channel_id, 2);
1604 assert_eq!(route.paths[0][0].fee_msat, 100);
1605 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1606 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1607 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1609 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1610 assert_eq!(route.paths[0][1].short_channel_id, 4);
1611 assert_eq!(route.paths[0][1].fee_msat, 100);
1612 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1613 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1614 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1618 fn invalid_first_hop_test() {
1619 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1620 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1622 // Simple route to 2 via 1
1624 let our_chans = vec![channelmanager::ChannelDetails {
1625 channel_id: [0; 32],
1626 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1627 short_channel_id: Some(2),
1628 remote_network_id: our_id,
1629 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1630 channel_value_satoshis: 100000,
1632 outbound_capacity_msat: 100000,
1633 inbound_capacity_msat: 100000,
1634 is_outbound: true, is_funding_locked: true,
1635 is_usable: true, is_public: true,
1636 counterparty_forwarding_info: None,
1639 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)) {
1640 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1641 } else { panic!(); }
1643 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1644 assert_eq!(route.paths[0].len(), 2);
1648 fn htlc_minimum_test() {
1649 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1650 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1652 // Simple route to 2 via 1
1654 // Disable other paths
1655 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1656 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1657 short_channel_id: 12,
1659 flags: 2, // to disable
1660 cltv_expiry_delta: 0,
1661 htlc_minimum_msat: 0,
1662 htlc_maximum_msat: OptionalField::Absent,
1664 fee_proportional_millionths: 0,
1665 excess_data: Vec::new()
1667 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1668 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1669 short_channel_id: 3,
1671 flags: 2, // to disable
1672 cltv_expiry_delta: 0,
1673 htlc_minimum_msat: 0,
1674 htlc_maximum_msat: OptionalField::Absent,
1676 fee_proportional_millionths: 0,
1677 excess_data: Vec::new()
1679 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1680 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1681 short_channel_id: 13,
1683 flags: 2, // to disable
1684 cltv_expiry_delta: 0,
1685 htlc_minimum_msat: 0,
1686 htlc_maximum_msat: OptionalField::Absent,
1688 fee_proportional_millionths: 0,
1689 excess_data: Vec::new()
1691 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1693 short_channel_id: 6,
1695 flags: 2, // to disable
1696 cltv_expiry_delta: 0,
1697 htlc_minimum_msat: 0,
1698 htlc_maximum_msat: OptionalField::Absent,
1700 fee_proportional_millionths: 0,
1701 excess_data: Vec::new()
1703 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1705 short_channel_id: 7,
1707 flags: 2, // to disable
1708 cltv_expiry_delta: 0,
1709 htlc_minimum_msat: 0,
1710 htlc_maximum_msat: OptionalField::Absent,
1712 fee_proportional_millionths: 0,
1713 excess_data: Vec::new()
1716 // Check against amount_to_transfer_over_msat.
1717 // Set minimal HTLC of 200_000_000 msat.
1718 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1719 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1720 short_channel_id: 2,
1723 cltv_expiry_delta: 0,
1724 htlc_minimum_msat: 200_000_000,
1725 htlc_maximum_msat: OptionalField::Absent,
1727 fee_proportional_millionths: 0,
1728 excess_data: Vec::new()
1731 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1733 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1734 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1735 short_channel_id: 4,
1738 cltv_expiry_delta: 0,
1739 htlc_minimum_msat: 0,
1740 htlc_maximum_msat: OptionalField::Present(199_999_999),
1742 fee_proportional_millionths: 0,
1743 excess_data: Vec::new()
1746 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1747 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)) {
1748 assert_eq!(err, "Failed to find a path to the given destination");
1749 } else { panic!(); }
1751 // Lift the restriction on the first hop.
1752 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1753 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1754 short_channel_id: 2,
1757 cltv_expiry_delta: 0,
1758 htlc_minimum_msat: 0,
1759 htlc_maximum_msat: OptionalField::Absent,
1761 fee_proportional_millionths: 0,
1762 excess_data: Vec::new()
1765 // A payment above the minimum should pass
1766 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)).unwrap();
1767 assert_eq!(route.paths[0].len(), 2);
1771 fn htlc_minimum_overpay_test() {
1772 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1773 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1775 // A route to node#2 via two paths.
1776 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1777 // Thus, they can't send 60 without overpaying.
1778 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1779 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1780 short_channel_id: 2,
1783 cltv_expiry_delta: 0,
1784 htlc_minimum_msat: 35_000,
1785 htlc_maximum_msat: OptionalField::Present(40_000),
1787 fee_proportional_millionths: 0,
1788 excess_data: Vec::new()
1790 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1792 short_channel_id: 12,
1795 cltv_expiry_delta: 0,
1796 htlc_minimum_msat: 35_000,
1797 htlc_maximum_msat: OptionalField::Present(40_000),
1799 fee_proportional_millionths: 0,
1800 excess_data: Vec::new()
1804 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1805 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1806 short_channel_id: 13,
1809 cltv_expiry_delta: 0,
1810 htlc_minimum_msat: 0,
1811 htlc_maximum_msat: OptionalField::Absent,
1813 fee_proportional_millionths: 0,
1814 excess_data: Vec::new()
1816 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1817 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1818 short_channel_id: 4,
1821 cltv_expiry_delta: 0,
1822 htlc_minimum_msat: 0,
1823 htlc_maximum_msat: OptionalField::Absent,
1825 fee_proportional_millionths: 0,
1826 excess_data: Vec::new()
1829 // Disable other paths
1830 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1831 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1832 short_channel_id: 1,
1834 flags: 2, // to disable
1835 cltv_expiry_delta: 0,
1836 htlc_minimum_msat: 0,
1837 htlc_maximum_msat: OptionalField::Absent,
1839 fee_proportional_millionths: 0,
1840 excess_data: Vec::new()
1843 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1844 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1845 // Overpay fees to hit htlc_minimum_msat.
1846 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1847 // TODO: this could be better balanced to overpay 10k and not 15k.
1848 assert_eq!(overpaid_fees, 15_000);
1850 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1851 // while taking even more fee to match htlc_minimum_msat.
1852 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1853 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1854 short_channel_id: 12,
1857 cltv_expiry_delta: 0,
1858 htlc_minimum_msat: 65_000,
1859 htlc_maximum_msat: OptionalField::Present(80_000),
1861 fee_proportional_millionths: 0,
1862 excess_data: Vec::new()
1864 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1865 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1866 short_channel_id: 2,
1869 cltv_expiry_delta: 0,
1870 htlc_minimum_msat: 0,
1871 htlc_maximum_msat: OptionalField::Absent,
1873 fee_proportional_millionths: 0,
1874 excess_data: Vec::new()
1876 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1877 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1878 short_channel_id: 4,
1881 cltv_expiry_delta: 0,
1882 htlc_minimum_msat: 0,
1883 htlc_maximum_msat: OptionalField::Absent,
1885 fee_proportional_millionths: 100_000,
1886 excess_data: Vec::new()
1889 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1890 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1891 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1892 assert_eq!(route.paths.len(), 1);
1893 assert_eq!(route.paths[0][0].short_channel_id, 12);
1894 let fees = route.paths[0][0].fee_msat;
1895 assert_eq!(fees, 5_000);
1897 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1898 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1899 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1900 // the other channel.
1901 assert_eq!(route.paths.len(), 1);
1902 assert_eq!(route.paths[0][0].short_channel_id, 2);
1903 let fees = route.paths[0][0].fee_msat;
1904 assert_eq!(fees, 5_000);
1908 fn disable_channels_test() {
1909 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1910 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1912 // // Disable channels 4 and 12 by flags=2
1913 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1914 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1915 short_channel_id: 4,
1917 flags: 2, // to disable
1918 cltv_expiry_delta: 0,
1919 htlc_minimum_msat: 0,
1920 htlc_maximum_msat: OptionalField::Absent,
1922 fee_proportional_millionths: 0,
1923 excess_data: Vec::new()
1925 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1926 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1927 short_channel_id: 12,
1929 flags: 2, // to disable
1930 cltv_expiry_delta: 0,
1931 htlc_minimum_msat: 0,
1932 htlc_maximum_msat: OptionalField::Absent,
1934 fee_proportional_millionths: 0,
1935 excess_data: Vec::new()
1938 // If all the channels require some features we don't understand, route should fail
1939 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1940 assert_eq!(err, "Failed to find a path to the given destination");
1941 } else { panic!(); }
1943 // If we specify a channel to node7, that overrides our local channel view and that gets used
1944 let our_chans = vec![channelmanager::ChannelDetails {
1945 channel_id: [0; 32],
1946 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1947 short_channel_id: Some(42),
1948 remote_network_id: nodes[7].clone(),
1949 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1950 channel_value_satoshis: 0,
1952 outbound_capacity_msat: 250_000_000,
1953 inbound_capacity_msat: 0,
1954 is_outbound: true, is_funding_locked: true,
1955 is_usable: true, is_public: true,
1956 counterparty_forwarding_info: None,
1958 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1959 assert_eq!(route.paths[0].len(), 2);
1961 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1962 assert_eq!(route.paths[0][0].short_channel_id, 42);
1963 assert_eq!(route.paths[0][0].fee_msat, 200);
1964 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1965 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1966 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1968 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1969 assert_eq!(route.paths[0][1].short_channel_id, 13);
1970 assert_eq!(route.paths[0][1].fee_msat, 100);
1971 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1972 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1973 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1977 fn disable_node_test() {
1978 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1979 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1981 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1982 let mut unknown_features = NodeFeatures::known();
1983 unknown_features.set_required_unknown_bits();
1984 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1985 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1986 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1988 // If all nodes require some features we don't understand, route should fail
1989 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1990 assert_eq!(err, "Failed to find a path to the given destination");
1991 } else { panic!(); }
1993 // If we specify a channel to node7, that overrides our local channel view and that gets used
1994 let our_chans = vec![channelmanager::ChannelDetails {
1995 channel_id: [0; 32],
1996 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1997 short_channel_id: Some(42),
1998 remote_network_id: nodes[7].clone(),
1999 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2000 channel_value_satoshis: 0,
2002 outbound_capacity_msat: 250_000_000,
2003 inbound_capacity_msat: 0,
2004 is_outbound: true, is_funding_locked: true,
2005 is_usable: true, is_public: true,
2006 counterparty_forwarding_info: None,
2008 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2009 assert_eq!(route.paths[0].len(), 2);
2011 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2012 assert_eq!(route.paths[0][0].short_channel_id, 42);
2013 assert_eq!(route.paths[0][0].fee_msat, 200);
2014 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2015 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2016 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2018 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2019 assert_eq!(route.paths[0][1].short_channel_id, 13);
2020 assert_eq!(route.paths[0][1].fee_msat, 100);
2021 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2022 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2023 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2025 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2026 // naively) assume that the user checked the feature bits on the invoice, which override
2027 // the node_announcement.
2031 fn our_chans_test() {
2032 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2033 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2035 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2036 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2037 assert_eq!(route.paths[0].len(), 3);
2039 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2040 assert_eq!(route.paths[0][0].short_channel_id, 2);
2041 assert_eq!(route.paths[0][0].fee_msat, 200);
2042 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2043 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2044 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2046 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2047 assert_eq!(route.paths[0][1].short_channel_id, 4);
2048 assert_eq!(route.paths[0][1].fee_msat, 100);
2049 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2050 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2051 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2053 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2054 assert_eq!(route.paths[0][2].short_channel_id, 3);
2055 assert_eq!(route.paths[0][2].fee_msat, 100);
2056 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2057 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2058 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2060 // If we specify a channel to node7, that overrides our local channel view and that gets used
2061 let our_chans = vec![channelmanager::ChannelDetails {
2062 channel_id: [0; 32],
2063 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2064 short_channel_id: Some(42),
2065 remote_network_id: nodes[7].clone(),
2066 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2067 channel_value_satoshis: 0,
2069 outbound_capacity_msat: 250_000_000,
2070 inbound_capacity_msat: 0,
2071 is_outbound: true, is_funding_locked: true,
2072 is_usable: true, is_public: true,
2073 counterparty_forwarding_info: None,
2075 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2076 assert_eq!(route.paths[0].len(), 2);
2078 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2079 assert_eq!(route.paths[0][0].short_channel_id, 42);
2080 assert_eq!(route.paths[0][0].fee_msat, 200);
2081 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2082 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2083 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2085 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2086 assert_eq!(route.paths[0][1].short_channel_id, 13);
2087 assert_eq!(route.paths[0][1].fee_msat, 100);
2088 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2089 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2090 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2093 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2094 let zero_fees = RoutingFees {
2096 proportional_millionths: 0,
2098 vec![RouteHint(vec![RouteHintHop {
2099 src_node_id: nodes[3].clone(),
2100 short_channel_id: 8,
2102 cltv_expiry_delta: (8 << 8) | 1,
2103 htlc_minimum_msat: None,
2104 htlc_maximum_msat: None,
2105 }]), RouteHint(vec![RouteHintHop {
2106 src_node_id: nodes[4].clone(),
2107 short_channel_id: 9,
2110 proportional_millionths: 0,
2112 cltv_expiry_delta: (9 << 8) | 1,
2113 htlc_minimum_msat: None,
2114 htlc_maximum_msat: None,
2115 }]), RouteHint(vec![RouteHintHop {
2116 src_node_id: nodes[5].clone(),
2117 short_channel_id: 10,
2119 cltv_expiry_delta: (10 << 8) | 1,
2120 htlc_minimum_msat: None,
2121 htlc_maximum_msat: None,
2126 fn last_hops_test() {
2127 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2128 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2130 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2132 // First check that last hop can't have its source as the payee.
2133 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2134 src_node_id: nodes[6],
2135 short_channel_id: 8,
2138 proportional_millionths: 0,
2140 cltv_expiry_delta: (8 << 8) | 1,
2141 htlc_minimum_msat: None,
2142 htlc_maximum_msat: None,
2145 let mut invalid_last_hops = last_hops(&nodes);
2146 invalid_last_hops.push(invalid_last_hop);
2148 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)) {
2149 assert_eq!(err, "Last hop cannot have a payee as a source.");
2150 } else { panic!(); }
2153 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2154 assert_eq!(route.paths[0].len(), 5);
2156 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2157 assert_eq!(route.paths[0][0].short_channel_id, 2);
2158 assert_eq!(route.paths[0][0].fee_msat, 100);
2159 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2160 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2161 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2163 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2164 assert_eq!(route.paths[0][1].short_channel_id, 4);
2165 assert_eq!(route.paths[0][1].fee_msat, 0);
2166 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2167 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2168 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2170 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2171 assert_eq!(route.paths[0][2].short_channel_id, 6);
2172 assert_eq!(route.paths[0][2].fee_msat, 0);
2173 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2174 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2175 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2177 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2178 assert_eq!(route.paths[0][3].short_channel_id, 11);
2179 assert_eq!(route.paths[0][3].fee_msat, 0);
2180 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2181 // If we have a peer in the node map, we'll use their features here since we don't have
2182 // a way of figuring out their features from the invoice:
2183 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2184 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2186 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2187 assert_eq!(route.paths[0][4].short_channel_id, 8);
2188 assert_eq!(route.paths[0][4].fee_msat, 100);
2189 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2190 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2191 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2195 fn our_chans_last_hop_connect_test() {
2196 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2197 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2199 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2200 let our_chans = vec![channelmanager::ChannelDetails {
2201 channel_id: [0; 32],
2202 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2203 short_channel_id: Some(42),
2204 remote_network_id: nodes[3].clone(),
2205 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2206 channel_value_satoshis: 0,
2208 outbound_capacity_msat: 250_000_000,
2209 inbound_capacity_msat: 0,
2210 is_outbound: true, is_funding_locked: true,
2211 is_usable: true, is_public: true,
2212 counterparty_forwarding_info: None,
2214 let mut last_hops = last_hops(&nodes);
2215 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2216 assert_eq!(route.paths[0].len(), 2);
2218 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2219 assert_eq!(route.paths[0][0].short_channel_id, 42);
2220 assert_eq!(route.paths[0][0].fee_msat, 0);
2221 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2222 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2223 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2225 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2226 assert_eq!(route.paths[0][1].short_channel_id, 8);
2227 assert_eq!(route.paths[0][1].fee_msat, 100);
2228 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2229 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2230 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2232 last_hops[0].0[0].fees.base_msat = 1000;
2234 // Revert to via 6 as the fee on 8 goes up
2235 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2236 assert_eq!(route.paths[0].len(), 4);
2238 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2239 assert_eq!(route.paths[0][0].short_channel_id, 2);
2240 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2241 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2242 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2243 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2245 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2246 assert_eq!(route.paths[0][1].short_channel_id, 4);
2247 assert_eq!(route.paths[0][1].fee_msat, 100);
2248 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2249 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2250 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2252 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2253 assert_eq!(route.paths[0][2].short_channel_id, 7);
2254 assert_eq!(route.paths[0][2].fee_msat, 0);
2255 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2256 // If we have a peer in the node map, we'll use their features here since we don't have
2257 // a way of figuring out their features from the invoice:
2258 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2259 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2261 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2262 assert_eq!(route.paths[0][3].short_channel_id, 10);
2263 assert_eq!(route.paths[0][3].fee_msat, 100);
2264 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2265 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2266 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2268 // ...but still use 8 for larger payments as 6 has a variable feerate
2269 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger)).unwrap();
2270 assert_eq!(route.paths[0].len(), 5);
2272 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2273 assert_eq!(route.paths[0][0].short_channel_id, 2);
2274 assert_eq!(route.paths[0][0].fee_msat, 3000);
2275 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2276 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2277 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2279 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2280 assert_eq!(route.paths[0][1].short_channel_id, 4);
2281 assert_eq!(route.paths[0][1].fee_msat, 0);
2282 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2283 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2284 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2286 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2287 assert_eq!(route.paths[0][2].short_channel_id, 6);
2288 assert_eq!(route.paths[0][2].fee_msat, 0);
2289 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2290 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2291 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2293 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2294 assert_eq!(route.paths[0][3].short_channel_id, 11);
2295 assert_eq!(route.paths[0][3].fee_msat, 1000);
2296 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2297 // If we have a peer in the node map, we'll use their features here since we don't have
2298 // a way of figuring out their features from the invoice:
2299 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2300 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2302 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2303 assert_eq!(route.paths[0][4].short_channel_id, 8);
2304 assert_eq!(route.paths[0][4].fee_msat, 2000);
2305 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2306 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2307 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2311 fn unannounced_path_test() {
2312 // We should be able to send a payment to a destination without any help of a routing graph
2313 // if we have a channel with a common counterparty that appears in the first and last hop
2315 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2316 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2317 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2319 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2320 let last_hops = RouteHint(vec![RouteHintHop {
2321 src_node_id: middle_node_id,
2322 short_channel_id: 8,
2325 proportional_millionths: 0,
2327 cltv_expiry_delta: (8 << 8) | 1,
2328 htlc_minimum_msat: None,
2329 htlc_maximum_msat: None,
2331 let our_chans = vec![channelmanager::ChannelDetails {
2332 channel_id: [0; 32],
2333 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2334 short_channel_id: Some(42),
2335 remote_network_id: middle_node_id,
2336 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2337 channel_value_satoshis: 100000,
2339 outbound_capacity_msat: 100000,
2340 inbound_capacity_msat: 100000,
2341 is_outbound: true, is_funding_locked: true,
2342 is_usable: true, is_public: true,
2343 counterparty_forwarding_info: None,
2345 let route = get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &vec![&last_hops], 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
2347 assert_eq!(route.paths[0].len(), 2);
2349 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2350 assert_eq!(route.paths[0][0].short_channel_id, 42);
2351 assert_eq!(route.paths[0][0].fee_msat, 1000);
2352 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2353 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2354 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2356 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2357 assert_eq!(route.paths[0][1].short_channel_id, 8);
2358 assert_eq!(route.paths[0][1].fee_msat, 100);
2359 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2360 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2361 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2365 fn available_amount_while_routing_test() {
2366 // Tests whether we choose the correct available channel amount while routing.
2368 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2369 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2371 // We will use a simple single-path route from
2372 // our node to node2 via node0: channels {1, 3}.
2374 // First disable all other paths.
2375 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2377 short_channel_id: 2,
2380 cltv_expiry_delta: 0,
2381 htlc_minimum_msat: 0,
2382 htlc_maximum_msat: OptionalField::Present(100_000),
2384 fee_proportional_millionths: 0,
2385 excess_data: Vec::new()
2387 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2388 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2389 short_channel_id: 12,
2392 cltv_expiry_delta: 0,
2393 htlc_minimum_msat: 0,
2394 htlc_maximum_msat: OptionalField::Present(100_000),
2396 fee_proportional_millionths: 0,
2397 excess_data: Vec::new()
2400 // Make the first channel (#1) very permissive,
2401 // and we will be testing all limits on the second channel.
2402 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2403 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2404 short_channel_id: 1,
2407 cltv_expiry_delta: 0,
2408 htlc_minimum_msat: 0,
2409 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2411 fee_proportional_millionths: 0,
2412 excess_data: Vec::new()
2415 // First, let's see if routing works if we have absolutely no idea about the available amount.
2416 // In this case, it should be set to 250_000 sats.
2417 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2418 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2419 short_channel_id: 3,
2422 cltv_expiry_delta: 0,
2423 htlc_minimum_msat: 0,
2424 htlc_maximum_msat: OptionalField::Absent,
2426 fee_proportional_millionths: 0,
2427 excess_data: Vec::new()
2431 // Attempt to route more than available results in a failure.
2432 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2433 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2434 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2435 } else { panic!(); }
2439 // Now, attempt to route an exact amount we have should be fine.
2440 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2441 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2442 assert_eq!(route.paths.len(), 1);
2443 let path = route.paths.last().unwrap();
2444 assert_eq!(path.len(), 2);
2445 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2446 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2449 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2450 // Disable channel #1 and use another first hop.
2451 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2452 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2453 short_channel_id: 1,
2456 cltv_expiry_delta: 0,
2457 htlc_minimum_msat: 0,
2458 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2460 fee_proportional_millionths: 0,
2461 excess_data: Vec::new()
2464 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2465 let our_chans = vec![channelmanager::ChannelDetails {
2466 channel_id: [0; 32],
2467 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2468 short_channel_id: Some(42),
2469 remote_network_id: nodes[0].clone(),
2470 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2471 channel_value_satoshis: 0,
2473 outbound_capacity_msat: 200_000_000,
2474 inbound_capacity_msat: 0,
2475 is_outbound: true, is_funding_locked: true,
2476 is_usable: true, is_public: true,
2477 counterparty_forwarding_info: None,
2481 // Attempt to route more than available results in a failure.
2482 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2483 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2484 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2485 } else { panic!(); }
2489 // Now, attempt to route an exact amount we have should be fine.
2490 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2491 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2492 assert_eq!(route.paths.len(), 1);
2493 let path = route.paths.last().unwrap();
2494 assert_eq!(path.len(), 2);
2495 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2496 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2499 // Enable channel #1 back.
2500 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2502 short_channel_id: 1,
2505 cltv_expiry_delta: 0,
2506 htlc_minimum_msat: 0,
2507 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2509 fee_proportional_millionths: 0,
2510 excess_data: Vec::new()
2514 // Now let's see if routing works if we know only htlc_maximum_msat.
2515 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2517 short_channel_id: 3,
2520 cltv_expiry_delta: 0,
2521 htlc_minimum_msat: 0,
2522 htlc_maximum_msat: OptionalField::Present(15_000),
2524 fee_proportional_millionths: 0,
2525 excess_data: Vec::new()
2529 // Attempt to route more than available results in a failure.
2530 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2531 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2532 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2533 } else { panic!(); }
2537 // Now, attempt to route an exact amount we have should be fine.
2538 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2539 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2540 assert_eq!(route.paths.len(), 1);
2541 let path = route.paths.last().unwrap();
2542 assert_eq!(path.len(), 2);
2543 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2544 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2547 // Now let's see if routing works if we know only capacity from the UTXO.
2549 // We can't change UTXO capacity on the fly, so we'll disable
2550 // the existing channel and add another one with the capacity we need.
2551 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2552 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2553 short_channel_id: 3,
2556 cltv_expiry_delta: 0,
2557 htlc_minimum_msat: 0,
2558 htlc_maximum_msat: OptionalField::Absent,
2560 fee_proportional_millionths: 0,
2561 excess_data: Vec::new()
2564 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2565 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2566 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2567 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2568 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2570 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2571 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2573 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2574 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2576 short_channel_id: 333,
2579 cltv_expiry_delta: (3 << 8) | 1,
2580 htlc_minimum_msat: 0,
2581 htlc_maximum_msat: OptionalField::Absent,
2583 fee_proportional_millionths: 0,
2584 excess_data: Vec::new()
2586 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2587 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2588 short_channel_id: 333,
2591 cltv_expiry_delta: (3 << 8) | 2,
2592 htlc_minimum_msat: 0,
2593 htlc_maximum_msat: OptionalField::Absent,
2595 fee_proportional_millionths: 0,
2596 excess_data: Vec::new()
2600 // Attempt to route more than available results in a failure.
2601 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2602 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2603 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2604 } else { panic!(); }
2608 // Now, attempt to route an exact amount we have should be fine.
2609 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2610 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2611 assert_eq!(route.paths.len(), 1);
2612 let path = route.paths.last().unwrap();
2613 assert_eq!(path.len(), 2);
2614 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2615 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2618 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2619 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2620 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2621 short_channel_id: 333,
2624 cltv_expiry_delta: 0,
2625 htlc_minimum_msat: 0,
2626 htlc_maximum_msat: OptionalField::Present(10_000),
2628 fee_proportional_millionths: 0,
2629 excess_data: Vec::new()
2633 // Attempt to route more than available results in a failure.
2634 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2635 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2636 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2637 } else { panic!(); }
2641 // Now, attempt to route an exact amount we have should be fine.
2642 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2643 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2644 assert_eq!(route.paths.len(), 1);
2645 let path = route.paths.last().unwrap();
2646 assert_eq!(path.len(), 2);
2647 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2648 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2653 fn available_liquidity_last_hop_test() {
2654 // Check that available liquidity properly limits the path even when only
2655 // one of the latter hops is limited.
2656 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2657 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2659 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2660 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2661 // Total capacity: 50 sats.
2663 // Disable other potential paths.
2664 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2665 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2666 short_channel_id: 2,
2669 cltv_expiry_delta: 0,
2670 htlc_minimum_msat: 0,
2671 htlc_maximum_msat: OptionalField::Present(100_000),
2673 fee_proportional_millionths: 0,
2674 excess_data: Vec::new()
2676 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2677 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2678 short_channel_id: 7,
2681 cltv_expiry_delta: 0,
2682 htlc_minimum_msat: 0,
2683 htlc_maximum_msat: OptionalField::Present(100_000),
2685 fee_proportional_millionths: 0,
2686 excess_data: Vec::new()
2691 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2692 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2693 short_channel_id: 12,
2696 cltv_expiry_delta: 0,
2697 htlc_minimum_msat: 0,
2698 htlc_maximum_msat: OptionalField::Present(100_000),
2700 fee_proportional_millionths: 0,
2701 excess_data: Vec::new()
2703 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2704 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2705 short_channel_id: 13,
2708 cltv_expiry_delta: 0,
2709 htlc_minimum_msat: 0,
2710 htlc_maximum_msat: OptionalField::Present(100_000),
2712 fee_proportional_millionths: 0,
2713 excess_data: Vec::new()
2716 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2718 short_channel_id: 6,
2721 cltv_expiry_delta: 0,
2722 htlc_minimum_msat: 0,
2723 htlc_maximum_msat: OptionalField::Present(50_000),
2725 fee_proportional_millionths: 0,
2726 excess_data: Vec::new()
2728 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2729 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2730 short_channel_id: 11,
2733 cltv_expiry_delta: 0,
2734 htlc_minimum_msat: 0,
2735 htlc_maximum_msat: OptionalField::Present(100_000),
2737 fee_proportional_millionths: 0,
2738 excess_data: Vec::new()
2741 // Attempt to route more than available results in a failure.
2742 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2743 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2744 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2745 } else { panic!(); }
2749 // Now, attempt to route 49 sats (just a bit below the capacity).
2750 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2751 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2752 assert_eq!(route.paths.len(), 1);
2753 let mut total_amount_paid_msat = 0;
2754 for path in &route.paths {
2755 assert_eq!(path.len(), 4);
2756 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2757 total_amount_paid_msat += path.last().unwrap().fee_msat;
2759 assert_eq!(total_amount_paid_msat, 49_000);
2763 // Attempt to route an exact amount is also fine
2764 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2765 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2766 assert_eq!(route.paths.len(), 1);
2767 let mut total_amount_paid_msat = 0;
2768 for path in &route.paths {
2769 assert_eq!(path.len(), 4);
2770 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2771 total_amount_paid_msat += path.last().unwrap().fee_msat;
2773 assert_eq!(total_amount_paid_msat, 50_000);
2778 fn ignore_fee_first_hop_test() {
2779 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2780 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2782 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2783 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2784 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2785 short_channel_id: 1,
2788 cltv_expiry_delta: 0,
2789 htlc_minimum_msat: 0,
2790 htlc_maximum_msat: OptionalField::Present(100_000),
2791 fee_base_msat: 1_000_000,
2792 fee_proportional_millionths: 0,
2793 excess_data: Vec::new()
2795 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2796 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2797 short_channel_id: 3,
2800 cltv_expiry_delta: 0,
2801 htlc_minimum_msat: 0,
2802 htlc_maximum_msat: OptionalField::Present(50_000),
2804 fee_proportional_millionths: 0,
2805 excess_data: Vec::new()
2809 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2810 assert_eq!(route.paths.len(), 1);
2811 let mut total_amount_paid_msat = 0;
2812 for path in &route.paths {
2813 assert_eq!(path.len(), 2);
2814 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2815 total_amount_paid_msat += path.last().unwrap().fee_msat;
2817 assert_eq!(total_amount_paid_msat, 50_000);
2822 fn simple_mpp_route_test() {
2823 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2824 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2826 // We need a route consisting of 3 paths:
2827 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2828 // To achieve this, the amount being transferred should be around
2829 // the total capacity of these 3 paths.
2831 // First, we set limits on these (previously unlimited) channels.
2832 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2834 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2835 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2836 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2837 short_channel_id: 1,
2840 cltv_expiry_delta: 0,
2841 htlc_minimum_msat: 0,
2842 htlc_maximum_msat: OptionalField::Present(100_000),
2844 fee_proportional_millionths: 0,
2845 excess_data: Vec::new()
2847 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2848 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2849 short_channel_id: 3,
2852 cltv_expiry_delta: 0,
2853 htlc_minimum_msat: 0,
2854 htlc_maximum_msat: OptionalField::Present(50_000),
2856 fee_proportional_millionths: 0,
2857 excess_data: Vec::new()
2860 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2861 // (total limit 60).
2862 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2863 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2864 short_channel_id: 12,
2867 cltv_expiry_delta: 0,
2868 htlc_minimum_msat: 0,
2869 htlc_maximum_msat: OptionalField::Present(60_000),
2871 fee_proportional_millionths: 0,
2872 excess_data: Vec::new()
2874 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2875 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2876 short_channel_id: 13,
2879 cltv_expiry_delta: 0,
2880 htlc_minimum_msat: 0,
2881 htlc_maximum_msat: OptionalField::Present(60_000),
2883 fee_proportional_millionths: 0,
2884 excess_data: Vec::new()
2887 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2888 // (total capacity 180 sats).
2889 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2890 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2891 short_channel_id: 2,
2894 cltv_expiry_delta: 0,
2895 htlc_minimum_msat: 0,
2896 htlc_maximum_msat: OptionalField::Present(200_000),
2898 fee_proportional_millionths: 0,
2899 excess_data: Vec::new()
2901 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2902 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2903 short_channel_id: 4,
2906 cltv_expiry_delta: 0,
2907 htlc_minimum_msat: 0,
2908 htlc_maximum_msat: OptionalField::Present(180_000),
2910 fee_proportional_millionths: 0,
2911 excess_data: Vec::new()
2915 // Attempt to route more than available results in a failure.
2916 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2917 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2918 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2919 } else { panic!(); }
2923 // Now, attempt to route 250 sats (just a bit below the capacity).
2924 // Our algorithm should provide us with these 3 paths.
2925 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2926 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2927 assert_eq!(route.paths.len(), 3);
2928 let mut total_amount_paid_msat = 0;
2929 for path in &route.paths {
2930 assert_eq!(path.len(), 2);
2931 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2932 total_amount_paid_msat += path.last().unwrap().fee_msat;
2934 assert_eq!(total_amount_paid_msat, 250_000);
2938 // Attempt to route an exact amount is also fine
2939 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2940 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2941 assert_eq!(route.paths.len(), 3);
2942 let mut total_amount_paid_msat = 0;
2943 for path in &route.paths {
2944 assert_eq!(path.len(), 2);
2945 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2946 total_amount_paid_msat += path.last().unwrap().fee_msat;
2948 assert_eq!(total_amount_paid_msat, 290_000);
2953 fn long_mpp_route_test() {
2954 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2955 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2957 // We need a route consisting of 3 paths:
2958 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2959 // Note that these paths overlap (channels 5, 12, 13).
2960 // We will route 300 sats.
2961 // Each path will have 100 sats capacity, those channels which
2962 // are used twice will have 200 sats capacity.
2964 // Disable other potential paths.
2965 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2966 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2967 short_channel_id: 2,
2970 cltv_expiry_delta: 0,
2971 htlc_minimum_msat: 0,
2972 htlc_maximum_msat: OptionalField::Present(100_000),
2974 fee_proportional_millionths: 0,
2975 excess_data: Vec::new()
2977 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2978 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2979 short_channel_id: 7,
2982 cltv_expiry_delta: 0,
2983 htlc_minimum_msat: 0,
2984 htlc_maximum_msat: OptionalField::Present(100_000),
2986 fee_proportional_millionths: 0,
2987 excess_data: Vec::new()
2990 // Path via {node0, node2} is channels {1, 3, 5}.
2991 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2992 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2993 short_channel_id: 1,
2996 cltv_expiry_delta: 0,
2997 htlc_minimum_msat: 0,
2998 htlc_maximum_msat: OptionalField::Present(100_000),
3000 fee_proportional_millionths: 0,
3001 excess_data: Vec::new()
3003 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3004 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3005 short_channel_id: 3,
3008 cltv_expiry_delta: 0,
3009 htlc_minimum_msat: 0,
3010 htlc_maximum_msat: OptionalField::Present(100_000),
3012 fee_proportional_millionths: 0,
3013 excess_data: Vec::new()
3016 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3017 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3018 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3019 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3020 short_channel_id: 5,
3023 cltv_expiry_delta: 0,
3024 htlc_minimum_msat: 0,
3025 htlc_maximum_msat: OptionalField::Present(200_000),
3027 fee_proportional_millionths: 0,
3028 excess_data: Vec::new()
3031 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3032 // Add 100 sats to the capacities of {12, 13}, because these channels
3033 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3034 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3035 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3036 short_channel_id: 12,
3039 cltv_expiry_delta: 0,
3040 htlc_minimum_msat: 0,
3041 htlc_maximum_msat: OptionalField::Present(200_000),
3043 fee_proportional_millionths: 0,
3044 excess_data: Vec::new()
3046 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3048 short_channel_id: 13,
3051 cltv_expiry_delta: 0,
3052 htlc_minimum_msat: 0,
3053 htlc_maximum_msat: OptionalField::Present(200_000),
3055 fee_proportional_millionths: 0,
3056 excess_data: Vec::new()
3059 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3061 short_channel_id: 6,
3064 cltv_expiry_delta: 0,
3065 htlc_minimum_msat: 0,
3066 htlc_maximum_msat: OptionalField::Present(100_000),
3068 fee_proportional_millionths: 0,
3069 excess_data: Vec::new()
3071 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3072 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3073 short_channel_id: 11,
3076 cltv_expiry_delta: 0,
3077 htlc_minimum_msat: 0,
3078 htlc_maximum_msat: OptionalField::Present(100_000),
3080 fee_proportional_millionths: 0,
3081 excess_data: Vec::new()
3084 // Path via {node7, node2} is channels {12, 13, 5}.
3085 // We already limited them to 200 sats (they are used twice for 100 sats).
3086 // Nothing to do here.
3089 // Attempt to route more than available results in a failure.
3090 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3091 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3092 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3093 } else { panic!(); }
3097 // Now, attempt to route 300 sats (exact amount we can route).
3098 // Our algorithm should provide us with these 3 paths, 100 sats each.
3099 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3100 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3101 assert_eq!(route.paths.len(), 3);
3103 let mut total_amount_paid_msat = 0;
3104 for path in &route.paths {
3105 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3106 total_amount_paid_msat += path.last().unwrap().fee_msat;
3108 assert_eq!(total_amount_paid_msat, 300_000);
3114 fn mpp_cheaper_route_test() {
3115 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3116 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3118 // This test checks that if we have two cheaper paths and one more expensive path,
3119 // so that liquidity-wise any 2 of 3 combination is sufficient,
3120 // two cheaper paths will be taken.
3121 // These paths have equal available liquidity.
3123 // We need a combination of 3 paths:
3124 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3125 // Note that these paths overlap (channels 5, 12, 13).
3126 // Each path will have 100 sats capacity, those channels which
3127 // are used twice will have 200 sats capacity.
3129 // Disable other potential paths.
3130 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3131 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3132 short_channel_id: 2,
3135 cltv_expiry_delta: 0,
3136 htlc_minimum_msat: 0,
3137 htlc_maximum_msat: OptionalField::Present(100_000),
3139 fee_proportional_millionths: 0,
3140 excess_data: Vec::new()
3142 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3143 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3144 short_channel_id: 7,
3147 cltv_expiry_delta: 0,
3148 htlc_minimum_msat: 0,
3149 htlc_maximum_msat: OptionalField::Present(100_000),
3151 fee_proportional_millionths: 0,
3152 excess_data: Vec::new()
3155 // Path via {node0, node2} is channels {1, 3, 5}.
3156 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3157 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3158 short_channel_id: 1,
3161 cltv_expiry_delta: 0,
3162 htlc_minimum_msat: 0,
3163 htlc_maximum_msat: OptionalField::Present(100_000),
3165 fee_proportional_millionths: 0,
3166 excess_data: Vec::new()
3168 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3169 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3170 short_channel_id: 3,
3173 cltv_expiry_delta: 0,
3174 htlc_minimum_msat: 0,
3175 htlc_maximum_msat: OptionalField::Present(100_000),
3177 fee_proportional_millionths: 0,
3178 excess_data: Vec::new()
3181 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3182 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
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: 5,
3188 cltv_expiry_delta: 0,
3189 htlc_minimum_msat: 0,
3190 htlc_maximum_msat: OptionalField::Present(200_000),
3192 fee_proportional_millionths: 0,
3193 excess_data: Vec::new()
3196 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3197 // Add 100 sats to the capacities of {12, 13}, because these channels
3198 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3199 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3201 short_channel_id: 12,
3204 cltv_expiry_delta: 0,
3205 htlc_minimum_msat: 0,
3206 htlc_maximum_msat: OptionalField::Present(200_000),
3208 fee_proportional_millionths: 0,
3209 excess_data: Vec::new()
3211 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3212 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3213 short_channel_id: 13,
3216 cltv_expiry_delta: 0,
3217 htlc_minimum_msat: 0,
3218 htlc_maximum_msat: OptionalField::Present(200_000),
3220 fee_proportional_millionths: 0,
3221 excess_data: Vec::new()
3224 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3226 short_channel_id: 6,
3229 cltv_expiry_delta: 0,
3230 htlc_minimum_msat: 0,
3231 htlc_maximum_msat: OptionalField::Present(100_000),
3232 fee_base_msat: 1_000,
3233 fee_proportional_millionths: 0,
3234 excess_data: Vec::new()
3236 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3237 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3238 short_channel_id: 11,
3241 cltv_expiry_delta: 0,
3242 htlc_minimum_msat: 0,
3243 htlc_maximum_msat: OptionalField::Present(100_000),
3245 fee_proportional_millionths: 0,
3246 excess_data: Vec::new()
3249 // Path via {node7, node2} is channels {12, 13, 5}.
3250 // We already limited them to 200 sats (they are used twice for 100 sats).
3251 // Nothing to do here.
3254 // Now, attempt to route 180 sats.
3255 // Our algorithm should provide us with these 2 paths.
3256 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3257 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3258 assert_eq!(route.paths.len(), 2);
3260 let mut total_value_transferred_msat = 0;
3261 let mut total_paid_msat = 0;
3262 for path in &route.paths {
3263 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3264 total_value_transferred_msat += path.last().unwrap().fee_msat;
3266 total_paid_msat += hop.fee_msat;
3269 // If we paid fee, this would be higher.
3270 assert_eq!(total_value_transferred_msat, 180_000);
3271 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3272 assert_eq!(total_fees_paid, 0);
3277 fn fees_on_mpp_route_test() {
3278 // This test makes sure that MPP algorithm properly takes into account
3279 // fees charged on the channels, by making the fees impactful:
3280 // if the fee is not properly accounted for, the behavior is different.
3281 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3282 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3284 // We need a route consisting of 2 paths:
3285 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3286 // We will route 200 sats, Each path will have 100 sats capacity.
3288 // This test is not particularly stable: e.g.,
3289 // there's a way to route via {node0, node2, node4}.
3290 // It works while pathfinding is deterministic, but can be broken otherwise.
3291 // It's fine to ignore this concern for now.
3293 // Disable other potential paths.
3294 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3295 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3296 short_channel_id: 2,
3299 cltv_expiry_delta: 0,
3300 htlc_minimum_msat: 0,
3301 htlc_maximum_msat: OptionalField::Present(100_000),
3303 fee_proportional_millionths: 0,
3304 excess_data: Vec::new()
3307 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3309 short_channel_id: 7,
3312 cltv_expiry_delta: 0,
3313 htlc_minimum_msat: 0,
3314 htlc_maximum_msat: OptionalField::Present(100_000),
3316 fee_proportional_millionths: 0,
3317 excess_data: Vec::new()
3320 // Path via {node0, node2} is channels {1, 3, 5}.
3321 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3322 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3323 short_channel_id: 1,
3326 cltv_expiry_delta: 0,
3327 htlc_minimum_msat: 0,
3328 htlc_maximum_msat: OptionalField::Present(100_000),
3330 fee_proportional_millionths: 0,
3331 excess_data: Vec::new()
3333 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3334 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3335 short_channel_id: 3,
3338 cltv_expiry_delta: 0,
3339 htlc_minimum_msat: 0,
3340 htlc_maximum_msat: OptionalField::Present(100_000),
3342 fee_proportional_millionths: 0,
3343 excess_data: Vec::new()
3346 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3347 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3348 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3349 short_channel_id: 5,
3352 cltv_expiry_delta: 0,
3353 htlc_minimum_msat: 0,
3354 htlc_maximum_msat: OptionalField::Present(100_000),
3356 fee_proportional_millionths: 0,
3357 excess_data: Vec::new()
3360 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3361 // All channels should be 100 sats capacity. But for the fee experiment,
3362 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3363 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3364 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3365 // so no matter how large are other channels,
3366 // the whole path will be limited by 100 sats with just these 2 conditions:
3367 // - channel 12 capacity is 250 sats
3368 // - fee for channel 6 is 150 sats
3369 // Let's test this by enforcing these 2 conditions and removing other limits.
3370 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3372 short_channel_id: 12,
3375 cltv_expiry_delta: 0,
3376 htlc_minimum_msat: 0,
3377 htlc_maximum_msat: OptionalField::Present(250_000),
3379 fee_proportional_millionths: 0,
3380 excess_data: Vec::new()
3382 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3384 short_channel_id: 13,
3387 cltv_expiry_delta: 0,
3388 htlc_minimum_msat: 0,
3389 htlc_maximum_msat: OptionalField::Absent,
3391 fee_proportional_millionths: 0,
3392 excess_data: Vec::new()
3395 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3397 short_channel_id: 6,
3400 cltv_expiry_delta: 0,
3401 htlc_minimum_msat: 0,
3402 htlc_maximum_msat: OptionalField::Absent,
3403 fee_base_msat: 150_000,
3404 fee_proportional_millionths: 0,
3405 excess_data: Vec::new()
3407 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3408 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3409 short_channel_id: 11,
3412 cltv_expiry_delta: 0,
3413 htlc_minimum_msat: 0,
3414 htlc_maximum_msat: OptionalField::Absent,
3416 fee_proportional_millionths: 0,
3417 excess_data: Vec::new()
3421 // Attempt to route more than available results in a failure.
3422 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3423 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3424 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3425 } else { panic!(); }
3429 // Now, attempt to route 200 sats (exact amount we can route).
3430 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3431 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3432 assert_eq!(route.paths.len(), 2);
3434 let mut total_amount_paid_msat = 0;
3435 for path in &route.paths {
3436 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3437 total_amount_paid_msat += path.last().unwrap().fee_msat;
3439 assert_eq!(total_amount_paid_msat, 200_000);
3445 fn drop_lowest_channel_mpp_route_test() {
3446 // This test checks that low-capacity channel is dropped when after
3447 // path finding we realize that we found more capacity than we need.
3448 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3449 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3451 // We need a route consisting of 3 paths:
3452 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3454 // The first and the second paths should be sufficient, but the third should be
3455 // cheaper, so that we select it but drop later.
3457 // First, we set limits on these (previously unlimited) channels.
3458 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3460 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
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: 1,
3466 cltv_expiry_delta: 0,
3467 htlc_minimum_msat: 0,
3468 htlc_maximum_msat: OptionalField::Present(100_000),
3470 fee_proportional_millionths: 0,
3471 excess_data: Vec::new()
3473 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3475 short_channel_id: 3,
3478 cltv_expiry_delta: 0,
3479 htlc_minimum_msat: 0,
3480 htlc_maximum_msat: OptionalField::Present(50_000),
3482 fee_proportional_millionths: 0,
3483 excess_data: Vec::new()
3486 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3487 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3489 short_channel_id: 12,
3492 cltv_expiry_delta: 0,
3493 htlc_minimum_msat: 0,
3494 htlc_maximum_msat: OptionalField::Present(60_000),
3496 fee_proportional_millionths: 0,
3497 excess_data: Vec::new()
3499 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3501 short_channel_id: 13,
3504 cltv_expiry_delta: 0,
3505 htlc_minimum_msat: 0,
3506 htlc_maximum_msat: OptionalField::Present(60_000),
3508 fee_proportional_millionths: 0,
3509 excess_data: Vec::new()
3512 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3513 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3515 short_channel_id: 2,
3518 cltv_expiry_delta: 0,
3519 htlc_minimum_msat: 0,
3520 htlc_maximum_msat: OptionalField::Present(20_000),
3522 fee_proportional_millionths: 0,
3523 excess_data: Vec::new()
3525 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3526 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3527 short_channel_id: 4,
3530 cltv_expiry_delta: 0,
3531 htlc_minimum_msat: 0,
3532 htlc_maximum_msat: OptionalField::Present(20_000),
3534 fee_proportional_millionths: 0,
3535 excess_data: Vec::new()
3539 // Attempt to route more than available results in a failure.
3540 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3541 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3542 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3543 } else { panic!(); }
3547 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3548 // Our algorithm should provide us with these 3 paths.
3549 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3550 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3551 assert_eq!(route.paths.len(), 3);
3552 let mut total_amount_paid_msat = 0;
3553 for path in &route.paths {
3554 assert_eq!(path.len(), 2);
3555 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3556 total_amount_paid_msat += path.last().unwrap().fee_msat;
3558 assert_eq!(total_amount_paid_msat, 125_000);
3562 // Attempt to route without the last small cheap channel
3563 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3564 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3565 assert_eq!(route.paths.len(), 2);
3566 let mut total_amount_paid_msat = 0;
3567 for path in &route.paths {
3568 assert_eq!(path.len(), 2);
3569 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3570 total_amount_paid_msat += path.last().unwrap().fee_msat;
3572 assert_eq!(total_amount_paid_msat, 90_000);
3577 fn min_criteria_consistency() {
3578 // Test that we don't use an inconsistent metric between updating and walking nodes during
3579 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3580 // was updated with a different criterion from the heap sorting, resulting in loops in
3581 // calculated paths. We test for that specific case here.
3583 // We construct a network that looks like this:
3585 // node2 -1(3)2- node3
3589 // node1 -1(5)2- node4 -1(1)2- node6
3595 // We create a loop on the side of our real path - our destination is node 6, with a
3596 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3597 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3598 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3599 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3600 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3601 // "previous hop" being set to node 3, creating a loop in the path.
3602 let secp_ctx = Secp256k1::new();
3603 let logger = Arc::new(test_utils::TestLogger::new());
3604 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3605 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3607 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3608 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3609 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3610 short_channel_id: 6,
3613 cltv_expiry_delta: (6 << 8) | 0,
3614 htlc_minimum_msat: 0,
3615 htlc_maximum_msat: OptionalField::Absent,
3617 fee_proportional_millionths: 0,
3618 excess_data: Vec::new()
3620 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3622 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3623 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3624 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3625 short_channel_id: 5,
3628 cltv_expiry_delta: (5 << 8) | 0,
3629 htlc_minimum_msat: 0,
3630 htlc_maximum_msat: OptionalField::Absent,
3632 fee_proportional_millionths: 0,
3633 excess_data: Vec::new()
3635 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3637 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3638 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3639 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3640 short_channel_id: 4,
3643 cltv_expiry_delta: (4 << 8) | 0,
3644 htlc_minimum_msat: 0,
3645 htlc_maximum_msat: OptionalField::Absent,
3647 fee_proportional_millionths: 0,
3648 excess_data: Vec::new()
3650 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3652 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3653 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3654 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3655 short_channel_id: 3,
3658 cltv_expiry_delta: (3 << 8) | 0,
3659 htlc_minimum_msat: 0,
3660 htlc_maximum_msat: OptionalField::Absent,
3662 fee_proportional_millionths: 0,
3663 excess_data: Vec::new()
3665 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3667 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3668 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3669 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3670 short_channel_id: 2,
3673 cltv_expiry_delta: (2 << 8) | 0,
3674 htlc_minimum_msat: 0,
3675 htlc_maximum_msat: OptionalField::Absent,
3677 fee_proportional_millionths: 0,
3678 excess_data: Vec::new()
3681 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3682 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3684 short_channel_id: 1,
3687 cltv_expiry_delta: (1 << 8) | 0,
3688 htlc_minimum_msat: 100,
3689 htlc_maximum_msat: OptionalField::Absent,
3691 fee_proportional_millionths: 0,
3692 excess_data: Vec::new()
3694 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3697 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3698 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
3699 assert_eq!(route.paths.len(), 1);
3700 assert_eq!(route.paths[0].len(), 3);
3702 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3703 assert_eq!(route.paths[0][0].short_channel_id, 6);
3704 assert_eq!(route.paths[0][0].fee_msat, 100);
3705 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3706 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3707 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3709 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3710 assert_eq!(route.paths[0][1].short_channel_id, 5);
3711 assert_eq!(route.paths[0][1].fee_msat, 0);
3712 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3713 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3714 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3716 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3717 assert_eq!(route.paths[0][2].short_channel_id, 1);
3718 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3719 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3720 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3721 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3727 fn exact_fee_liquidity_limit() {
3728 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3729 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3730 // we calculated fees on a higher value, resulting in us ignoring such paths.
3731 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3732 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3734 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3736 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3737 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3738 short_channel_id: 2,
3741 cltv_expiry_delta: 0,
3742 htlc_minimum_msat: 0,
3743 htlc_maximum_msat: OptionalField::Present(85_000),
3745 fee_proportional_millionths: 0,
3746 excess_data: Vec::new()
3749 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3751 short_channel_id: 12,
3754 cltv_expiry_delta: (4 << 8) | 1,
3755 htlc_minimum_msat: 0,
3756 htlc_maximum_msat: OptionalField::Present(270_000),
3758 fee_proportional_millionths: 1000000,
3759 excess_data: Vec::new()
3763 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3764 // 200% fee charged channel 13 in the 1-to-2 direction.
3765 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3766 assert_eq!(route.paths.len(), 1);
3767 assert_eq!(route.paths[0].len(), 2);
3769 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3770 assert_eq!(route.paths[0][0].short_channel_id, 12);
3771 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3772 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3773 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3774 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3776 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3777 assert_eq!(route.paths[0][1].short_channel_id, 13);
3778 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3779 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3780 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3781 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3786 fn htlc_max_reduction_below_min() {
3787 // Test that if, while walking the graph, we reduce the value being sent to meet an
3788 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3789 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3790 // resulting in us thinking there is no possible path, even if other paths exist.
3791 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3792 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3794 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3795 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3796 // then try to send 90_000.
3797 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3799 short_channel_id: 2,
3802 cltv_expiry_delta: 0,
3803 htlc_minimum_msat: 0,
3804 htlc_maximum_msat: OptionalField::Present(80_000),
3806 fee_proportional_millionths: 0,
3807 excess_data: Vec::new()
3809 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3810 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3811 short_channel_id: 4,
3814 cltv_expiry_delta: (4 << 8) | 1,
3815 htlc_minimum_msat: 90_000,
3816 htlc_maximum_msat: OptionalField::Absent,
3818 fee_proportional_millionths: 0,
3819 excess_data: Vec::new()
3823 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3824 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3825 // expensive) channels 12-13 path.
3826 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3827 assert_eq!(route.paths.len(), 1);
3828 assert_eq!(route.paths[0].len(), 2);
3830 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3831 assert_eq!(route.paths[0][0].short_channel_id, 12);
3832 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3833 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3834 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3835 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3837 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3838 assert_eq!(route.paths[0][1].short_channel_id, 13);
3839 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3840 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3841 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3842 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3846 pub(super) fn random_init_seed() -> u64 {
3847 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3848 use core::hash::{BuildHasher, Hasher};
3849 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3850 println!("Using seed of {}", seed);
3853 use util::ser::Readable;
3856 fn generate_routes() {
3857 let mut d = match super::test_utils::get_route_file() {
3864 let graph = NetworkGraph::read(&mut d).unwrap();
3866 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3867 let mut seed = random_init_seed() as usize;
3868 'load_endpoints: for _ in 0..10 {
3870 seed = seed.overflowing_mul(0xdeadbeef).0;
3871 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3872 seed = seed.overflowing_mul(0xdeadbeef).0;
3873 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3874 let amt = seed as u64 % 200_000_000;
3875 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3876 continue 'load_endpoints;
3883 fn generate_routes_mpp() {
3884 let mut d = match super::test_utils::get_route_file() {
3891 let graph = NetworkGraph::read(&mut d).unwrap();
3893 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3894 let mut seed = random_init_seed() as usize;
3895 'load_endpoints: for _ in 0..10 {
3897 seed = seed.overflowing_mul(0xdeadbeef).0;
3898 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3899 seed = seed.overflowing_mul(0xdeadbeef).0;
3900 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3901 let amt = seed as u64 % 200_000_000;
3902 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3903 continue 'load_endpoints;
3911 pub(crate) mod test_utils {
3913 /// Tries to open a network graph file, or panics with a URL to fetch it.
3914 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
3915 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
3916 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
3917 .or_else(|_| { // Fall back to guessing based on the binary location
3918 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3919 let mut path = std::env::current_exe().unwrap();
3920 path.pop(); // lightning-...
3922 path.pop(); // debug
3923 path.pop(); // target
3924 path.push("lightning");
3925 path.push("net_graph-2021-05-31.bin");
3926 eprintln!("{}", path.to_str().unwrap());
3929 .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");
3930 #[cfg(require_route_graph_test)]
3931 return Ok(res.unwrap());
3932 #[cfg(not(require_route_graph_test))]
3937 #[cfg(all(test, feature = "unstable"))]
3940 use util::logger::{Logger, Record};
3944 struct DummyLogger {}
3945 impl Logger for DummyLogger {
3946 fn log(&self, _record: &Record) {}
3950 fn generate_routes(bench: &mut Bencher) {
3951 let mut d = test_utils::get_route_file().unwrap();
3952 let graph = NetworkGraph::read(&mut d).unwrap();
3954 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3955 let mut path_endpoints = Vec::new();
3956 let mut seed: usize = 0xdeadbeef;
3957 'load_endpoints: for _ in 0..100 {
3960 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3962 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3963 let amt = seed as u64 % 1_000_000;
3964 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3965 path_endpoints.push((src, dst, amt));
3966 continue 'load_endpoints;
3971 // ...then benchmark finding paths between the nodes we learned.
3974 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3975 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3981 fn generate_mpp_routes(bench: &mut Bencher) {
3982 let mut d = test_utils::get_route_file().unwrap();
3983 let graph = NetworkGraph::read(&mut d).unwrap();
3985 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3986 let mut path_endpoints = Vec::new();
3987 let mut seed: usize = 0xdeadbeef;
3988 'load_endpoints: for _ in 0..100 {
3991 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3993 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3994 let amt = seed as u64 % 1_000_000;
3995 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3996 path_endpoints.push((src, dst, amt));
3997 continue 'load_endpoints;
4002 // ...then benchmark finding paths between the nodes we learned.
4005 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4006 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());