[router] Avoid re-selecting the same path over and over again
[rust-lightning] / lightning / src / routing / router.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
10 //! The top-level routing/network map tracking logic lives here.
11 //!
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.
14
15 use bitcoin::secp256k1::key::PublicKey;
16
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;
23
24 use std::cmp;
25 use std::collections::{HashMap, BinaryHeap};
26 use std::ops::Deref;
27
28 /// A hop in a route
29 #[derive(Clone, PartialEq)]
30 pub struct RouteHop {
31         /// The node_id of the node at this hop.
32         pub pubkey: PublicKey,
33         /// The node_announcement features of the node at this hop. For the last hop, these may be
34         /// amended to match the features present in the invoice this node generated.
35         pub node_features: NodeFeatures,
36         /// The channel that should be used from the previous hop to reach this node.
37         pub short_channel_id: u64,
38         /// The channel_announcement features of the channel that should be used from the previous hop
39         /// to reach this node.
40         pub channel_features: ChannelFeatures,
41         /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
42         /// For the last hop, this should be the full value of the payment (might be more than
43         /// requested if we had to match htlc_minimum_msat).
44         pub fee_msat: u64,
45         /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
46         /// expected at the destination, in excess of the current block height.
47         pub cltv_expiry_delta: u32,
48 }
49
50 /// (C-not exported)
51 impl Writeable for Vec<RouteHop> {
52         fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
53                 (self.len() as u8).write(writer)?;
54                 for hop in self.iter() {
55                         hop.pubkey.write(writer)?;
56                         hop.node_features.write(writer)?;
57                         hop.short_channel_id.write(writer)?;
58                         hop.channel_features.write(writer)?;
59                         hop.fee_msat.write(writer)?;
60                         hop.cltv_expiry_delta.write(writer)?;
61                 }
62                 Ok(())
63         }
64 }
65
66 /// (C-not exported)
67 impl Readable for Vec<RouteHop> {
68         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
69                 let hops_count: u8 = Readable::read(reader)?;
70                 let mut hops = Vec::with_capacity(hops_count as usize);
71                 for _ in 0..hops_count {
72                         hops.push(RouteHop {
73                                 pubkey: Readable::read(reader)?,
74                                 node_features: Readable::read(reader)?,
75                                 short_channel_id: Readable::read(reader)?,
76                                 channel_features: Readable::read(reader)?,
77                                 fee_msat: Readable::read(reader)?,
78                                 cltv_expiry_delta: Readable::read(reader)?,
79                         });
80                 }
81                 Ok(hops)
82         }
83 }
84
85 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
86 /// it can take multiple paths. Each path is composed of one or more hops through the network.
87 #[derive(Clone, PartialEq)]
88 pub struct Route {
89         /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
90         /// last RouteHop in each path must be the same.
91         /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
92         /// destination. Thus, this must always be at least length one. While the maximum length of any
93         /// given path is variable, keeping the length of any path to less than 20 should currently
94         /// ensure it is viable.
95         pub paths: Vec<Vec<RouteHop>>,
96 }
97
98 impl Writeable for Route {
99         fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
100                 (self.paths.len() as u64).write(writer)?;
101                 for hops in self.paths.iter() {
102                         hops.write(writer)?;
103                 }
104                 Ok(())
105         }
106 }
107
108 impl Readable for Route {
109         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
110                 let path_count: u64 = Readable::read(reader)?;
111                 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
112                 for _ in 0..path_count {
113                         paths.push(Readable::read(reader)?);
114                 }
115                 Ok(Route { paths })
116         }
117 }
118
119 /// A channel descriptor which provides a last-hop route to get_route
120 #[derive(Clone)]
121 pub struct RouteHint {
122         /// The node_id of the non-target end of the route
123         pub src_node_id: PublicKey,
124         /// The short_channel_id of this channel
125         pub short_channel_id: u64,
126         /// The fees which must be paid to use this channel
127         pub fees: RoutingFees,
128         /// The difference in CLTV values between this node and the next node.
129         pub cltv_expiry_delta: u16,
130         /// The minimum value, in msat, which must be relayed to the next hop.
131         pub htlc_minimum_msat: Option<u64>,
132         /// The maximum value in msat available for routing with a single HTLC.
133         pub htlc_maximum_msat: Option<u64>,
134 }
135
136 #[derive(Eq, PartialEq)]
137 struct RouteGraphNode {
138         pubkey: PublicKey,
139         lowest_fee_to_peer_through_node: u64,
140         lowest_fee_to_node: u64,
141         // The maximum value a yet-to-be-constructed payment path might flow through this node.
142         // This value is upper-bounded by us by:
143         // - how much is needed for a path being constructed
144         // - how much value can channels following this node (up to the destination) can contribute,
145         //   considering their capacity and fees
146         value_contribution_msat: u64,
147         /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
148         /// minimum, we use it, plus the fees required at each earlier hop to meet it.
149         path_htlc_minimum_msat: u64,
150 }
151
152 impl cmp::Ord for RouteGraphNode {
153         fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
154                 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
155                         .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
156         }
157 }
158
159 impl cmp::PartialOrd for RouteGraphNode {
160         fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
161                 Some(self.cmp(other))
162         }
163 }
164
165 struct DummyDirectionalChannelInfo {
166         cltv_expiry_delta: u32,
167         htlc_minimum_msat: u64,
168         htlc_maximum_msat: Option<u64>,
169         fees: RoutingFees,
170 }
171
172 /// It's useful to keep track of the hops associated with the fees required to use them,
173 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
174 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
175 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
176 #[derive(Clone)]
177 struct PathBuildingHop {
178         /// Hop-specific details unrelated to the path during the routing phase,
179         /// but rather relevant to the LN graph.
180         route_hop: RouteHop,
181         /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
182         src_lowest_inbound_fees: RoutingFees,
183         /// Fees of the channel used in this hop.
184         channel_fees: RoutingFees,
185         /// All the fees paid *after* this channel on the way to the destination
186         next_hops_fee_msat: u64,
187         /// Fee paid for the use of the current channel (see channel_fees).
188         /// The value will be actually deducted from the counterparty balance on the previous link.
189         hop_use_fee_msat: u64,
190         /// Used to compare channels when choosing the for routing.
191         /// Includes paying for the use of a hop and the following hops, as well as
192         /// an estimated cost of reaching this hop.
193         /// Might get stale when fees are recomputed. Primarily for internal use.
194         total_fee_msat: u64,
195         /// This is useful for update_value_and_recompute_fees to make sure
196         /// we don't fall below the minimum. Should not be updated manually and
197         /// generally should not be accessed.
198         htlc_minimum_msat: u64,
199 }
200
201 // Instantiated with a list of hops with correct data in them collected during path finding,
202 // an instance of this struct should be further modified only via given methods.
203 #[derive(Clone)]
204 struct PaymentPath {
205         hops: Vec<PathBuildingHop>,
206 }
207
208 impl PaymentPath {
209
210         // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
211         fn get_value_msat(&self) -> u64 {
212                 self.hops.last().unwrap().route_hop.fee_msat
213         }
214
215         fn get_total_fee_paid_msat(&self) -> u64 {
216                 if self.hops.len() < 1 {
217                         return 0;
218                 }
219                 let mut result = 0;
220                 // Can't use next_hops_fee_msat because it gets outdated.
221                 for (i, hop) in self.hops.iter().enumerate() {
222                         if i != self.hops.len() - 1 {
223                                 result += hop.route_hop.fee_msat;
224                         }
225                 }
226                 return result;
227         }
228
229         // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
230         // to change fees may result in an inconsistency.
231         //
232         // Sometimes we call this function right after constructing a path which has inconsistent
233         // (in terms of reaching htlc_minimum_msat), so that this function puts the fees in order.
234         // In that case we call it on the "same" amount we initially allocated for this path, and which
235         // could have been reduced on the way. In that case, there is also a risk of exceeding
236         // available_liquidity inside this function, because the function is unaware of this bound.
237         // In our specific recomputation cases where we never increase the value the risk is pretty low.
238         // This function, however, does not support arbitrarily increasing the value being transferred,
239         // and the exception will be triggered.
240         fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
241                 assert!(value_msat <= self.hops.last().unwrap().route_hop.fee_msat);
242
243                 let mut total_fee_paid_msat = 0 as u64;
244                 for i in (0..self.hops.len()).rev() {
245                         let last_hop = i == self.hops.len() - 1;
246
247                         // For non-last-hop, this value will represent the fees paid on the current hop. It
248                         // will consist of the fees for the use of the next hop, and extra fees to match
249                         // htlc_minimum_msat of the current channel. Last hop is handled separately.
250                         let mut cur_hop_fees_msat = 0;
251                         if !last_hop {
252                                 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().hop_use_fee_msat;
253                         }
254
255                         let mut cur_hop = self.hops.get_mut(i).unwrap();
256                         cur_hop.next_hops_fee_msat = total_fee_paid_msat;
257                         // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
258                         // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
259                         // set it too high just to maliciously take more fees by exploiting this
260                         // match htlc_minimum_msat logic.
261                         let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
262                         if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
263                                 // Note that there is a risk that *previous hops* (those closer to us, as we go
264                                 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
265                                 //
266                                 // This might make us end up with a broken route, although this should be super-rare
267                                 // in practice, both because of how healthy channels look like, and how we pick
268                                 // channels in add_entry.
269                                 // Also, this can't be exploited more heavily than *announce a free path and fail
270                                 // all payments*.
271                                 cur_hop_transferred_amount_msat += extra_fees_msat;
272                                 total_fee_paid_msat += extra_fees_msat;
273                                 cur_hop_fees_msat += extra_fees_msat;
274                         }
275
276                         if last_hop {
277                                 // Final hop is a special case: it usually has just value_msat (by design), but also
278                                 // it still could overpay for the htlc_minimum_msat.
279                                 cur_hop.route_hop.fee_msat = cur_hop_transferred_amount_msat;
280                         } else {
281                                 // Propagate updated fees for the use of the channels to one hop back, where they
282                                 // will be actually paid (fee_msat). The last hop is handled above separately.
283                                 cur_hop.route_hop.fee_msat = cur_hop_fees_msat;
284                         }
285
286                         // Fee for the use of the current hop which will be deducted on the previous hop.
287                         // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
288                         // this channel is free for us.
289                         if i != 0 {
290                                 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
291                                         cur_hop.hop_use_fee_msat = new_fee;
292                                         total_fee_paid_msat += new_fee;
293                                 } else {
294                                         // It should not be possible because this function is called only to reduce the
295                                         // value. In that case, compute_fee was already called with the same fees for
296                                         // larger amount and there was no overflow.
297                                         unreachable!();
298                                 }
299                         }
300                 }
301         }
302 }
303
304 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
305         let proportional_fee_millions =
306                 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
307         if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
308                         (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
309
310                 Some(new_fee)
311         } else {
312                 // This function may be (indirectly) called without any verification,
313                 // with channel_fees provided by a caller. We should handle it gracefully.
314                 None
315         }
316 }
317
318 /// Gets a route from us (payer) to the given target node (payee).
319 ///
320 /// If the payee provided features in their invoice, they should be provided via payee_features.
321 /// Without this, MPP will only be used if the payee's features are available in the network graph.
322 ///
323 /// Extra routing hops between known nodes and the target will be used if they are included in
324 /// last_hops.
325 ///
326 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
327 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
328 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
329 /// in first_hops will be used.
330 ///
331 /// Panics if first_hops contains channels without short_channel_ids
332 /// (ChannelManager::list_usable_channels will never include such channels).
333 ///
334 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
335 /// equal), however the enabled/disabled bit on such channels as well as the
336 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
337 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
338         last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
339         // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
340         // uptime/success in using a node in the past.
341         if *payee == *our_node_id {
342                 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
343         }
344
345         if final_value_msat > MAX_VALUE_MSAT {
346                 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
347         }
348
349         if final_value_msat == 0 {
350                 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
351         }
352
353         for last_hop in last_hops {
354                 if last_hop.src_node_id == *payee {
355                         return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
356                 }
357         }
358
359         // The general routing idea is the following:
360         // 1. Fill first/last hops communicated by the caller.
361         // 2. Attempt to construct a path from payer to payee for transferring
362         //    any ~sufficient (described later) value.
363         //    If succeed, remember which channels were used and how much liquidity they have available,
364         //    so that future paths don't rely on the same liquidity.
365         // 3. Prooceed to the next step if:
366         //    - we hit the recommended target value;
367         //    - OR if we could not construct a new path. Any next attempt will fail too.
368         //    Otherwise, repeat step 2.
369         // 4. See if we managed to collect paths which aggregately are able to transfer target value
370         //    (not recommended value). If yes, proceed. If not, fail routing.
371         // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
372         // 6. Of all the found paths, select only those with the lowest total fee.
373         // 7. The last path in every selected route is likely to be more than we need.
374         //    Reduce its value-to-transfer and recompute fees.
375         // 8. Choose the best route by the lowest total fee.
376
377         // As for the actual search algorithm,
378         // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
379         // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
380         //
381         // We are not a faithful Dijkstra's implementation because we can change values which impact
382         // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
383         // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
384         // the value we are currently attempting to send over a path, we simply reduce the value being
385         // sent along the path for any hops after that channel. This may imply that later fees (which
386         // we've already tabulated) are lower because a smaller value is passing through the channels
387         // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
388         // channels which were selected earlier (and which may still be used for other paths without a
389         // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
390         // de-preferenced.
391         //
392         // One potentially problematic case for this algorithm would be if there are many
393         // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
394         // graph walking), we may never find a path which is not liquidity-limited and has lower
395         // proportional fee (and only lower absolute fee when considering the ultimate value sent).
396         // Because we only consider paths with at least 5% of the total value being sent, the damage
397         // from such a case should be limited, however this could be further reduced in the future by
398         // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
399         // limits for the purposes of fee calculation.
400         //
401         // Alternatively, we could store more detailed path information in the heap (targets, below)
402         // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
403         // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
404         // and practically (as we would need to store dynamically-allocated path information in heap
405         // objects, increasing malloc traffic and indirect memory access significantly). Further, the
406         // results of such an algorithm would likely be biased towards lower-value paths.
407         //
408         // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
409         // outside of our current search value, running a path search more times to gather candidate
410         // paths at different values. While this may be acceptable, further path searches may increase
411         // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
412         // graph for candidate paths, calculating the maximum value which can realistically be sent at
413         // the same time, remaining generic across different payment values.
414         //
415         // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
416         // to use as the A* heuristic beyond just the cost to get one node further than the current
417         // one.
418
419         let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
420                 cltv_expiry_delta: 0,
421                 htlc_minimum_msat: 0,
422                 htlc_maximum_msat: None,
423                 fees: RoutingFees {
424                         base_msat: 0,
425                         proportional_millionths: 0,
426                 }
427         };
428
429         let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
430         let mut dist = HashMap::with_capacity(network.get_nodes().len());
431
432         // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
433         // indicating that we may wish to try again with a higher value, potentially paying to meet an
434         // htlc_minimum with extra fees while still finding a cheaper path.
435         let mut hit_minimum_limit;
436
437         // When arranging a route, we select multiple paths so that we can make a multi-path payment.
438         // We start with a path_value of the exact amount we want, and if that generates a route we may
439         // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
440         // amount we want in total across paths, selecting the best subset at the end.
441         const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
442         let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
443         let mut path_value_msat = final_value_msat;
444
445         // Allow MPP only if we have a features set from somewhere that indicates the payee supports
446         // it. If the payee supports it they're supposed to include it in the invoice, so that should
447         // work reliably.
448         let allow_mpp = if let Some(features) = &payee_features {
449                 features.supports_basic_mpp()
450         } else if let Some(node) = network.get_nodes().get(&payee) {
451                 if let Some(node_info) = node.announcement_info.as_ref() {
452                         node_info.features.supports_basic_mpp()
453                 } else { false }
454         } else { false };
455
456         // Step (1).
457         // Prepare the data we'll use for payee-to-payer search by
458         // inserting first hops suggested by the caller as targets.
459         // Our search will then attempt to reach them while traversing from the payee node.
460         let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
461         if let Some(hops) = first_hops {
462                 for chan in hops {
463                         let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
464                         if chan.remote_network_id == *our_node_id {
465                                 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
466                         }
467                         first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone(), chan.outbound_capacity_msat));
468                 }
469                 if first_hop_targets.is_empty() {
470                         return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
471                 }
472         }
473
474         // We don't want multiple paths (as per MPP) share liquidity of the same channels.
475         // This map allows paths to be aware of the channel use by other paths in the same call.
476         // This would help to make a better path finding decisions and not "overbook" channels.
477         // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
478         let mut bookkeeped_channels_liquidity_available_msat = HashMap::new();
479
480         // Keeping track of how much value we already collected across other paths. Helps to decide:
481         // - how much a new path should be transferring (upper bound);
482         // - whether a channel should be disregarded because
483         //   it's available liquidity is too small comparing to how much more we need to collect;
484         // - when we want to stop looking for new paths.
485         let mut already_collected_value_msat = 0;
486
487         macro_rules! add_entry {
488                 // Adds entry which goes from $src_node_id to $dest_node_id
489                 // over the channel with id $chan_id with fees described in
490                 // $directional_info.
491                 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
492                 // since that value has to be transferred over this channel.
493                 ( $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,
494                    $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
495                         // Channels to self should not be used. This is more of belt-and-suspenders, because in
496                         // practice these cases should be caught earlier:
497                         // - for regular channels at channel announcement (TODO)
498                         // - for first and last hops early in get_route
499                         if $src_node_id != $dest_node_id.clone() {
500                                 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
501                                         let mut initial_liquidity_available_msat = None;
502                                         if let Some(capacity_sats) = $capacity_sats {
503                                                 initial_liquidity_available_msat = Some(capacity_sats * 1000);
504                                         }
505
506                                         if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
507                                                 if let Some(available_msat) = initial_liquidity_available_msat {
508                                                         initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
509                                                 } else {
510                                                         initial_liquidity_available_msat = Some(htlc_maximum_msat);
511                                                 }
512                                         }
513
514                                         match initial_liquidity_available_msat {
515                                                 Some(available_msat) => available_msat,
516                                                 // We assume channels with unknown balance have
517                                                 // a capacity of 0.0025 BTC (or 250_000 sats).
518                                                 None => 250_000 * 1000
519                                         }
520                                 });
521
522                                 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
523                                 // It may be misleading because we might later choose to reduce the value transferred
524                                 // over these channels, and the channel which was insufficient might become sufficient.
525                                 // Worst case: we drop a good channel here because it can't cover the high following
526                                 // fees caused by one expensive channel, but then this channel could have been used
527                                 // if the amount being transferred over this path is lower.
528                                 // We do this for now, but this is a subject for removal.
529                                 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
530
531                                         // Routing Fragmentation Mitigation heuristic:
532                                         //
533                                         // Routing fragmentation across many payment paths increases the overall routing
534                                         // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
535                                         // Taking too many smaller paths also increases the chance of payment failure.
536                                         // Thus to avoid this effect, we require from our collected links to provide
537                                         // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
538                                         //
539                                         // This requirement is currently 5% of the remaining-to-be-collected value.
540                                         // This means as we successfully advance in our collection,
541                                         // the absolute liquidity contribution is lowered,
542                                         // thus increasing the number of potential channels to be selected.
543
544                                         // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
545                                         // or 100% if we're not allowed to do multipath payments.
546                                         let minimal_value_contribution_msat: u64 = if allow_mpp {
547                                                 (recommended_value_msat - already_collected_value_msat + 19) / 20
548                                         } else {
549                                                 final_value_msat
550                                         };
551                                         // Verify the liquidity offered by this channel complies to the minimal contribution.
552                                         let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
553
554                                         let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
555                                         // Includes paying fees for the use of the following channels.
556                                         let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
557                                                 Some(result) => result,
558                                                 // Can't overflow due to how the values were computed right above.
559                                                 None => unreachable!(),
560                                         };
561                                         #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
562                                         let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
563                                                 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
564
565                                         // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
566                                         // bother considering this channel.
567                                         // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
568                                         // be only reduced later (not increased), so this channel should just be skipped
569                                         // as not sufficient.
570                                         if !over_path_minimum_msat {
571                                                 hit_minimum_limit = true;
572                                         } else if contributes_sufficient_value {
573                                                 // Note that low contribution here (limited by available_liquidity_msat)
574                                                 // might violate htlc_minimum_msat on the hops which are next along the
575                                                 // payment path (upstream to the payee). To avoid that, we recompute path
576                                                 // path fees knowing the final path contribution after constructing it.
577                                                 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
578                                                                 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
579                                                         Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
580                                                         _ => u64::max_value()
581                                                 };
582                                                 let hm_entry = dist.entry(&$src_node_id);
583                                                 let old_entry = hm_entry.or_insert_with(|| {
584                                                         // If there was previously no known way to access
585                                                         // the source node (recall it goes payee-to-payer) of $chan_id, first add
586                                                         // a semi-dummy record just to compute the fees to reach the source node.
587                                                         // This will affect our decision on selecting $chan_id
588                                                         // as a way to reach the $dest_node_id.
589                                                         let mut fee_base_msat = u32::max_value();
590                                                         let mut fee_proportional_millionths = u32::max_value();
591                                                         if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
592                                                                 fee_base_msat = fees.base_msat;
593                                                                 fee_proportional_millionths = fees.proportional_millionths;
594                                                         }
595                                                         PathBuildingHop {
596                                                                 route_hop: RouteHop {
597                                                                         pubkey: $dest_node_id.clone(),
598                                                                         node_features: NodeFeatures::empty(),
599                                                                         short_channel_id: 0,
600                                                                         channel_features: $chan_features.clone(),
601                                                                         fee_msat: 0,
602                                                                         cltv_expiry_delta: 0,
603                                                                 },
604                                                                 src_lowest_inbound_fees: RoutingFees {
605                                                                         base_msat: fee_base_msat,
606                                                                         proportional_millionths: fee_proportional_millionths,
607                                                                 },
608                                                                 channel_fees: $directional_info.fees,
609                                                                 next_hops_fee_msat: u64::max_value(),
610                                                                 hop_use_fee_msat: u64::max_value(),
611                                                                 total_fee_msat: u64::max_value(),
612                                                                 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
613                                                         }
614                                                 });
615
616                                                 let mut hop_use_fee_msat = 0;
617                                                 let mut total_fee_msat = $next_hops_fee_msat;
618
619                                                 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
620                                                 // will have the same effective-fee
621                                                 if $src_node_id != *our_node_id {
622                                                         match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
623                                                                 // max_value means we'll always fail
624                                                                 // the old_entry.total_fee_msat > total_fee_msat check
625                                                                 None => total_fee_msat = u64::max_value(),
626                                                                 Some(fee_msat) => {
627                                                                         hop_use_fee_msat = fee_msat;
628                                                                         total_fee_msat += hop_use_fee_msat;
629                                                                         if let Some(prev_hop_fee_msat) = compute_fees(total_fee_msat + amount_to_transfer_over_msat,
630                                                                                                                                                                 old_entry.src_lowest_inbound_fees) {
631                                                                                 if let Some(incremented_total_fee_msat) = total_fee_msat.checked_add(prev_hop_fee_msat) {
632                                                                                         total_fee_msat = incremented_total_fee_msat;
633                                                                                 }
634                                                                                 else {
635                                                                                         // max_value means we'll always fail
636                                                                                         // the old_entry.total_fee_msat > total_fee_msat check
637                                                                                         total_fee_msat = u64::max_value();
638                                                                                 }
639                                                                         } else {
640                                                                                 // max_value means we'll always fail
641                                                                                 // the old_entry.total_fee_msat > total_fee_msat check
642                                                                                 total_fee_msat = u64::max_value();
643                                                                         }
644                                                                 }
645                                                         }
646                                                 }
647
648                                                 let new_graph_node = RouteGraphNode {
649                                                         pubkey: $src_node_id,
650                                                         lowest_fee_to_peer_through_node: total_fee_msat,
651                                                         lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
652                                                         value_contribution_msat: value_contribution_msat,
653                                                         path_htlc_minimum_msat,
654                                                 };
655
656                                                 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
657                                                 // if this way is cheaper than the already known
658                                                 // (considering the cost to "reach" this channel from the route destination,
659                                                 // the cost of using this channel,
660                                                 // and the cost of routing to the source node of this channel).
661                                                 // Also, consider that htlc_minimum_msat_difference, because we might end up
662                                                 // paying it. Consider the following exploit:
663                                                 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
664                                                 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
665                                                 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
666                                                 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
667                                                 // to this channel.
668                                                 // TODO: this scoring could be smarter (e.g. 0.5*htlc_minimum_msat here).
669                                                 let mut old_cost = old_entry.total_fee_msat;
670                                                 if let Some(increased_old_cost) = old_cost.checked_add(old_entry.htlc_minimum_msat) {
671                                                         old_cost = increased_old_cost;
672                                                 } else {
673                                                         old_cost = u64::max_value();
674                                                 }
675
676                                                 let mut new_cost = total_fee_msat;
677                                                 if let Some(increased_new_cost) = new_cost.checked_add($directional_info.htlc_minimum_msat) {
678                                                         new_cost = increased_new_cost;
679                                                 } else {
680                                                         new_cost = u64::max_value();
681                                                 }
682
683                                                 if new_cost < old_cost {
684                                                         targets.push(new_graph_node);
685                                                         old_entry.next_hops_fee_msat = $next_hops_fee_msat;
686                                                         old_entry.hop_use_fee_msat = hop_use_fee_msat;
687                                                         old_entry.total_fee_msat = total_fee_msat;
688                                                         old_entry.route_hop = RouteHop {
689                                                                 pubkey: $dest_node_id.clone(),
690                                                                 node_features: NodeFeatures::empty(),
691                                                                 short_channel_id: $chan_id.clone(),
692                                                                 channel_features: $chan_features.clone(),
693                                                                 fee_msat: 0, // This value will be later filled with hop_use_fee_msat of the following channel
694                                                                 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
695                                                         };
696                                                         old_entry.channel_fees = $directional_info.fees;
697                                                         // It's probably fine to replace the old entry, because the new one
698                                                         // passed the htlc_minimum-related checks above.
699                                                         old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
700                                                 }
701                                         }
702                                 }
703                         }
704                 };
705         }
706
707         // Find ways (channels with destination) to reach a given node and store them
708         // in the corresponding data structures (routing graph etc).
709         // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
710         // meaning how much will be paid in fees after this node (to the best of our knowledge).
711         // This data can later be helpful to optimize routing (pay lower fees).
712         macro_rules! add_entries_to_cheapest_to_target_node {
713                 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
714                         if first_hops.is_some() {
715                                 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&$node_id) {
716                                         add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
717                                 }
718                         }
719
720                         let features;
721                         if let Some(node_info) = $node.announcement_info.as_ref() {
722                                 features = node_info.features.clone();
723                         } else {
724                                 features = NodeFeatures::empty();
725                         }
726
727                         if !features.requires_unknown_bits() {
728                                 for chan_id in $node.channels.iter() {
729                                         let chan = network.get_channels().get(chan_id).unwrap();
730                                         if !chan.features.requires_unknown_bits() {
731                                                 if chan.node_one == *$node_id {
732                                                         // ie $node is one, ie next hop in A* is two, via the two_to_one channel
733                                                         if first_hops.is_none() || chan.node_two != *our_node_id {
734                                                                 if let Some(two_to_one) = chan.two_to_one.as_ref() {
735                                                                         if two_to_one.enabled {
736                                                                                 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);
737                                                                         }
738                                                                 }
739                                                         }
740                                                 } else {
741                                                         if first_hops.is_none() || chan.node_one != *our_node_id {
742                                                                 if let Some(one_to_two) = chan.one_to_two.as_ref() {
743                                                                         if one_to_two.enabled {
744                                                                                 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);
745                                                                         }
746                                                                 }
747
748                                                         }
749                                                 }
750                                         }
751                                 }
752                         }
753                 };
754         }
755
756         let mut payment_paths = Vec::<PaymentPath>::new();
757
758         // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
759         'paths_collection: loop {
760                 // For every new path, start from scratch, except
761                 // bookkeeped_channels_liquidity_available_msat, which will improve
762                 // the further iterations of path finding. Also don't erase first_hop_targets.
763                 targets.clear();
764                 dist.clear();
765                 hit_minimum_limit = false;
766
767                 // If first hop is a private channel and the only way to reach the payee, this is the only
768                 // place where it could be added.
769                 if first_hops.is_some() {
770                         if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&payee) {
771                                 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, path_value_msat, 0);
772                         }
773                 }
774
775                 // Add the payee as a target, so that the payee-to-payer
776                 // search algorithm knows what to start with.
777                 match network.get_nodes().get(payee) {
778                         // The payee is not in our network graph, so nothing to add here.
779                         // There is still a chance of reaching them via last_hops though,
780                         // so don't yet fail the payment here.
781                         // If not, targets.pop() will not even let us enter the loop in step 2.
782                         None => {},
783                         Some(node) => {
784                                 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
785                         },
786                 }
787
788                 // Step (1).
789                 // If a caller provided us with last hops, add them to routing targets. Since this happens
790                 // earlier than general path finding, they will be somewhat prioritized, although currently
791                 // it matters only if the fees are exactly the same.
792                 for hop in last_hops.iter() {
793                         let have_hop_src_in_graph =
794                                 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&hop.src_node_id) {
795                                         // If this hop connects to a node with which we have a direct channel, ignore
796                                         // the network graph and add both the hop and our direct channel to
797                                         // the candidate set.
798                                         //
799                                         // Currently there are no channel-context features defined, so we are a
800                                         // bit lazy here. In the future, we should pull them out via our
801                                         // ChannelManager, but there's no reason to waste the space until we
802                                         // need them.
803                                         add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, path_value_msat, 0);
804                                         true
805                                 } else {
806                                         // In any other case, only add the hop if the source is in the regular network
807                                         // graph:
808                                         network.get_nodes().get(&hop.src_node_id).is_some()
809                                 };
810                         if have_hop_src_in_graph {
811                                 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
812                                 // really sucks, cause we're gonna need that eventually.
813                                 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
814                                         Some(htlc_minimum_msat) => htlc_minimum_msat,
815                                         None => 0
816                                 };
817                                 let directional_info = DummyDirectionalChannelInfo {
818                                         cltv_expiry_delta: hop.cltv_expiry_delta as u32,
819                                         htlc_minimum_msat: last_hop_htlc_minimum_msat,
820                                         htlc_maximum_msat: hop.htlc_maximum_msat,
821                                         fees: hop.fees,
822                                 };
823                                 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, ChannelFeatures::empty(), 0, path_value_msat, 0);
824                         }
825                 }
826
827                 // At this point, targets are filled with the data from first and
828                 // last hops communicated by the caller, and the payment receiver.
829                 let mut found_new_path = false;
830
831                 // Step (2).
832                 // If this loop terminates due the exhaustion of targets, two situations are possible:
833                 // - not enough outgoing liquidity:
834                 //   0 < already_collected_value_msat < final_value_msat
835                 // - enough outgoing liquidity:
836                 //   final_value_msat <= already_collected_value_msat < recommended_value_msat
837                 // Both these cases (and other cases except reaching recommended_value_msat) mean that
838                 // paths_collection will be stopped because found_new_path==false.
839                 // This is not necessarily a routing failure.
840                 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
841
842                         // Since we're going payee-to-payer, hitting our node as a target means we should stop
843                         // traversing the graph and arrange the path out of what we found.
844                         if pubkey == *our_node_id {
845                                 let mut new_entry = dist.remove(&our_node_id).unwrap();
846                                 let mut ordered_hops = vec!(new_entry.clone());
847
848                                 'path_walk: loop {
849                                         if let Some(&(_, ref features, _)) = first_hop_targets.get(&ordered_hops.last().unwrap().route_hop.pubkey) {
850                                                 ordered_hops.last_mut().unwrap().route_hop.node_features = features.to_context();
851                                         } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().route_hop.pubkey) {
852                                                 if let Some(node_info) = node.announcement_info.as_ref() {
853                                                         ordered_hops.last_mut().unwrap().route_hop.node_features = node_info.features.clone();
854                                                 } else {
855                                                         ordered_hops.last_mut().unwrap().route_hop.node_features = NodeFeatures::empty();
856                                                 }
857                                         } else {
858                                                 // We should be able to fill in features for everything except the last
859                                                 // hop, if the last hop was provided via a BOLT 11 invoice (though we
860                                                 // should be able to extend it further as BOLT 11 does have feature
861                                                 // flags for the last hop node itself).
862                                                 assert!(ordered_hops.last().unwrap().route_hop.pubkey == *payee);
863                                         }
864
865                                         // Means we succesfully traversed from the payer to the payee, now
866                                         // save this path for the payment route. Also, update the liquidity
867                                         // remaining on the used hops, so that we take them into account
868                                         // while looking for more paths.
869                                         if ordered_hops.last().unwrap().route_hop.pubkey == *payee {
870                                                 break 'path_walk;
871                                         }
872
873                                         new_entry = match dist.remove(&ordered_hops.last().unwrap().route_hop.pubkey) {
874                                                 Some(payment_hop) => payment_hop,
875                                                 // We can't arrive at None because, if we ever add an entry to targets,
876                                                 // we also fill in the entry in dist (see add_entry!).
877                                                 None => unreachable!(),
878                                         };
879                                         // We "propagate" the fees one hop backward (topologically) here,
880                                         // so that fees paid for a HTLC forwarding on the current channel are
881                                         // associated with the previous channel (where they will be subtracted).
882                                         ordered_hops.last_mut().unwrap().route_hop.fee_msat = new_entry.hop_use_fee_msat;
883                                         ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = new_entry.route_hop.cltv_expiry_delta;
884                                         ordered_hops.push(new_entry.clone());
885                                 }
886                                 ordered_hops.last_mut().unwrap().route_hop.fee_msat = value_contribution_msat;
887                                 ordered_hops.last_mut().unwrap().hop_use_fee_msat = 0;
888                                 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = final_cltv;
889
890                                 let mut payment_path = PaymentPath {hops: ordered_hops};
891
892                                 // We could have possibly constructed a slightly inconsistent path: since we reduce
893                                 // value being transferred along the way, we could have violated htlc_minimum_msat
894                                 // on some channels we already passed (assuming dest->source direction). Here, we
895                                 // recompute the fees again, so that if that's the case, we match the currently
896                                 // underpaid htlc_minimum_msat with fees.
897                                 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
898
899                                 // Since a path allows to transfer as much value as
900                                 // the smallest channel it has ("bottleneck"), we should recompute
901                                 // the fees so sender HTLC don't overpay fees when traversing
902                                 // larger channels than the bottleneck. This may happen because
903                                 // when we were selecting those channels we were not aware how much value
904                                 // this path will transfer, and the relative fee for them
905                                 // might have been computed considering a larger value.
906                                 // Remember that we used these channels so that we don't rely
907                                 // on the same liquidity in future paths.
908                                 let mut prevented_redundant_path_selection = false;
909                                 for payment_hop in payment_path.hops.iter() {
910                                         let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.route_hop.short_channel_id).unwrap();
911                                         let mut spent_on_hop_msat = value_contribution_msat;
912                                         let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
913                                         spent_on_hop_msat += next_hops_fee_msat;
914                                         if *channel_liquidity_available_msat < spent_on_hop_msat {
915                                                 // This should not happen because we do recompute fees right before,
916                                                 // trying to avoid cases when a hop is not usable due to the fee situation.
917                                                 break 'path_construction;
918                                         }
919                                         if spent_on_hop_msat == *channel_liquidity_available_msat {
920                                                 // If this path used all of this channel's available liquidity, we know
921                                                 // this path will not be selected again in the next loop iteration.
922                                                 prevented_redundant_path_selection = true;
923                                         }
924                                         *channel_liquidity_available_msat -= spent_on_hop_msat;
925                                 }
926                                 if !prevented_redundant_path_selection {
927                                         // If we weren't capped by hitting a liquidity limit on a channel in the path,
928                                         // we'll probably end up picking the same path again on the next iteration.
929                                         // Decrease the available liquidity of a hop in the middle of the path.
930                                         let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(
931                                                 &payment_path.hops[(payment_path.hops.len() - 1) / 2].route_hop.short_channel_id).unwrap();
932                                         *victim_liquidity = 0;
933                                 }
934
935                                 // Track the total amount all our collected paths allow to send so that we:
936                                 // - know when to stop looking for more paths
937                                 // - know which of the hops are useless considering how much more sats we need
938                                 //   (contributes_sufficient_value)
939                                 already_collected_value_msat += value_contribution_msat;
940
941                                 payment_paths.push(payment_path);
942                                 found_new_path = true;
943                                 break 'path_construction;
944                         }
945
946                         // Otherwise, since the current target node is not us,
947                         // keep "unrolling" the payment graph from payee to payer by
948                         // finding a way to reach the current target from the payer side.
949                         match network.get_nodes().get(&pubkey) {
950                                 None => {},
951                                 Some(node) => {
952                                         add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
953                                 },
954                         }
955                 }
956
957                 if !allow_mpp {
958                         // If we don't support MPP, no use trying to gather more value ever.
959                         break 'paths_collection;
960                 }
961
962                 // Step (3).
963                 // Stop either when the recommended value is reached or if no new path was found in this
964                 // iteration.
965                 // In the latter case, making another path finding attempt won't help,
966                 // because we deterministically terminated the search due to low liquidity.
967                 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
968                         break 'paths_collection;
969                 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
970                         // Further, if this was our first walk of the graph, and we weren't limited by an
971                         // htlc_minimum_msat, return immediately because this path should suffice. If we were
972                         // limited by an htlc_minimum_msat value, find another path with a higher value,
973                         // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
974                         // still keeping a lower total fee than this path.
975                         if !hit_minimum_limit {
976                                 break 'paths_collection;
977                         }
978                         path_value_msat = recommended_value_msat;
979                 }
980         }
981
982         // Step (4).
983         if payment_paths.len() == 0 {
984                 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
985         }
986
987         if already_collected_value_msat < final_value_msat {
988                 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
989         }
990
991         // Sort by total fees and take the best paths.
992         payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
993         if payment_paths.len() > 50 {
994                 payment_paths.truncate(50);
995         }
996
997         // Draw multiple sufficient routes by randomly combining the selected paths.
998         let mut drawn_routes = Vec::new();
999         for i in 0..payment_paths.len() {
1000                 let mut cur_route = Vec::<PaymentPath>::new();
1001                 let mut aggregate_route_value_msat = 0;
1002
1003                 // Step (5).
1004                 // TODO: real random shuffle
1005                 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1006                 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1007
1008                 // Step (6).
1009                 for payment_path in cur_payment_paths {
1010                         cur_route.push(payment_path.clone());
1011                         aggregate_route_value_msat += payment_path.get_value_msat();
1012                         if aggregate_route_value_msat > final_value_msat {
1013                                 // Last path likely overpaid. Substract it from the most expensive
1014                                 // (in terms of proportional fee) path in this route and recompute fees.
1015                                 // This might be not the most economically efficient way, but fewer paths
1016                                 // also makes routing more reliable.
1017                                 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1018
1019                                 // First, drop some expensive low-value paths entirely if possible.
1020                                 // Sort by value so that we drop many really-low values first, since
1021                                 // fewer paths is better: the payment is less likely to fail.
1022                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1023                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1024                                 cur_route.sort_by_key(|path| path.get_value_msat());
1025                                 // We should make sure that at least 1 path left.
1026                                 let mut paths_left = cur_route.len();
1027                                 cur_route.retain(|path| {
1028                                         if paths_left == 1 {
1029                                                 return true
1030                                         }
1031                                         let mut keep = true;
1032                                         let path_value_msat = path.get_value_msat();
1033                                         if path_value_msat <= overpaid_value_msat {
1034                                                 keep = false;
1035                                                 overpaid_value_msat -= path_value_msat;
1036                                                 paths_left -= 1;
1037                                         }
1038                                         keep
1039                                 });
1040
1041                                 if overpaid_value_msat == 0 {
1042                                         break;
1043                                 }
1044
1045                                 assert!(cur_route.len() > 0);
1046
1047                                 // Step (7).
1048                                 // Now, substract the overpaid value from the most-expensive path.
1049                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1050                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1051                                 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
1052                                 let expensive_payment_path = cur_route.first_mut().unwrap();
1053                                 // We already dropped all the small channels above, meaning all the
1054                                 // remaining channels are larger than remaining overpaid_value_msat.
1055                                 // Thus, this can't be negative.
1056                                 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1057                                 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1058                                 break;
1059                         }
1060                 }
1061                 drawn_routes.push(cur_route);
1062         }
1063
1064         // Step (8).
1065         // Select the best route by lowest total fee.
1066         drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1067         let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1068         for payment_path in drawn_routes.first().unwrap() {
1069                 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
1070         }
1071
1072         if let Some(features) = &payee_features {
1073                 for path in selected_paths.iter_mut() {
1074                         path.last_mut().unwrap().node_features = features.to_context();
1075                 }
1076         }
1077
1078         let route = Route { paths: selected_paths };
1079         log_trace!(logger, "Got route: {}", log_route!(route));
1080         Ok(route)
1081 }
1082
1083 #[cfg(test)]
1084 mod tests {
1085         use routing::router::{get_route, RouteHint, RoutingFees};
1086         use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1087         use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1088         use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1089            NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1090         use ln::channelmanager;
1091         use util::test_utils;
1092         use util::ser::Writeable;
1093
1094         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1095         use bitcoin::hashes::Hash;
1096         use bitcoin::network::constants::Network;
1097         use bitcoin::blockdata::constants::genesis_block;
1098         use bitcoin::blockdata::script::Builder;
1099         use bitcoin::blockdata::opcodes;
1100         use bitcoin::blockdata::transaction::TxOut;
1101
1102         use hex;
1103
1104         use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1105         use bitcoin::secp256k1::{Secp256k1, All};
1106
1107         use std::sync::Arc;
1108
1109         // Using the same keys for LN and BTC ids
1110         fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1111            node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1112                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1113                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1114
1115                 let unsigned_announcement = UnsignedChannelAnnouncement {
1116                         features,
1117                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1118                         short_channel_id,
1119                         node_id_1,
1120                         node_id_2,
1121                         bitcoin_key_1: node_id_1,
1122                         bitcoin_key_2: node_id_2,
1123                         excess_data: Vec::new(),
1124                 };
1125
1126                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1127                 let valid_announcement = ChannelAnnouncement {
1128                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1129                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1130                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1131                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1132                         contents: unsigned_announcement.clone(),
1133                 };
1134                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1135                         Ok(res) => assert!(res),
1136                         _ => panic!()
1137                 };
1138         }
1139
1140         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) {
1141                 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1142                 let valid_channel_update = ChannelUpdate {
1143                         signature: secp_ctx.sign(&msghash, node_privkey),
1144                         contents: update.clone()
1145                 };
1146
1147                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1148                         Ok(res) => assert!(res),
1149                         Err(_) => panic!()
1150                 };
1151         }
1152
1153         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,
1154            features: NodeFeatures, timestamp: u32) {
1155                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1156                 let unsigned_announcement = UnsignedNodeAnnouncement {
1157                         features,
1158                         timestamp,
1159                         node_id,
1160                         rgb: [0; 3],
1161                         alias: [0; 32],
1162                         addresses: Vec::new(),
1163                         excess_address_data: Vec::new(),
1164                         excess_data: Vec::new(),
1165                 };
1166                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1167                 let valid_announcement = NodeAnnouncement {
1168                         signature: secp_ctx.sign(&msghash, node_privkey),
1169                         contents: unsigned_announcement.clone()
1170                 };
1171
1172                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1173                         Ok(_) => (),
1174                         Err(_) => panic!()
1175                 };
1176         }
1177
1178         fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1179                 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1180                         SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1181                 }).collect();
1182
1183                 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1184
1185                 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1186                 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1187
1188                 (our_privkey, our_id, privkeys, pubkeys)
1189         }
1190
1191         fn id_to_feature_flags(id: u8) -> Vec<u8> {
1192                 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1193                 // test for it later.
1194                 let idx = (id - 1) * 2 + 1;
1195                 if idx > 8*3 {
1196                         vec![1 << (idx - 8*3), 0, 0, 0]
1197                 } else if idx > 8*2 {
1198                         vec![1 << (idx - 8*2), 0, 0]
1199                 } else if idx > 8*1 {
1200                         vec![1 << (idx - 8*1), 0]
1201                 } else {
1202                         vec![1 << idx]
1203                 }
1204         }
1205
1206         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>) {
1207                 let secp_ctx = Secp256k1::new();
1208                 let logger = Arc::new(test_utils::TestLogger::new());
1209                 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1210                 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1211                 // Build network from our_id to node7:
1212                 //
1213                 //        -1(1)2-  node0  -1(3)2-
1214                 //       /                       \
1215                 // our_id -1(12)2- node7 -1(13)2--- node2
1216                 //       \                       /
1217                 //        -1(2)2-  node1  -1(4)2-
1218                 //
1219                 //
1220                 // chan1  1-to-2: disabled
1221                 // chan1  2-to-1: enabled, 0 fee
1222                 //
1223                 // chan2  1-to-2: enabled, ignored fee
1224                 // chan2  2-to-1: enabled, 0 fee
1225                 //
1226                 // chan3  1-to-2: enabled, 0 fee
1227                 // chan3  2-to-1: enabled, 100 msat fee
1228                 //
1229                 // chan4  1-to-2: enabled, 100% fee
1230                 // chan4  2-to-1: enabled, 0 fee
1231                 //
1232                 // chan12 1-to-2: enabled, ignored fee
1233                 // chan12 2-to-1: enabled, 0 fee
1234                 //
1235                 // chan13 1-to-2: enabled, 200% fee
1236                 // chan13 2-to-1: enabled, 0 fee
1237                 //
1238                 //
1239                 //       -1(5)2- node3 -1(8)2--
1240                 //       |         2          |
1241                 //       |       (11)         |
1242                 //      /          1           \
1243                 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1244                 //      \                      /
1245                 //       -1(7)2- node5 -1(10)2-
1246                 //
1247                 // chan5  1-to-2: enabled, 100 msat fee
1248                 // chan5  2-to-1: enabled, 0 fee
1249                 //
1250                 // chan6  1-to-2: enabled, 0 fee
1251                 // chan6  2-to-1: enabled, 0 fee
1252                 //
1253                 // chan7  1-to-2: enabled, 100% fee
1254                 // chan7  2-to-1: enabled, 0 fee
1255                 //
1256                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
1257                 // chan8  2-to-1: enabled, 0 fee
1258                 //
1259                 // chan9  1-to-2: enabled, 1001 msat fee
1260                 // chan9  2-to-1: enabled, 0 fee
1261                 //
1262                 // chan10 1-to-2: enabled, 0 fee
1263                 // chan10 2-to-1: enabled, 0 fee
1264                 //
1265                 // chan11 1-to-2: enabled, 0 fee
1266                 // chan11 2-to-1: enabled, 0 fee
1267
1268                 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1269
1270                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1271                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1272                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1273                         short_channel_id: 1,
1274                         timestamp: 1,
1275                         flags: 1,
1276                         cltv_expiry_delta: 0,
1277                         htlc_minimum_msat: 0,
1278                         htlc_maximum_msat: OptionalField::Absent,
1279                         fee_base_msat: 0,
1280                         fee_proportional_millionths: 0,
1281                         excess_data: Vec::new()
1282                 });
1283
1284                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1285
1286                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1287                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1288                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1289                         short_channel_id: 2,
1290                         timestamp: 1,
1291                         flags: 0,
1292                         cltv_expiry_delta: u16::max_value(),
1293                         htlc_minimum_msat: 0,
1294                         htlc_maximum_msat: OptionalField::Absent,
1295                         fee_base_msat: u32::max_value(),
1296                         fee_proportional_millionths: u32::max_value(),
1297                         excess_data: Vec::new()
1298                 });
1299                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1300                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1301                         short_channel_id: 2,
1302                         timestamp: 1,
1303                         flags: 1,
1304                         cltv_expiry_delta: 0,
1305                         htlc_minimum_msat: 0,
1306                         htlc_maximum_msat: OptionalField::Absent,
1307                         fee_base_msat: 0,
1308                         fee_proportional_millionths: 0,
1309                         excess_data: Vec::new()
1310                 });
1311
1312                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1313
1314                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1315                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1316                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1317                         short_channel_id: 12,
1318                         timestamp: 1,
1319                         flags: 0,
1320                         cltv_expiry_delta: u16::max_value(),
1321                         htlc_minimum_msat: 0,
1322                         htlc_maximum_msat: OptionalField::Absent,
1323                         fee_base_msat: u32::max_value(),
1324                         fee_proportional_millionths: u32::max_value(),
1325                         excess_data: Vec::new()
1326                 });
1327                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1328                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1329                         short_channel_id: 12,
1330                         timestamp: 1,
1331                         flags: 1,
1332                         cltv_expiry_delta: 0,
1333                         htlc_minimum_msat: 0,
1334                         htlc_maximum_msat: OptionalField::Absent,
1335                         fee_base_msat: 0,
1336                         fee_proportional_millionths: 0,
1337                         excess_data: Vec::new()
1338                 });
1339
1340                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1341
1342                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1343                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1344                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1345                         short_channel_id: 3,
1346                         timestamp: 1,
1347                         flags: 0,
1348                         cltv_expiry_delta: (3 << 8) | 1,
1349                         htlc_minimum_msat: 0,
1350                         htlc_maximum_msat: OptionalField::Absent,
1351                         fee_base_msat: 0,
1352                         fee_proportional_millionths: 0,
1353                         excess_data: Vec::new()
1354                 });
1355                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1356                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1357                         short_channel_id: 3,
1358                         timestamp: 1,
1359                         flags: 1,
1360                         cltv_expiry_delta: (3 << 8) | 2,
1361                         htlc_minimum_msat: 0,
1362                         htlc_maximum_msat: OptionalField::Absent,
1363                         fee_base_msat: 100,
1364                         fee_proportional_millionths: 0,
1365                         excess_data: Vec::new()
1366                 });
1367
1368                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1369                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1370                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1371                         short_channel_id: 4,
1372                         timestamp: 1,
1373                         flags: 0,
1374                         cltv_expiry_delta: (4 << 8) | 1,
1375                         htlc_minimum_msat: 0,
1376                         htlc_maximum_msat: OptionalField::Absent,
1377                         fee_base_msat: 0,
1378                         fee_proportional_millionths: 1000000,
1379                         excess_data: Vec::new()
1380                 });
1381                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1382                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1383                         short_channel_id: 4,
1384                         timestamp: 1,
1385                         flags: 1,
1386                         cltv_expiry_delta: (4 << 8) | 2,
1387                         htlc_minimum_msat: 0,
1388                         htlc_maximum_msat: OptionalField::Absent,
1389                         fee_base_msat: 0,
1390                         fee_proportional_millionths: 0,
1391                         excess_data: Vec::new()
1392                 });
1393
1394                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1395                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1396                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1397                         short_channel_id: 13,
1398                         timestamp: 1,
1399                         flags: 0,
1400                         cltv_expiry_delta: (13 << 8) | 1,
1401                         htlc_minimum_msat: 0,
1402                         htlc_maximum_msat: OptionalField::Absent,
1403                         fee_base_msat: 0,
1404                         fee_proportional_millionths: 2000000,
1405                         excess_data: Vec::new()
1406                 });
1407                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1408                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1409                         short_channel_id: 13,
1410                         timestamp: 1,
1411                         flags: 1,
1412                         cltv_expiry_delta: (13 << 8) | 2,
1413                         htlc_minimum_msat: 0,
1414                         htlc_maximum_msat: OptionalField::Absent,
1415                         fee_base_msat: 0,
1416                         fee_proportional_millionths: 0,
1417                         excess_data: Vec::new()
1418                 });
1419
1420                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1421
1422                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1423                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1424                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1425                         short_channel_id: 6,
1426                         timestamp: 1,
1427                         flags: 0,
1428                         cltv_expiry_delta: (6 << 8) | 1,
1429                         htlc_minimum_msat: 0,
1430                         htlc_maximum_msat: OptionalField::Absent,
1431                         fee_base_msat: 0,
1432                         fee_proportional_millionths: 0,
1433                         excess_data: Vec::new()
1434                 });
1435                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1436                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1437                         short_channel_id: 6,
1438                         timestamp: 1,
1439                         flags: 1,
1440                         cltv_expiry_delta: (6 << 8) | 2,
1441                         htlc_minimum_msat: 0,
1442                         htlc_maximum_msat: OptionalField::Absent,
1443                         fee_base_msat: 0,
1444                         fee_proportional_millionths: 0,
1445                         excess_data: Vec::new(),
1446                 });
1447
1448                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1449                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1450                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1451                         short_channel_id: 11,
1452                         timestamp: 1,
1453                         flags: 0,
1454                         cltv_expiry_delta: (11 << 8) | 1,
1455                         htlc_minimum_msat: 0,
1456                         htlc_maximum_msat: OptionalField::Absent,
1457                         fee_base_msat: 0,
1458                         fee_proportional_millionths: 0,
1459                         excess_data: Vec::new()
1460                 });
1461                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1462                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1463                         short_channel_id: 11,
1464                         timestamp: 1,
1465                         flags: 1,
1466                         cltv_expiry_delta: (11 << 8) | 2,
1467                         htlc_minimum_msat: 0,
1468                         htlc_maximum_msat: OptionalField::Absent,
1469                         fee_base_msat: 0,
1470                         fee_proportional_millionths: 0,
1471                         excess_data: Vec::new()
1472                 });
1473
1474                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1475
1476                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1477
1478                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1479                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1480                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1481                         short_channel_id: 7,
1482                         timestamp: 1,
1483                         flags: 0,
1484                         cltv_expiry_delta: (7 << 8) | 1,
1485                         htlc_minimum_msat: 0,
1486                         htlc_maximum_msat: OptionalField::Absent,
1487                         fee_base_msat: 0,
1488                         fee_proportional_millionths: 1000000,
1489                         excess_data: Vec::new()
1490                 });
1491                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1492                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1493                         short_channel_id: 7,
1494                         timestamp: 1,
1495                         flags: 1,
1496                         cltv_expiry_delta: (7 << 8) | 2,
1497                         htlc_minimum_msat: 0,
1498                         htlc_maximum_msat: OptionalField::Absent,
1499                         fee_base_msat: 0,
1500                         fee_proportional_millionths: 0,
1501                         excess_data: Vec::new()
1502                 });
1503
1504                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1505
1506                 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1507         }
1508
1509         #[test]
1510         fn simple_route_test() {
1511                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1512                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1513
1514                 // Simple route to 2 via 1
1515
1516                 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)) {
1517                         assert_eq!(err, "Cannot send a payment of 0 msat");
1518                 } else { panic!(); }
1519
1520                 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();
1521                 assert_eq!(route.paths[0].len(), 2);
1522
1523                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1524                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1525                 assert_eq!(route.paths[0][0].fee_msat, 100);
1526                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1527                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1528                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1529
1530                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1531                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1532                 assert_eq!(route.paths[0][1].fee_msat, 100);
1533                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1534                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1535                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1536         }
1537
1538         #[test]
1539         fn invalid_first_hop_test() {
1540                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1541                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1542
1543                 // Simple route to 2 via 1
1544
1545                 let our_chans = vec![channelmanager::ChannelDetails {
1546                         channel_id: [0; 32],
1547                         short_channel_id: Some(2),
1548                         remote_network_id: our_id,
1549                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1550                         channel_value_satoshis: 100000,
1551                         user_id: 0,
1552                         outbound_capacity_msat: 100000,
1553                         inbound_capacity_msat: 100000,
1554                         is_live: true,
1555                         counterparty_forwarding_info: None,
1556                 }];
1557
1558                 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)) {
1559                         assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1560                 } else { panic!(); }
1561
1562                 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();
1563                 assert_eq!(route.paths[0].len(), 2);
1564         }
1565
1566         #[test]
1567         fn htlc_minimum_test() {
1568                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1569                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1570
1571                 // Simple route to 2 via 1
1572
1573                 // Disable other paths
1574                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1575                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1576                         short_channel_id: 12,
1577                         timestamp: 2,
1578                         flags: 2, // to disable
1579                         cltv_expiry_delta: 0,
1580                         htlc_minimum_msat: 0,
1581                         htlc_maximum_msat: OptionalField::Absent,
1582                         fee_base_msat: 0,
1583                         fee_proportional_millionths: 0,
1584                         excess_data: Vec::new()
1585                 });
1586                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1587                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1588                         short_channel_id: 3,
1589                         timestamp: 2,
1590                         flags: 2, // to disable
1591                         cltv_expiry_delta: 0,
1592                         htlc_minimum_msat: 0,
1593                         htlc_maximum_msat: OptionalField::Absent,
1594                         fee_base_msat: 0,
1595                         fee_proportional_millionths: 0,
1596                         excess_data: Vec::new()
1597                 });
1598                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1599                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1600                         short_channel_id: 13,
1601                         timestamp: 2,
1602                         flags: 2, // to disable
1603                         cltv_expiry_delta: 0,
1604                         htlc_minimum_msat: 0,
1605                         htlc_maximum_msat: OptionalField::Absent,
1606                         fee_base_msat: 0,
1607                         fee_proportional_millionths: 0,
1608                         excess_data: Vec::new()
1609                 });
1610                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1611                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1612                         short_channel_id: 6,
1613                         timestamp: 2,
1614                         flags: 2, // to disable
1615                         cltv_expiry_delta: 0,
1616                         htlc_minimum_msat: 0,
1617                         htlc_maximum_msat: OptionalField::Absent,
1618                         fee_base_msat: 0,
1619                         fee_proportional_millionths: 0,
1620                         excess_data: Vec::new()
1621                 });
1622                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1623                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1624                         short_channel_id: 7,
1625                         timestamp: 2,
1626                         flags: 2, // to disable
1627                         cltv_expiry_delta: 0,
1628                         htlc_minimum_msat: 0,
1629                         htlc_maximum_msat: OptionalField::Absent,
1630                         fee_base_msat: 0,
1631                         fee_proportional_millionths: 0,
1632                         excess_data: Vec::new()
1633                 });
1634
1635                 // Check against amount_to_transfer_over_msat.
1636                 // Set minimal HTLC of 200_000_000 msat.
1637                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1638                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1639                         short_channel_id: 2,
1640                         timestamp: 3,
1641                         flags: 0,
1642                         cltv_expiry_delta: 0,
1643                         htlc_minimum_msat: 200_000_000,
1644                         htlc_maximum_msat: OptionalField::Absent,
1645                         fee_base_msat: 0,
1646                         fee_proportional_millionths: 0,
1647                         excess_data: Vec::new()
1648                 });
1649
1650                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1651                 // be used.
1652                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1653                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1654                         short_channel_id: 4,
1655                         timestamp: 3,
1656                         flags: 0,
1657                         cltv_expiry_delta: 0,
1658                         htlc_minimum_msat: 0,
1659                         htlc_maximum_msat: OptionalField::Present(199_999_999),
1660                         fee_base_msat: 0,
1661                         fee_proportional_millionths: 0,
1662                         excess_data: Vec::new()
1663                 });
1664
1665                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1666                 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)) {
1667                         assert_eq!(err, "Failed to find a path to the given destination");
1668                 } else { panic!(); }
1669
1670                 // Lift the restriction on the first hop.
1671                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1672                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1673                         short_channel_id: 2,
1674                         timestamp: 4,
1675                         flags: 0,
1676                         cltv_expiry_delta: 0,
1677                         htlc_minimum_msat: 0,
1678                         htlc_maximum_msat: OptionalField::Absent,
1679                         fee_base_msat: 0,
1680                         fee_proportional_millionths: 0,
1681                         excess_data: Vec::new()
1682                 });
1683
1684                 // A payment above the minimum should pass
1685                 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();
1686                 assert_eq!(route.paths[0].len(), 2);
1687         }
1688
1689         #[test]
1690         fn htlc_minimum_overpay_test() {
1691                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1692                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1693
1694                 // A route to node#2 via two paths.
1695                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1696                 // Thus, they can't send 60 without overpaying.
1697                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1698                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1699                         short_channel_id: 2,
1700                         timestamp: 2,
1701                         flags: 0,
1702                         cltv_expiry_delta: 0,
1703                         htlc_minimum_msat: 35_000,
1704                         htlc_maximum_msat: OptionalField::Present(40_000),
1705                         fee_base_msat: 0,
1706                         fee_proportional_millionths: 0,
1707                         excess_data: Vec::new()
1708                 });
1709                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1710                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1711                         short_channel_id: 12,
1712                         timestamp: 3,
1713                         flags: 0,
1714                         cltv_expiry_delta: 0,
1715                         htlc_minimum_msat: 35_000,
1716                         htlc_maximum_msat: OptionalField::Present(40_000),
1717                         fee_base_msat: 0,
1718                         fee_proportional_millionths: 0,
1719                         excess_data: Vec::new()
1720                 });
1721
1722                 // Make 0 fee.
1723                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1724                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1725                         short_channel_id: 13,
1726                         timestamp: 2,
1727                         flags: 0,
1728                         cltv_expiry_delta: 0,
1729                         htlc_minimum_msat: 0,
1730                         htlc_maximum_msat: OptionalField::Absent,
1731                         fee_base_msat: 0,
1732                         fee_proportional_millionths: 0,
1733                         excess_data: Vec::new()
1734                 });
1735                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1736                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1737                         short_channel_id: 4,
1738                         timestamp: 2,
1739                         flags: 0,
1740                         cltv_expiry_delta: 0,
1741                         htlc_minimum_msat: 0,
1742                         htlc_maximum_msat: OptionalField::Absent,
1743                         fee_base_msat: 0,
1744                         fee_proportional_millionths: 0,
1745                         excess_data: Vec::new()
1746                 });
1747
1748                 // Disable other paths
1749                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1750                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1751                         short_channel_id: 1,
1752                         timestamp: 3,
1753                         flags: 2, // to disable
1754                         cltv_expiry_delta: 0,
1755                         htlc_minimum_msat: 0,
1756                         htlc_maximum_msat: OptionalField::Absent,
1757                         fee_base_msat: 0,
1758                         fee_proportional_millionths: 0,
1759                         excess_data: Vec::new()
1760                 });
1761
1762                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1763                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1764                 // Overpay fees to hit htlc_minimum_msat.
1765                 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1766                 // TODO: this could be better balanced to overpay 10k and not 15k.
1767                 assert_eq!(overpaid_fees, 15_000);
1768
1769                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1770                 // while taking even more fee to match htlc_minimum_msat.
1771                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1772                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1773                         short_channel_id: 12,
1774                         timestamp: 4,
1775                         flags: 0,
1776                         cltv_expiry_delta: 0,
1777                         htlc_minimum_msat: 65_000,
1778                         htlc_maximum_msat: OptionalField::Present(80_000),
1779                         fee_base_msat: 0,
1780                         fee_proportional_millionths: 0,
1781                         excess_data: Vec::new()
1782                 });
1783                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1784                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1785                         short_channel_id: 2,
1786                         timestamp: 3,
1787                         flags: 0,
1788                         cltv_expiry_delta: 0,
1789                         htlc_minimum_msat: 0,
1790                         htlc_maximum_msat: OptionalField::Absent,
1791                         fee_base_msat: 0,
1792                         fee_proportional_millionths: 0,
1793                         excess_data: Vec::new()
1794                 });
1795                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1796                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1797                         short_channel_id: 4,
1798                         timestamp: 4,
1799                         flags: 0,
1800                         cltv_expiry_delta: 0,
1801                         htlc_minimum_msat: 0,
1802                         htlc_maximum_msat: OptionalField::Absent,
1803                         fee_base_msat: 0,
1804                         fee_proportional_millionths: 100_000,
1805                         excess_data: Vec::new()
1806                 });
1807
1808                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1809                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1810                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1811                 assert_eq!(route.paths.len(), 1);
1812                 assert_eq!(route.paths[0][0].short_channel_id, 12);
1813                 let fees = route.paths[0][0].fee_msat;
1814                 assert_eq!(fees, 5_000);
1815
1816                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1817                         Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1818                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1819                 // the other channel.
1820                 assert_eq!(route.paths.len(), 1);
1821                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1822                 let fees = route.paths[0][0].fee_msat;
1823                 assert_eq!(fees, 5_000);
1824         }
1825
1826         #[test]
1827         fn disable_channels_test() {
1828                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1829                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1830
1831                 // // Disable channels 4 and 12 by flags=2
1832                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1833                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1834                         short_channel_id: 4,
1835                         timestamp: 2,
1836                         flags: 2, // to disable
1837                         cltv_expiry_delta: 0,
1838                         htlc_minimum_msat: 0,
1839                         htlc_maximum_msat: OptionalField::Absent,
1840                         fee_base_msat: 0,
1841                         fee_proportional_millionths: 0,
1842                         excess_data: Vec::new()
1843                 });
1844                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1845                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1846                         short_channel_id: 12,
1847                         timestamp: 2,
1848                         flags: 2, // to disable
1849                         cltv_expiry_delta: 0,
1850                         htlc_minimum_msat: 0,
1851                         htlc_maximum_msat: OptionalField::Absent,
1852                         fee_base_msat: 0,
1853                         fee_proportional_millionths: 0,
1854                         excess_data: Vec::new()
1855                 });
1856
1857                 // If all the channels require some features we don't understand, route should fail
1858                 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)) {
1859                         assert_eq!(err, "Failed to find a path to the given destination");
1860                 } else { panic!(); }
1861
1862                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1863                 let our_chans = vec![channelmanager::ChannelDetails {
1864                         channel_id: [0; 32],
1865                         short_channel_id: Some(42),
1866                         remote_network_id: nodes[7].clone(),
1867                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1868                         channel_value_satoshis: 0,
1869                         user_id: 0,
1870                         outbound_capacity_msat: 250_000_000,
1871                         inbound_capacity_msat: 0,
1872                         is_live: true,
1873                         counterparty_forwarding_info: None,
1874                 }];
1875                 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();
1876                 assert_eq!(route.paths[0].len(), 2);
1877
1878                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1879                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1880                 assert_eq!(route.paths[0][0].fee_msat, 200);
1881                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1882                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1883                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1884
1885                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1886                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1887                 assert_eq!(route.paths[0][1].fee_msat, 100);
1888                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1889                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1890                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1891         }
1892
1893         #[test]
1894         fn disable_node_test() {
1895                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1896                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1897
1898                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1899                 let mut unknown_features = NodeFeatures::known();
1900                 unknown_features.set_required_unknown_bits();
1901                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1902                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1903                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1904
1905                 // If all nodes require some features we don't understand, route should fail
1906                 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)) {
1907                         assert_eq!(err, "Failed to find a path to the given destination");
1908                 } else { panic!(); }
1909
1910                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1911                 let our_chans = vec![channelmanager::ChannelDetails {
1912                         channel_id: [0; 32],
1913                         short_channel_id: Some(42),
1914                         remote_network_id: nodes[7].clone(),
1915                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1916                         channel_value_satoshis: 0,
1917                         user_id: 0,
1918                         outbound_capacity_msat: 250_000_000,
1919                         inbound_capacity_msat: 0,
1920                         is_live: true,
1921                         counterparty_forwarding_info: None,
1922                 }];
1923                 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();
1924                 assert_eq!(route.paths[0].len(), 2);
1925
1926                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1927                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1928                 assert_eq!(route.paths[0][0].fee_msat, 200);
1929                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1930                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1931                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1932
1933                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1934                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1935                 assert_eq!(route.paths[0][1].fee_msat, 100);
1936                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1937                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1938                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1939
1940                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1941                 // naively) assume that the user checked the feature bits on the invoice, which override
1942                 // the node_announcement.
1943         }
1944
1945         #[test]
1946         fn our_chans_test() {
1947                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1948                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1949
1950                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1951                 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();
1952                 assert_eq!(route.paths[0].len(), 3);
1953
1954                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1955                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1956                 assert_eq!(route.paths[0][0].fee_msat, 200);
1957                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1958                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1959                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1960
1961                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1962                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1963                 assert_eq!(route.paths[0][1].fee_msat, 100);
1964                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1965                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1966                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1967
1968                 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1969                 assert_eq!(route.paths[0][2].short_channel_id, 3);
1970                 assert_eq!(route.paths[0][2].fee_msat, 100);
1971                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1972                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1973                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1974
1975                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1976                 let our_chans = vec![channelmanager::ChannelDetails {
1977                         channel_id: [0; 32],
1978                         short_channel_id: Some(42),
1979                         remote_network_id: nodes[7].clone(),
1980                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1981                         channel_value_satoshis: 0,
1982                         user_id: 0,
1983                         outbound_capacity_msat: 250_000_000,
1984                         inbound_capacity_msat: 0,
1985                         is_live: true,
1986                         counterparty_forwarding_info: None,
1987                 }];
1988                 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();
1989                 assert_eq!(route.paths[0].len(), 2);
1990
1991                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1992                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1993                 assert_eq!(route.paths[0][0].fee_msat, 200);
1994                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1995                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1996                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1997
1998                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1999                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2000                 assert_eq!(route.paths[0][1].fee_msat, 100);
2001                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2002                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2003                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2004         }
2005
2006         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2007                 let zero_fees = RoutingFees {
2008                         base_msat: 0,
2009                         proportional_millionths: 0,
2010                 };
2011                 vec!(RouteHint {
2012                         src_node_id: nodes[3].clone(),
2013                         short_channel_id: 8,
2014                         fees: zero_fees,
2015                         cltv_expiry_delta: (8 << 8) | 1,
2016                         htlc_minimum_msat: None,
2017                         htlc_maximum_msat: None,
2018                 }, RouteHint {
2019                         src_node_id: nodes[4].clone(),
2020                         short_channel_id: 9,
2021                         fees: RoutingFees {
2022                                 base_msat: 1001,
2023                                 proportional_millionths: 0,
2024                         },
2025                         cltv_expiry_delta: (9 << 8) | 1,
2026                         htlc_minimum_msat: None,
2027                         htlc_maximum_msat: None,
2028                 }, RouteHint {
2029                         src_node_id: nodes[5].clone(),
2030                         short_channel_id: 10,
2031                         fees: zero_fees,
2032                         cltv_expiry_delta: (10 << 8) | 1,
2033                         htlc_minimum_msat: None,
2034                         htlc_maximum_msat: None,
2035                 })
2036         }
2037
2038         #[test]
2039         fn last_hops_test() {
2040                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2041                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2042
2043                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2044
2045                 // First check that lst hop can't have its source as the payee.
2046                 let invalid_last_hop = RouteHint {
2047                         src_node_id: nodes[6],
2048                         short_channel_id: 8,
2049                         fees: RoutingFees {
2050                                 base_msat: 1000,
2051                                 proportional_millionths: 0,
2052                         },
2053                         cltv_expiry_delta: (8 << 8) | 1,
2054                         htlc_minimum_msat: None,
2055                         htlc_maximum_msat: None,
2056                 };
2057
2058                 let mut invalid_last_hops = last_hops(&nodes);
2059                 invalid_last_hops.push(invalid_last_hop);
2060                 {
2061                         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)) {
2062                                 assert_eq!(err, "Last hop cannot have a payee as a source.");
2063                         } else { panic!(); }
2064                 }
2065
2066                 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();
2067                 assert_eq!(route.paths[0].len(), 5);
2068
2069                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2070                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2071                 assert_eq!(route.paths[0][0].fee_msat, 100);
2072                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2073                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2074                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2075
2076                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2077                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2078                 assert_eq!(route.paths[0][1].fee_msat, 0);
2079                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2080                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2081                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2082
2083                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2084                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2085                 assert_eq!(route.paths[0][2].fee_msat, 0);
2086                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2087                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2088                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2089
2090                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2091                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2092                 assert_eq!(route.paths[0][3].fee_msat, 0);
2093                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2094                 // If we have a peer in the node map, we'll use their features here since we don't have
2095                 // a way of figuring out their features from the invoice:
2096                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2097                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2098
2099                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2100                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2101                 assert_eq!(route.paths[0][4].fee_msat, 100);
2102                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2103                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2104                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2105         }
2106
2107         #[test]
2108         fn our_chans_last_hop_connect_test() {
2109                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2110                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2111
2112                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2113                 let our_chans = vec![channelmanager::ChannelDetails {
2114                         channel_id: [0; 32],
2115                         short_channel_id: Some(42),
2116                         remote_network_id: nodes[3].clone(),
2117                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2118                         channel_value_satoshis: 0,
2119                         user_id: 0,
2120                         outbound_capacity_msat: 250_000_000,
2121                         inbound_capacity_msat: 0,
2122                         is_live: true,
2123                         counterparty_forwarding_info: None,
2124                 }];
2125                 let mut last_hops = last_hops(&nodes);
2126                 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();
2127                 assert_eq!(route.paths[0].len(), 2);
2128
2129                 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2130                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2131                 assert_eq!(route.paths[0][0].fee_msat, 0);
2132                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2133                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2134                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2135
2136                 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2137                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2138                 assert_eq!(route.paths[0][1].fee_msat, 100);
2139                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2140                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2141                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2142
2143                 last_hops[0].fees.base_msat = 1000;
2144
2145                 // Revert to via 6 as the fee on 8 goes up
2146                 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();
2147                 assert_eq!(route.paths[0].len(), 4);
2148
2149                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2150                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2151                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2152                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2153                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2154                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2155
2156                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2157                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2158                 assert_eq!(route.paths[0][1].fee_msat, 100);
2159                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2160                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2161                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2162
2163                 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2164                 assert_eq!(route.paths[0][2].short_channel_id, 7);
2165                 assert_eq!(route.paths[0][2].fee_msat, 0);
2166                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2167                 // If we have a peer in the node map, we'll use their features here since we don't have
2168                 // a way of figuring out their features from the invoice:
2169                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2170                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2171
2172                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2173                 assert_eq!(route.paths[0][3].short_channel_id, 10);
2174                 assert_eq!(route.paths[0][3].fee_msat, 100);
2175                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2176                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2177                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2178
2179                 // ...but still use 8 for larger payments as 6 has a variable feerate
2180                 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();
2181                 assert_eq!(route.paths[0].len(), 5);
2182
2183                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2184                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2185                 assert_eq!(route.paths[0][0].fee_msat, 3000);
2186                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2187                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2188                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2189
2190                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2191                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2192                 assert_eq!(route.paths[0][1].fee_msat, 0);
2193                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2194                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2195                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2196
2197                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2198                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2199                 assert_eq!(route.paths[0][2].fee_msat, 0);
2200                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2201                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2202                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2203
2204                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2205                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2206                 assert_eq!(route.paths[0][3].fee_msat, 1000);
2207                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2208                 // If we have a peer in the node map, we'll use their features here since we don't have
2209                 // a way of figuring out their features from the invoice:
2210                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2211                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2212
2213                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2214                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2215                 assert_eq!(route.paths[0][4].fee_msat, 2000);
2216                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2217                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2218                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2219         }
2220
2221         #[test]
2222         fn unannounced_path_test() {
2223                 // We should be able to send a payment to a destination without any help of a routing graph
2224                 // if we have a channel with a common counterparty that appears in the first and last hop
2225                 // hints.
2226                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2227                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2228                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2229
2230                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2231                 let last_hops = vec![RouteHint {
2232                         src_node_id: middle_node_id,
2233                         short_channel_id: 8,
2234                         fees: RoutingFees {
2235                                 base_msat: 1000,
2236                                 proportional_millionths: 0,
2237                         },
2238                         cltv_expiry_delta: (8 << 8) | 1,
2239                         htlc_minimum_msat: None,
2240                         htlc_maximum_msat: None,
2241                 }];
2242                 let our_chans = vec![channelmanager::ChannelDetails {
2243                         channel_id: [0; 32],
2244                         short_channel_id: Some(42),
2245                         remote_network_id: middle_node_id,
2246                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2247                         channel_value_satoshis: 100000,
2248                         user_id: 0,
2249                         outbound_capacity_msat: 100000,
2250                         inbound_capacity_msat: 100000,
2251                         is_live: true,
2252                         counterparty_forwarding_info: None,
2253                 }];
2254                 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<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
2255
2256                 assert_eq!(route.paths[0].len(), 2);
2257
2258                 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2259                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2260                 assert_eq!(route.paths[0][0].fee_msat, 1000);
2261                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2262                 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2263                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2264
2265                 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2266                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2267                 assert_eq!(route.paths[0][1].fee_msat, 100);
2268                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2269                 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2270                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2271         }
2272
2273         #[test]
2274         fn available_amount_while_routing_test() {
2275                 // Tests whether we choose the correct available channel amount while routing.
2276
2277                 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2278                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2279
2280                 // We will use a simple single-path route from
2281                 // our node to node2 via node0: channels {1, 3}.
2282
2283                 // First disable all other paths.
2284                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2285                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2286                         short_channel_id: 2,
2287                         timestamp: 2,
2288                         flags: 2,
2289                         cltv_expiry_delta: 0,
2290                         htlc_minimum_msat: 0,
2291                         htlc_maximum_msat: OptionalField::Present(100_000),
2292                         fee_base_msat: 0,
2293                         fee_proportional_millionths: 0,
2294                         excess_data: Vec::new()
2295                 });
2296                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2297                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2298                         short_channel_id: 12,
2299                         timestamp: 2,
2300                         flags: 2,
2301                         cltv_expiry_delta: 0,
2302                         htlc_minimum_msat: 0,
2303                         htlc_maximum_msat: OptionalField::Present(100_000),
2304                         fee_base_msat: 0,
2305                         fee_proportional_millionths: 0,
2306                         excess_data: Vec::new()
2307                 });
2308
2309                 // Make the first channel (#1) very permissive,
2310                 // and we will be testing all limits on the second channel.
2311                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2312                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2313                         short_channel_id: 1,
2314                         timestamp: 2,
2315                         flags: 0,
2316                         cltv_expiry_delta: 0,
2317                         htlc_minimum_msat: 0,
2318                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2319                         fee_base_msat: 0,
2320                         fee_proportional_millionths: 0,
2321                         excess_data: Vec::new()
2322                 });
2323
2324                 // First, let's see if routing works if we have absolutely no idea about the available amount.
2325                 // In this case, it should be set to 250_000 sats.
2326                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2327                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2328                         short_channel_id: 3,
2329                         timestamp: 2,
2330                         flags: 0,
2331                         cltv_expiry_delta: 0,
2332                         htlc_minimum_msat: 0,
2333                         htlc_maximum_msat: OptionalField::Absent,
2334                         fee_base_msat: 0,
2335                         fee_proportional_millionths: 0,
2336                         excess_data: Vec::new()
2337                 });
2338
2339                 {
2340                         // Attempt to route more than available results in a failure.
2341                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2342                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2343                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2344                         } else { panic!(); }
2345                 }
2346
2347                 {
2348                         // Now, attempt to route an exact amount we have should be fine.
2349                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2350                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2351                         assert_eq!(route.paths.len(), 1);
2352                         let path = route.paths.last().unwrap();
2353                         assert_eq!(path.len(), 2);
2354                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2355                         assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2356                 }
2357
2358                 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2359                 // Disable channel #1 and use another first hop.
2360                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2361                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2362                         short_channel_id: 1,
2363                         timestamp: 3,
2364                         flags: 2,
2365                         cltv_expiry_delta: 0,
2366                         htlc_minimum_msat: 0,
2367                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2368                         fee_base_msat: 0,
2369                         fee_proportional_millionths: 0,
2370                         excess_data: Vec::new()
2371                 });
2372
2373                 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2374                 let our_chans = vec![channelmanager::ChannelDetails {
2375                         channel_id: [0; 32],
2376                         short_channel_id: Some(42),
2377                         remote_network_id: nodes[0].clone(),
2378                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2379                         channel_value_satoshis: 0,
2380                         user_id: 0,
2381                         outbound_capacity_msat: 200_000_000,
2382                         inbound_capacity_msat: 0,
2383                         is_live: true,
2384                         counterparty_forwarding_info: None,
2385                 }];
2386
2387                 {
2388                         // Attempt to route more than available results in a failure.
2389                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2390                                         Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2391                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2392                         } else { panic!(); }
2393                 }
2394
2395                 {
2396                         // Now, attempt to route an exact amount we have should be fine.
2397                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2398                                 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2399                         assert_eq!(route.paths.len(), 1);
2400                         let path = route.paths.last().unwrap();
2401                         assert_eq!(path.len(), 2);
2402                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2403                         assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2404                 }
2405
2406                 // Enable channel #1 back.
2407                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2408                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2409                         short_channel_id: 1,
2410                         timestamp: 4,
2411                         flags: 0,
2412                         cltv_expiry_delta: 0,
2413                         htlc_minimum_msat: 0,
2414                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2415                         fee_base_msat: 0,
2416                         fee_proportional_millionths: 0,
2417                         excess_data: Vec::new()
2418                 });
2419
2420
2421                 // Now let's see if routing works if we know only htlc_maximum_msat.
2422                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2423                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2424                         short_channel_id: 3,
2425                         timestamp: 3,
2426                         flags: 0,
2427                         cltv_expiry_delta: 0,
2428                         htlc_minimum_msat: 0,
2429                         htlc_maximum_msat: OptionalField::Present(15_000),
2430                         fee_base_msat: 0,
2431                         fee_proportional_millionths: 0,
2432                         excess_data: Vec::new()
2433                 });
2434
2435                 {
2436                         // Attempt to route more than available results in a failure.
2437                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2438                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2439                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2440                         } else { panic!(); }
2441                 }
2442
2443                 {
2444                         // Now, attempt to route an exact amount we have should be fine.
2445                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2446                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2447                         assert_eq!(route.paths.len(), 1);
2448                         let path = route.paths.last().unwrap();
2449                         assert_eq!(path.len(), 2);
2450                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2451                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2452                 }
2453
2454                 // Now let's see if routing works if we know only capacity from the UTXO.
2455
2456                 // We can't change UTXO capacity on the fly, so we'll disable
2457                 // the existing channel and add another one with the capacity we need.
2458                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2459                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2460                         short_channel_id: 3,
2461                         timestamp: 4,
2462                         flags: 2,
2463                         cltv_expiry_delta: 0,
2464                         htlc_minimum_msat: 0,
2465                         htlc_maximum_msat: OptionalField::Absent,
2466                         fee_base_msat: 0,
2467                         fee_proportional_millionths: 0,
2468                         excess_data: Vec::new()
2469                 });
2470
2471                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2472                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2473                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2474                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2475                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2476
2477                 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2478                 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2479
2480                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2481                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2482                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2483                         short_channel_id: 333,
2484                         timestamp: 1,
2485                         flags: 0,
2486                         cltv_expiry_delta: (3 << 8) | 1,
2487                         htlc_minimum_msat: 0,
2488                         htlc_maximum_msat: OptionalField::Absent,
2489                         fee_base_msat: 0,
2490                         fee_proportional_millionths: 0,
2491                         excess_data: Vec::new()
2492                 });
2493                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2494                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2495                         short_channel_id: 333,
2496                         timestamp: 1,
2497                         flags: 1,
2498                         cltv_expiry_delta: (3 << 8) | 2,
2499                         htlc_minimum_msat: 0,
2500                         htlc_maximum_msat: OptionalField::Absent,
2501                         fee_base_msat: 100,
2502                         fee_proportional_millionths: 0,
2503                         excess_data: Vec::new()
2504                 });
2505
2506                 {
2507                         // Attempt to route more than available results in a failure.
2508                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2509                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2510                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2511                         } else { panic!(); }
2512                 }
2513
2514                 {
2515                         // Now, attempt to route an exact amount we have should be fine.
2516                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2517                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2518                         assert_eq!(route.paths.len(), 1);
2519                         let path = route.paths.last().unwrap();
2520                         assert_eq!(path.len(), 2);
2521                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2522                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2523                 }
2524
2525                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2526                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2527                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2528                         short_channel_id: 333,
2529                         timestamp: 6,
2530                         flags: 0,
2531                         cltv_expiry_delta: 0,
2532                         htlc_minimum_msat: 0,
2533                         htlc_maximum_msat: OptionalField::Present(10_000),
2534                         fee_base_msat: 0,
2535                         fee_proportional_millionths: 0,
2536                         excess_data: Vec::new()
2537                 });
2538
2539                 {
2540                         // Attempt to route more than available results in a failure.
2541                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2542                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2543                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2544                         } else { panic!(); }
2545                 }
2546
2547                 {
2548                         // Now, attempt to route an exact amount we have should be fine.
2549                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2550                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2551                         assert_eq!(route.paths.len(), 1);
2552                         let path = route.paths.last().unwrap();
2553                         assert_eq!(path.len(), 2);
2554                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2555                         assert_eq!(path.last().unwrap().fee_msat, 10_000);
2556                 }
2557         }
2558
2559         #[test]
2560         fn available_liquidity_last_hop_test() {
2561                 // Check that available liquidity properly limits the path even when only
2562                 // one of the latter hops is limited.
2563                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2564                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2565
2566                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2567                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2568                 // Total capacity: 50 sats.
2569
2570                 // Disable other potential paths.
2571                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2572                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2573                         short_channel_id: 2,
2574                         timestamp: 2,
2575                         flags: 2,
2576                         cltv_expiry_delta: 0,
2577                         htlc_minimum_msat: 0,
2578                         htlc_maximum_msat: OptionalField::Present(100_000),
2579                         fee_base_msat: 0,
2580                         fee_proportional_millionths: 0,
2581                         excess_data: Vec::new()
2582                 });
2583                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2584                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2585                         short_channel_id: 7,
2586                         timestamp: 2,
2587                         flags: 2,
2588                         cltv_expiry_delta: 0,
2589                         htlc_minimum_msat: 0,
2590                         htlc_maximum_msat: OptionalField::Present(100_000),
2591                         fee_base_msat: 0,
2592                         fee_proportional_millionths: 0,
2593                         excess_data: Vec::new()
2594                 });
2595
2596                 // Limit capacities
2597
2598                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2599                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2600                         short_channel_id: 12,
2601                         timestamp: 2,
2602                         flags: 0,
2603                         cltv_expiry_delta: 0,
2604                         htlc_minimum_msat: 0,
2605                         htlc_maximum_msat: OptionalField::Present(100_000),
2606                         fee_base_msat: 0,
2607                         fee_proportional_millionths: 0,
2608                         excess_data: Vec::new()
2609                 });
2610                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2611                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2612                         short_channel_id: 13,
2613                         timestamp: 2,
2614                         flags: 0,
2615                         cltv_expiry_delta: 0,
2616                         htlc_minimum_msat: 0,
2617                         htlc_maximum_msat: OptionalField::Present(100_000),
2618                         fee_base_msat: 0,
2619                         fee_proportional_millionths: 0,
2620                         excess_data: Vec::new()
2621                 });
2622
2623                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2624                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2625                         short_channel_id: 6,
2626                         timestamp: 2,
2627                         flags: 0,
2628                         cltv_expiry_delta: 0,
2629                         htlc_minimum_msat: 0,
2630                         htlc_maximum_msat: OptionalField::Present(50_000),
2631                         fee_base_msat: 0,
2632                         fee_proportional_millionths: 0,
2633                         excess_data: Vec::new()
2634                 });
2635                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2636                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2637                         short_channel_id: 11,
2638                         timestamp: 2,
2639                         flags: 0,
2640                         cltv_expiry_delta: 0,
2641                         htlc_minimum_msat: 0,
2642                         htlc_maximum_msat: OptionalField::Present(100_000),
2643                         fee_base_msat: 0,
2644                         fee_proportional_millionths: 0,
2645                         excess_data: Vec::new()
2646                 });
2647                 {
2648                         // Attempt to route more than available results in a failure.
2649                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2650                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2651                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2652                         } else { panic!(); }
2653                 }
2654
2655                 {
2656                         // Now, attempt to route 49 sats (just a bit below the capacity).
2657                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2658                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2659                         assert_eq!(route.paths.len(), 1);
2660                         let mut total_amount_paid_msat = 0;
2661                         for path in &route.paths {
2662                                 assert_eq!(path.len(), 4);
2663                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2664                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2665                         }
2666                         assert_eq!(total_amount_paid_msat, 49_000);
2667                 }
2668
2669                 {
2670                         // Attempt to route an exact amount is also fine
2671                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2672                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2673                         assert_eq!(route.paths.len(), 1);
2674                         let mut total_amount_paid_msat = 0;
2675                         for path in &route.paths {
2676                                 assert_eq!(path.len(), 4);
2677                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2678                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2679                         }
2680                         assert_eq!(total_amount_paid_msat, 50_000);
2681                 }
2682         }
2683
2684         #[test]
2685         fn ignore_fee_first_hop_test() {
2686                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2687                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2688
2689                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2690                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2691                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2692                         short_channel_id: 1,
2693                         timestamp: 2,
2694                         flags: 0,
2695                         cltv_expiry_delta: 0,
2696                         htlc_minimum_msat: 0,
2697                         htlc_maximum_msat: OptionalField::Present(100_000),
2698                         fee_base_msat: 1_000_000,
2699                         fee_proportional_millionths: 0,
2700                         excess_data: Vec::new()
2701                 });
2702                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2703                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2704                         short_channel_id: 3,
2705                         timestamp: 2,
2706                         flags: 0,
2707                         cltv_expiry_delta: 0,
2708                         htlc_minimum_msat: 0,
2709                         htlc_maximum_msat: OptionalField::Present(50_000),
2710                         fee_base_msat: 0,
2711                         fee_proportional_millionths: 0,
2712                         excess_data: Vec::new()
2713                 });
2714
2715                 {
2716                         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();
2717                         assert_eq!(route.paths.len(), 1);
2718                         let mut total_amount_paid_msat = 0;
2719                         for path in &route.paths {
2720                                 assert_eq!(path.len(), 2);
2721                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2722                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2723                         }
2724                         assert_eq!(total_amount_paid_msat, 50_000);
2725                 }
2726         }
2727
2728         #[test]
2729         fn simple_mpp_route_test() {
2730                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2731                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2732
2733                 // We need a route consisting of 3 paths:
2734                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2735                 // To achieve this, the amount being transferred should be around
2736                 // the total capacity of these 3 paths.
2737
2738                 // First, we set limits on these (previously unlimited) channels.
2739                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2740
2741                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2742                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2743                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2744                         short_channel_id: 1,
2745                         timestamp: 2,
2746                         flags: 0,
2747                         cltv_expiry_delta: 0,
2748                         htlc_minimum_msat: 0,
2749                         htlc_maximum_msat: OptionalField::Present(100_000),
2750                         fee_base_msat: 0,
2751                         fee_proportional_millionths: 0,
2752                         excess_data: Vec::new()
2753                 });
2754                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2755                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2756                         short_channel_id: 3,
2757                         timestamp: 2,
2758                         flags: 0,
2759                         cltv_expiry_delta: 0,
2760                         htlc_minimum_msat: 0,
2761                         htlc_maximum_msat: OptionalField::Present(50_000),
2762                         fee_base_msat: 0,
2763                         fee_proportional_millionths: 0,
2764                         excess_data: Vec::new()
2765                 });
2766
2767                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2768                 // (total limit 60).
2769                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2770                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2771                         short_channel_id: 12,
2772                         timestamp: 2,
2773                         flags: 0,
2774                         cltv_expiry_delta: 0,
2775                         htlc_minimum_msat: 0,
2776                         htlc_maximum_msat: OptionalField::Present(60_000),
2777                         fee_base_msat: 0,
2778                         fee_proportional_millionths: 0,
2779                         excess_data: Vec::new()
2780                 });
2781                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2782                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2783                         short_channel_id: 13,
2784                         timestamp: 2,
2785                         flags: 0,
2786                         cltv_expiry_delta: 0,
2787                         htlc_minimum_msat: 0,
2788                         htlc_maximum_msat: OptionalField::Present(60_000),
2789                         fee_base_msat: 0,
2790                         fee_proportional_millionths: 0,
2791                         excess_data: Vec::new()
2792                 });
2793
2794                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2795                 // (total capacity 180 sats).
2796                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2797                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2798                         short_channel_id: 2,
2799                         timestamp: 2,
2800                         flags: 0,
2801                         cltv_expiry_delta: 0,
2802                         htlc_minimum_msat: 0,
2803                         htlc_maximum_msat: OptionalField::Present(200_000),
2804                         fee_base_msat: 0,
2805                         fee_proportional_millionths: 0,
2806                         excess_data: Vec::new()
2807                 });
2808                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2809                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2810                         short_channel_id: 4,
2811                         timestamp: 2,
2812                         flags: 0,
2813                         cltv_expiry_delta: 0,
2814                         htlc_minimum_msat: 0,
2815                         htlc_maximum_msat: OptionalField::Present(180_000),
2816                         fee_base_msat: 0,
2817                         fee_proportional_millionths: 0,
2818                         excess_data: Vec::new()
2819                 });
2820
2821                 {
2822                         // Attempt to route more than available results in a failure.
2823                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2824                                         &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2825                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2826                         } else { panic!(); }
2827                 }
2828
2829                 {
2830                         // Now, attempt to route 250 sats (just a bit below the capacity).
2831                         // Our algorithm should provide us with these 3 paths.
2832                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2833                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2834                         assert_eq!(route.paths.len(), 3);
2835                         let mut total_amount_paid_msat = 0;
2836                         for path in &route.paths {
2837                                 assert_eq!(path.len(), 2);
2838                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2839                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2840                         }
2841                         assert_eq!(total_amount_paid_msat, 250_000);
2842                 }
2843
2844                 {
2845                         // Attempt to route an exact amount is also fine
2846                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2847                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2848                         assert_eq!(route.paths.len(), 3);
2849                         let mut total_amount_paid_msat = 0;
2850                         for path in &route.paths {
2851                                 assert_eq!(path.len(), 2);
2852                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2853                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2854                         }
2855                         assert_eq!(total_amount_paid_msat, 290_000);
2856                 }
2857         }
2858
2859         #[test]
2860         fn long_mpp_route_test() {
2861                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2862                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2863
2864                 // We need a route consisting of 3 paths:
2865                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2866                 // Note that these paths overlap (channels 5, 12, 13).
2867                 // We will route 300 sats.
2868                 // Each path will have 100 sats capacity, those channels which
2869                 // are used twice will have 200 sats capacity.
2870
2871                 // Disable other potential paths.
2872                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2873                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2874                         short_channel_id: 2,
2875                         timestamp: 2,
2876                         flags: 2,
2877                         cltv_expiry_delta: 0,
2878                         htlc_minimum_msat: 0,
2879                         htlc_maximum_msat: OptionalField::Present(100_000),
2880                         fee_base_msat: 0,
2881                         fee_proportional_millionths: 0,
2882                         excess_data: Vec::new()
2883                 });
2884                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2885                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2886                         short_channel_id: 7,
2887                         timestamp: 2,
2888                         flags: 2,
2889                         cltv_expiry_delta: 0,
2890                         htlc_minimum_msat: 0,
2891                         htlc_maximum_msat: OptionalField::Present(100_000),
2892                         fee_base_msat: 0,
2893                         fee_proportional_millionths: 0,
2894                         excess_data: Vec::new()
2895                 });
2896
2897                 // Path via {node0, node2} is channels {1, 3, 5}.
2898                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2899                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2900                         short_channel_id: 1,
2901                         timestamp: 2,
2902                         flags: 0,
2903                         cltv_expiry_delta: 0,
2904                         htlc_minimum_msat: 0,
2905                         htlc_maximum_msat: OptionalField::Present(100_000),
2906                         fee_base_msat: 0,
2907                         fee_proportional_millionths: 0,
2908                         excess_data: Vec::new()
2909                 });
2910                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2911                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2912                         short_channel_id: 3,
2913                         timestamp: 2,
2914                         flags: 0,
2915                         cltv_expiry_delta: 0,
2916                         htlc_minimum_msat: 0,
2917                         htlc_maximum_msat: OptionalField::Present(100_000),
2918                         fee_base_msat: 0,
2919                         fee_proportional_millionths: 0,
2920                         excess_data: Vec::new()
2921                 });
2922
2923                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2924                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2925                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2926                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2927                         short_channel_id: 5,
2928                         timestamp: 2,
2929                         flags: 0,
2930                         cltv_expiry_delta: 0,
2931                         htlc_minimum_msat: 0,
2932                         htlc_maximum_msat: OptionalField::Present(200_000),
2933                         fee_base_msat: 0,
2934                         fee_proportional_millionths: 0,
2935                         excess_data: Vec::new()
2936                 });
2937
2938                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2939                 // Add 100 sats to the capacities of {12, 13}, because these channels
2940                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2941                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2942                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2943                         short_channel_id: 12,
2944                         timestamp: 2,
2945                         flags: 0,
2946                         cltv_expiry_delta: 0,
2947                         htlc_minimum_msat: 0,
2948                         htlc_maximum_msat: OptionalField::Present(200_000),
2949                         fee_base_msat: 0,
2950                         fee_proportional_millionths: 0,
2951                         excess_data: Vec::new()
2952                 });
2953                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2954                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2955                         short_channel_id: 13,
2956                         timestamp: 2,
2957                         flags: 0,
2958                         cltv_expiry_delta: 0,
2959                         htlc_minimum_msat: 0,
2960                         htlc_maximum_msat: OptionalField::Present(200_000),
2961                         fee_base_msat: 0,
2962                         fee_proportional_millionths: 0,
2963                         excess_data: Vec::new()
2964                 });
2965
2966                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2967                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2968                         short_channel_id: 6,
2969                         timestamp: 2,
2970                         flags: 0,
2971                         cltv_expiry_delta: 0,
2972                         htlc_minimum_msat: 0,
2973                         htlc_maximum_msat: OptionalField::Present(100_000),
2974                         fee_base_msat: 0,
2975                         fee_proportional_millionths: 0,
2976                         excess_data: Vec::new()
2977                 });
2978                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2979                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2980                         short_channel_id: 11,
2981                         timestamp: 2,
2982                         flags: 0,
2983                         cltv_expiry_delta: 0,
2984                         htlc_minimum_msat: 0,
2985                         htlc_maximum_msat: OptionalField::Present(100_000),
2986                         fee_base_msat: 0,
2987                         fee_proportional_millionths: 0,
2988                         excess_data: Vec::new()
2989                 });
2990
2991                 // Path via {node7, node2} is channels {12, 13, 5}.
2992                 // We already limited them to 200 sats (they are used twice for 100 sats).
2993                 // Nothing to do here.
2994
2995                 {
2996                         // Attempt to route more than available results in a failure.
2997                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2998                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
2999                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3000                         } else { panic!(); }
3001                 }
3002
3003                 {
3004                         // Now, attempt to route 300 sats (exact amount we can route).
3005                         // Our algorithm should provide us with these 3 paths, 100 sats each.
3006                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3007                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3008                         assert_eq!(route.paths.len(), 3);
3009
3010                         let mut total_amount_paid_msat = 0;
3011                         for path in &route.paths {
3012                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3013                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3014                         }
3015                         assert_eq!(total_amount_paid_msat, 300_000);
3016                 }
3017
3018         }
3019
3020         #[test]
3021         fn mpp_cheaper_route_test() {
3022                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3023                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3024
3025                 // This test checks that if we have two cheaper paths and one more expensive path,
3026                 // so that liquidity-wise any 2 of 3 combination is sufficient,
3027                 // two cheaper paths will be taken.
3028                 // These paths have equal available liquidity.
3029
3030                 // We need a combination of 3 paths:
3031                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3032                 // Note that these paths overlap (channels 5, 12, 13).
3033                 // Each path will have 100 sats capacity, those channels which
3034                 // are used twice will have 200 sats capacity.
3035
3036                 // Disable other potential paths.
3037                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3038                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3039                         short_channel_id: 2,
3040                         timestamp: 2,
3041                         flags: 2,
3042                         cltv_expiry_delta: 0,
3043                         htlc_minimum_msat: 0,
3044                         htlc_maximum_msat: OptionalField::Present(100_000),
3045                         fee_base_msat: 0,
3046                         fee_proportional_millionths: 0,
3047                         excess_data: Vec::new()
3048                 });
3049                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3050                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3051                         short_channel_id: 7,
3052                         timestamp: 2,
3053                         flags: 2,
3054                         cltv_expiry_delta: 0,
3055                         htlc_minimum_msat: 0,
3056                         htlc_maximum_msat: OptionalField::Present(100_000),
3057                         fee_base_msat: 0,
3058                         fee_proportional_millionths: 0,
3059                         excess_data: Vec::new()
3060                 });
3061
3062                 // Path via {node0, node2} is channels {1, 3, 5}.
3063                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3064                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3065                         short_channel_id: 1,
3066                         timestamp: 2,
3067                         flags: 0,
3068                         cltv_expiry_delta: 0,
3069                         htlc_minimum_msat: 0,
3070                         htlc_maximum_msat: OptionalField::Present(100_000),
3071                         fee_base_msat: 0,
3072                         fee_proportional_millionths: 0,
3073                         excess_data: Vec::new()
3074                 });
3075                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3076                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3077                         short_channel_id: 3,
3078                         timestamp: 2,
3079                         flags: 0,
3080                         cltv_expiry_delta: 0,
3081                         htlc_minimum_msat: 0,
3082                         htlc_maximum_msat: OptionalField::Present(100_000),
3083                         fee_base_msat: 0,
3084                         fee_proportional_millionths: 0,
3085                         excess_data: Vec::new()
3086                 });
3087
3088                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3089                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3090                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3091                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3092                         short_channel_id: 5,
3093                         timestamp: 2,
3094                         flags: 0,
3095                         cltv_expiry_delta: 0,
3096                         htlc_minimum_msat: 0,
3097                         htlc_maximum_msat: OptionalField::Present(200_000),
3098                         fee_base_msat: 0,
3099                         fee_proportional_millionths: 0,
3100                         excess_data: Vec::new()
3101                 });
3102
3103                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3104                 // Add 100 sats to the capacities of {12, 13}, because these channels
3105                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3106                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3107                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3108                         short_channel_id: 12,
3109                         timestamp: 2,
3110                         flags: 0,
3111                         cltv_expiry_delta: 0,
3112                         htlc_minimum_msat: 0,
3113                         htlc_maximum_msat: OptionalField::Present(200_000),
3114                         fee_base_msat: 0,
3115                         fee_proportional_millionths: 0,
3116                         excess_data: Vec::new()
3117                 });
3118                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3119                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3120                         short_channel_id: 13,
3121                         timestamp: 2,
3122                         flags: 0,
3123                         cltv_expiry_delta: 0,
3124                         htlc_minimum_msat: 0,
3125                         htlc_maximum_msat: OptionalField::Present(200_000),
3126                         fee_base_msat: 0,
3127                         fee_proportional_millionths: 0,
3128                         excess_data: Vec::new()
3129                 });
3130
3131                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3132                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3133                         short_channel_id: 6,
3134                         timestamp: 2,
3135                         flags: 0,
3136                         cltv_expiry_delta: 0,
3137                         htlc_minimum_msat: 0,
3138                         htlc_maximum_msat: OptionalField::Present(100_000),
3139                         fee_base_msat: 1_000,
3140                         fee_proportional_millionths: 0,
3141                         excess_data: Vec::new()
3142                 });
3143                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3144                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3145                         short_channel_id: 11,
3146                         timestamp: 2,
3147                         flags: 0,
3148                         cltv_expiry_delta: 0,
3149                         htlc_minimum_msat: 0,
3150                         htlc_maximum_msat: OptionalField::Present(100_000),
3151                         fee_base_msat: 0,
3152                         fee_proportional_millionths: 0,
3153                         excess_data: Vec::new()
3154                 });
3155
3156                 // Path via {node7, node2} is channels {12, 13, 5}.
3157                 // We already limited them to 200 sats (they are used twice for 100 sats).
3158                 // Nothing to do here.
3159
3160                 {
3161                         // Now, attempt to route 180 sats.
3162                         // Our algorithm should provide us with these 2 paths.
3163                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3164                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3165                         assert_eq!(route.paths.len(), 2);
3166
3167                         let mut total_value_transferred_msat = 0;
3168                         let mut total_paid_msat = 0;
3169                         for path in &route.paths {
3170                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3171                                 total_value_transferred_msat += path.last().unwrap().fee_msat;
3172                                 for hop in path {
3173                                         total_paid_msat += hop.fee_msat;
3174                                 }
3175                         }
3176                         // If we paid fee, this would be higher.
3177                         assert_eq!(total_value_transferred_msat, 180_000);
3178                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3179                         assert_eq!(total_fees_paid, 0);
3180                 }
3181         }
3182
3183         #[test]
3184         fn fees_on_mpp_route_test() {
3185                 // This test makes sure that MPP algorithm properly takes into account
3186                 // fees charged on the channels, by making the fees impactful:
3187                 // if the fee is not properly accounted for, the behavior is different.
3188                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3189                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3190
3191                 // We need a route consisting of 2 paths:
3192                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3193                 // We will route 200 sats, Each path will have 100 sats capacity.
3194
3195                 // This test is not particularly stable: e.g.,
3196                 // there's a way to route via {node0, node2, node4}.
3197                 // It works while pathfinding is deterministic, but can be broken otherwise.
3198                 // It's fine to ignore this concern for now.
3199
3200                 // Disable other potential paths.
3201                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3202                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3203                         short_channel_id: 2,
3204                         timestamp: 2,
3205                         flags: 2,
3206                         cltv_expiry_delta: 0,
3207                         htlc_minimum_msat: 0,
3208                         htlc_maximum_msat: OptionalField::Present(100_000),
3209                         fee_base_msat: 0,
3210                         fee_proportional_millionths: 0,
3211                         excess_data: Vec::new()
3212                 });
3213
3214                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3215                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3216                         short_channel_id: 7,
3217                         timestamp: 2,
3218                         flags: 2,
3219                         cltv_expiry_delta: 0,
3220                         htlc_minimum_msat: 0,
3221                         htlc_maximum_msat: OptionalField::Present(100_000),
3222                         fee_base_msat: 0,
3223                         fee_proportional_millionths: 0,
3224                         excess_data: Vec::new()
3225                 });
3226
3227                 // Path via {node0, node2} is channels {1, 3, 5}.
3228                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3229                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3230                         short_channel_id: 1,
3231                         timestamp: 2,
3232                         flags: 0,
3233                         cltv_expiry_delta: 0,
3234                         htlc_minimum_msat: 0,
3235                         htlc_maximum_msat: OptionalField::Present(100_000),
3236                         fee_base_msat: 0,
3237                         fee_proportional_millionths: 0,
3238                         excess_data: Vec::new()
3239                 });
3240                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3241                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3242                         short_channel_id: 3,
3243                         timestamp: 2,
3244                         flags: 0,
3245                         cltv_expiry_delta: 0,
3246                         htlc_minimum_msat: 0,
3247                         htlc_maximum_msat: OptionalField::Present(100_000),
3248                         fee_base_msat: 0,
3249                         fee_proportional_millionths: 0,
3250                         excess_data: Vec::new()
3251                 });
3252
3253                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3254                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3255                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3256                         short_channel_id: 5,
3257                         timestamp: 2,
3258                         flags: 0,
3259                         cltv_expiry_delta: 0,
3260                         htlc_minimum_msat: 0,
3261                         htlc_maximum_msat: OptionalField::Present(100_000),
3262                         fee_base_msat: 0,
3263                         fee_proportional_millionths: 0,
3264                         excess_data: Vec::new()
3265                 });
3266
3267                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3268                 // All channels should be 100 sats capacity. But for the fee experiment,
3269                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3270                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3271                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3272                 // so no matter how large are other channels,
3273                 // the whole path will be limited by 100 sats with just these 2 conditions:
3274                 // - channel 12 capacity is 250 sats
3275                 // - fee for channel 6 is 150 sats
3276                 // Let's test this by enforcing these 2 conditions and removing other limits.
3277                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3278                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3279                         short_channel_id: 12,
3280                         timestamp: 2,
3281                         flags: 0,
3282                         cltv_expiry_delta: 0,
3283                         htlc_minimum_msat: 0,
3284                         htlc_maximum_msat: OptionalField::Present(250_000),
3285                         fee_base_msat: 0,
3286                         fee_proportional_millionths: 0,
3287                         excess_data: Vec::new()
3288                 });
3289                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3290                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3291                         short_channel_id: 13,
3292                         timestamp: 2,
3293                         flags: 0,
3294                         cltv_expiry_delta: 0,
3295                         htlc_minimum_msat: 0,
3296                         htlc_maximum_msat: OptionalField::Absent,
3297                         fee_base_msat: 0,
3298                         fee_proportional_millionths: 0,
3299                         excess_data: Vec::new()
3300                 });
3301
3302                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3303                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3304                         short_channel_id: 6,
3305                         timestamp: 2,
3306                         flags: 0,
3307                         cltv_expiry_delta: 0,
3308                         htlc_minimum_msat: 0,
3309                         htlc_maximum_msat: OptionalField::Absent,
3310                         fee_base_msat: 150_000,
3311                         fee_proportional_millionths: 0,
3312                         excess_data: Vec::new()
3313                 });
3314                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3315                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3316                         short_channel_id: 11,
3317                         timestamp: 2,
3318                         flags: 0,
3319                         cltv_expiry_delta: 0,
3320                         htlc_minimum_msat: 0,
3321                         htlc_maximum_msat: OptionalField::Absent,
3322                         fee_base_msat: 0,
3323                         fee_proportional_millionths: 0,
3324                         excess_data: Vec::new()
3325                 });
3326
3327                 {
3328                         // Attempt to route more than available results in a failure.
3329                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3330                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3331                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3332                         } else { panic!(); }
3333                 }
3334
3335                 {
3336                         // Now, attempt to route 200 sats (exact amount we can route).
3337                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3338                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3339                         assert_eq!(route.paths.len(), 2);
3340
3341                         let mut total_amount_paid_msat = 0;
3342                         for path in &route.paths {
3343                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3344                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3345                         }
3346                         assert_eq!(total_amount_paid_msat, 200_000);
3347                 }
3348
3349         }
3350
3351         #[test]
3352         fn drop_lowest_channel_mpp_route_test() {
3353                 // This test checks that low-capacity channel is dropped when after
3354                 // path finding we realize that we found more capacity than we need.
3355                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3356                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3357
3358                 // We need a route consisting of 3 paths:
3359                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3360
3361                 // The first and the second paths should be sufficient, but the third should be
3362                 // cheaper, so that we select it but drop later.
3363
3364                 // First, we set limits on these (previously unlimited) channels.
3365                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3366
3367                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3368                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3369                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3370                         short_channel_id: 1,
3371                         timestamp: 2,
3372                         flags: 0,
3373                         cltv_expiry_delta: 0,
3374                         htlc_minimum_msat: 0,
3375                         htlc_maximum_msat: OptionalField::Present(100_000),
3376                         fee_base_msat: 0,
3377                         fee_proportional_millionths: 0,
3378                         excess_data: Vec::new()
3379                 });
3380                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3381                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3382                         short_channel_id: 3,
3383                         timestamp: 2,
3384                         flags: 0,
3385                         cltv_expiry_delta: 0,
3386                         htlc_minimum_msat: 0,
3387                         htlc_maximum_msat: OptionalField::Present(50_000),
3388                         fee_base_msat: 100,
3389                         fee_proportional_millionths: 0,
3390                         excess_data: Vec::new()
3391                 });
3392
3393                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3394                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3395                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3396                         short_channel_id: 12,
3397                         timestamp: 2,
3398                         flags: 0,
3399                         cltv_expiry_delta: 0,
3400                         htlc_minimum_msat: 0,
3401                         htlc_maximum_msat: OptionalField::Present(60_000),
3402                         fee_base_msat: 100,
3403                         fee_proportional_millionths: 0,
3404                         excess_data: Vec::new()
3405                 });
3406                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3407                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3408                         short_channel_id: 13,
3409                         timestamp: 2,
3410                         flags: 0,
3411                         cltv_expiry_delta: 0,
3412                         htlc_minimum_msat: 0,
3413                         htlc_maximum_msat: OptionalField::Present(60_000),
3414                         fee_base_msat: 0,
3415                         fee_proportional_millionths: 0,
3416                         excess_data: Vec::new()
3417                 });
3418
3419                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3420                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3421                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3422                         short_channel_id: 2,
3423                         timestamp: 2,
3424                         flags: 0,
3425                         cltv_expiry_delta: 0,
3426                         htlc_minimum_msat: 0,
3427                         htlc_maximum_msat: OptionalField::Present(20_000),
3428                         fee_base_msat: 0,
3429                         fee_proportional_millionths: 0,
3430                         excess_data: Vec::new()
3431                 });
3432                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3433                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3434                         short_channel_id: 4,
3435                         timestamp: 2,
3436                         flags: 0,
3437                         cltv_expiry_delta: 0,
3438                         htlc_minimum_msat: 0,
3439                         htlc_maximum_msat: OptionalField::Present(20_000),
3440                         fee_base_msat: 0,
3441                         fee_proportional_millionths: 0,
3442                         excess_data: Vec::new()
3443                 });
3444
3445                 {
3446                         // Attempt to route more than available results in a failure.
3447                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3448                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3449                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3450                         } else { panic!(); }
3451                 }
3452
3453                 {
3454                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3455                         // Our algorithm should provide us with these 3 paths.
3456                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3457                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3458                         assert_eq!(route.paths.len(), 3);
3459                         let mut total_amount_paid_msat = 0;
3460                         for path in &route.paths {
3461                                 assert_eq!(path.len(), 2);
3462                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3463                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3464                         }
3465                         assert_eq!(total_amount_paid_msat, 125_000);
3466                 }
3467
3468                 {
3469                         // Attempt to route without the last small cheap channel
3470                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3471                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3472                         assert_eq!(route.paths.len(), 2);
3473                         let mut total_amount_paid_msat = 0;
3474                         for path in &route.paths {
3475                                 assert_eq!(path.len(), 2);
3476                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3477                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3478                         }
3479                         assert_eq!(total_amount_paid_msat, 90_000);
3480                 }
3481         }
3482
3483         #[test]
3484         fn exact_fee_liquidity_limit() {
3485                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3486                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3487                 // we calculated fees on a higher value, resulting in us ignoring such paths.
3488                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3489                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3490
3491                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3492                 // send.
3493                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3494                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3495                         short_channel_id: 2,
3496                         timestamp: 2,
3497                         flags: 0,
3498                         cltv_expiry_delta: 0,
3499                         htlc_minimum_msat: 0,
3500                         htlc_maximum_msat: OptionalField::Present(85_000),
3501                         fee_base_msat: 0,
3502                         fee_proportional_millionths: 0,
3503                         excess_data: Vec::new()
3504                 });
3505
3506                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3507                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3508                         short_channel_id: 12,
3509                         timestamp: 2,
3510                         flags: 0,
3511                         cltv_expiry_delta: (4 << 8) | 1,
3512                         htlc_minimum_msat: 0,
3513                         htlc_maximum_msat: OptionalField::Present(270_000),
3514                         fee_base_msat: 0,
3515                         fee_proportional_millionths: 1000000,
3516                         excess_data: Vec::new()
3517                 });
3518
3519                 {
3520                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3521                         // 200% fee charged channel 13 in the 1-to-2 direction.
3522                         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();
3523                         assert_eq!(route.paths.len(), 1);
3524                         assert_eq!(route.paths[0].len(), 2);
3525
3526                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3527                         assert_eq!(route.paths[0][0].short_channel_id, 12);
3528                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3529                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3530                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3531                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3532
3533                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3534                         assert_eq!(route.paths[0][1].short_channel_id, 13);
3535                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
3536                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3537                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3538                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3539                 }
3540         }
3541
3542         #[test]
3543         fn htlc_max_reduction_below_min() {
3544                 // Test that if, while walking the graph, we reduce the value being sent to meet an
3545                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3546                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3547                 // resulting in us thinking there is no possible path, even if other paths exist.
3548                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3549                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3550
3551                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3552                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3553                 // then try to send 90_000.
3554                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3555                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3556                         short_channel_id: 2,
3557                         timestamp: 2,
3558                         flags: 0,
3559                         cltv_expiry_delta: 0,
3560                         htlc_minimum_msat: 0,
3561                         htlc_maximum_msat: OptionalField::Present(80_000),
3562                         fee_base_msat: 0,
3563                         fee_proportional_millionths: 0,
3564                         excess_data: Vec::new()
3565                 });
3566                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3567                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3568                         short_channel_id: 4,
3569                         timestamp: 2,
3570                         flags: 0,
3571                         cltv_expiry_delta: (4 << 8) | 1,
3572                         htlc_minimum_msat: 90_000,
3573                         htlc_maximum_msat: OptionalField::Absent,
3574                         fee_base_msat: 0,
3575                         fee_proportional_millionths: 0,
3576                         excess_data: Vec::new()
3577                 });
3578
3579                 {
3580                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3581                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3582                         // expensive) channels 12-13 path.
3583                         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();
3584                         assert_eq!(route.paths.len(), 1);
3585                         assert_eq!(route.paths[0].len(), 2);
3586
3587                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3588                         assert_eq!(route.paths[0][0].short_channel_id, 12);
3589                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3590                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3591                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3592                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3593
3594                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3595                         assert_eq!(route.paths[0][1].short_channel_id, 13);
3596                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
3597                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3598                         assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3599                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3600                 }
3601         }
3602 }
3603
3604 #[cfg(all(test, feature = "unstable"))]
3605 mod benches {
3606         use super::*;
3607         use util::logger::{Logger, Record};
3608
3609         use std::fs::File;
3610         use test::Bencher;
3611
3612         struct DummyLogger {}
3613         impl Logger for DummyLogger {
3614                 fn log(&self, _record: &Record) {}
3615         }
3616
3617         #[bench]
3618         fn generate_routes(bench: &mut Bencher) {
3619                 let mut d = File::open("net_graph-2021-02-12.bin").expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3620                 let graph = NetworkGraph::read(&mut d).unwrap();
3621
3622                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3623                 let mut path_endpoints = Vec::new();
3624                 let mut seed: usize = 0xdeadbeef;
3625                 'load_endpoints: for _ in 0..100 {
3626                         loop {
3627                                 seed *= 0xdeadbeef;
3628                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3629                                 seed *= 0xdeadbeef;
3630                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3631                                 let amt = seed as u64 % 1_000_000;
3632                                 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3633                                         path_endpoints.push((src, dst, amt));
3634                                         continue 'load_endpoints;
3635                                 }
3636                         }
3637                 }
3638
3639                 // ...then benchmark finding paths between the nodes we learned.
3640                 let mut idx = 0;
3641                 bench.iter(|| {
3642                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3643                         assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3644                         idx += 1;
3645                 });
3646         }
3647
3648         #[bench]
3649         fn generate_mpp_routes(bench: &mut Bencher) {
3650                 let mut d = File::open("net_graph-2021-02-12.bin").expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3651                 let graph = NetworkGraph::read(&mut d).unwrap();
3652
3653                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3654                 let mut path_endpoints = Vec::new();
3655                 let mut seed: usize = 0xdeadbeef;
3656                 'load_endpoints: for _ in 0..100 {
3657                         loop {
3658                                 seed *= 0xdeadbeef;
3659                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3660                                 seed *= 0xdeadbeef;
3661                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3662                                 let amt = seed as u64 % 1_000_000;
3663                                 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3664                                         path_endpoints.push((src, dst, amt));
3665                                         continue 'load_endpoints;
3666                                 }
3667                         }
3668                 }
3669
3670                 // ...then benchmark finding paths between the nodes we learned.
3671                 let mut idx = 0;
3672                 bench.iter(|| {
3673                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3674                         assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());
3675                         idx += 1;
3676                 });
3677         }
3678 }