[router] Track full-path htlc-minimum-msat while graph-walking
[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(value_contribution_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                                 for payment_hop in payment_path.hops.iter() {
909                                         let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.route_hop.short_channel_id).unwrap();
910                                         let mut spent_on_hop_msat = value_contribution_msat;
911                                         let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
912                                         spent_on_hop_msat += next_hops_fee_msat;
913                                         if *channel_liquidity_available_msat < spent_on_hop_msat {
914                                                 // This should not happen because we do recompute fees right before,
915                                                 // trying to avoid cases when a hop is not usable due to the fee situation.
916                                                 break 'path_construction;
917                                         }
918                                         *channel_liquidity_available_msat -= spent_on_hop_msat;
919                                 }
920                                 // Track the total amount all our collected paths allow to send so that we:
921                                 // - know when to stop looking for more paths
922                                 // - know which of the hops are useless considering how much more sats we need
923                                 //   (contributes_sufficient_value)
924                                 already_collected_value_msat += value_contribution_msat;
925
926                                 payment_paths.push(payment_path);
927                                 found_new_path = true;
928                                 break 'path_construction;
929                         }
930
931                         // Otherwise, since the current target node is not us,
932                         // keep "unrolling" the payment graph from payee to payer by
933                         // finding a way to reach the current target from the payer side.
934                         match network.get_nodes().get(&pubkey) {
935                                 None => {},
936                                 Some(node) => {
937                                         add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
938                                 },
939                         }
940                 }
941
942                 if !allow_mpp {
943                         // If we don't support MPP, no use trying to gather more value ever.
944                         break 'paths_collection;
945                 }
946
947                 // Step (3).
948                 // Stop either when the recommended value is reached or if no new path was found in this
949                 // iteration.
950                 // In the latter case, making another path finding attempt won't help,
951                 // because we deterministically terminated the search due to low liquidity.
952                 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
953                         break 'paths_collection;
954                 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
955                         // Further, if this was our first walk of the graph, and we weren't limited by an
956                         // htlc_minimum_msat, return immediately because this path should suffice. If we were
957                         // limited by an htlc_minimum_msat value, find another path with a higher value,
958                         // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
959                         // still keeping a lower total fee than this path.
960                         if !hit_minimum_limit {
961                                 break 'paths_collection;
962                         }
963                         path_value_msat = recommended_value_msat;
964                 }
965         }
966
967         // Step (4).
968         if payment_paths.len() == 0 {
969                 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
970         }
971
972         if already_collected_value_msat < final_value_msat {
973                 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
974         }
975
976         // Sort by total fees and take the best paths.
977         payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
978         if payment_paths.len() > 50 {
979                 payment_paths.truncate(50);
980         }
981
982         // Draw multiple sufficient routes by randomly combining the selected paths.
983         let mut drawn_routes = Vec::new();
984         for i in 0..payment_paths.len() {
985                 let mut cur_route = Vec::<PaymentPath>::new();
986                 let mut aggregate_route_value_msat = 0;
987
988                 // Step (5).
989                 // TODO: real random shuffle
990                 // Currently just starts with i_th and goes up to i-1_th in a looped way.
991                 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
992
993                 // Step (6).
994                 for payment_path in cur_payment_paths {
995                         cur_route.push(payment_path.clone());
996                         aggregate_route_value_msat += payment_path.get_value_msat();
997                         if aggregate_route_value_msat > final_value_msat {
998                                 // Last path likely overpaid. Substract it from the most expensive
999                                 // (in terms of proportional fee) path in this route and recompute fees.
1000                                 // This might be not the most economically efficient way, but fewer paths
1001                                 // also makes routing more reliable.
1002                                 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1003
1004                                 // First, drop some expensive low-value paths entirely if possible.
1005                                 // Sort by value so that we drop many really-low values first, since
1006                                 // fewer paths is better: the payment is less likely to fail.
1007                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1008                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1009                                 cur_route.sort_by_key(|path| path.get_value_msat());
1010                                 // We should make sure that at least 1 path left.
1011                                 let mut paths_left = cur_route.len();
1012                                 cur_route.retain(|path| {
1013                                         if paths_left == 1 {
1014                                                 return true
1015                                         }
1016                                         let mut keep = true;
1017                                         let path_value_msat = path.get_value_msat();
1018                                         if path_value_msat <= overpaid_value_msat {
1019                                                 keep = false;
1020                                                 overpaid_value_msat -= path_value_msat;
1021                                                 paths_left -= 1;
1022                                         }
1023                                         keep
1024                                 });
1025
1026                                 if overpaid_value_msat == 0 {
1027                                         break;
1028                                 }
1029
1030                                 assert!(cur_route.len() > 0);
1031
1032                                 // Step (7).
1033                                 // Now, substract the overpaid value from the most-expensive path.
1034                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1035                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1036                                 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
1037                                 let expensive_payment_path = cur_route.first_mut().unwrap();
1038                                 // We already dropped all the small channels above, meaning all the
1039                                 // remaining channels are larger than remaining overpaid_value_msat.
1040                                 // Thus, this can't be negative.
1041                                 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1042                                 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1043                                 break;
1044                         }
1045                 }
1046                 drawn_routes.push(cur_route);
1047         }
1048
1049         // Step (8).
1050         // Select the best route by lowest total fee.
1051         drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1052         let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1053         for payment_path in drawn_routes.first().unwrap() {
1054                 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
1055         }
1056
1057         if let Some(features) = &payee_features {
1058                 for path in selected_paths.iter_mut() {
1059                         path.last_mut().unwrap().node_features = features.to_context();
1060                 }
1061         }
1062
1063         let route = Route { paths: selected_paths };
1064         log_trace!(logger, "Got route: {}", log_route!(route));
1065         Ok(route)
1066 }
1067
1068 #[cfg(test)]
1069 mod tests {
1070         use routing::router::{get_route, RouteHint, RoutingFees};
1071         use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1072         use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1073         use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1074            NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1075         use ln::channelmanager;
1076         use util::test_utils;
1077         use util::ser::Writeable;
1078
1079         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1080         use bitcoin::hashes::Hash;
1081         use bitcoin::network::constants::Network;
1082         use bitcoin::blockdata::constants::genesis_block;
1083         use bitcoin::blockdata::script::Builder;
1084         use bitcoin::blockdata::opcodes;
1085         use bitcoin::blockdata::transaction::TxOut;
1086
1087         use hex;
1088
1089         use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1090         use bitcoin::secp256k1::{Secp256k1, All};
1091
1092         use std::sync::Arc;
1093
1094         // Using the same keys for LN and BTC ids
1095         fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1096            node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1097                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1098                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1099
1100                 let unsigned_announcement = UnsignedChannelAnnouncement {
1101                         features,
1102                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1103                         short_channel_id,
1104                         node_id_1,
1105                         node_id_2,
1106                         bitcoin_key_1: node_id_1,
1107                         bitcoin_key_2: node_id_2,
1108                         excess_data: Vec::new(),
1109                 };
1110
1111                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1112                 let valid_announcement = ChannelAnnouncement {
1113                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1114                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1115                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1116                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1117                         contents: unsigned_announcement.clone(),
1118                 };
1119                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1120                         Ok(res) => assert!(res),
1121                         _ => panic!()
1122                 };
1123         }
1124
1125         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) {
1126                 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1127                 let valid_channel_update = ChannelUpdate {
1128                         signature: secp_ctx.sign(&msghash, node_privkey),
1129                         contents: update.clone()
1130                 };
1131
1132                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1133                         Ok(res) => assert!(res),
1134                         Err(_) => panic!()
1135                 };
1136         }
1137
1138         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,
1139            features: NodeFeatures, timestamp: u32) {
1140                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1141                 let unsigned_announcement = UnsignedNodeAnnouncement {
1142                         features,
1143                         timestamp,
1144                         node_id,
1145                         rgb: [0; 3],
1146                         alias: [0; 32],
1147                         addresses: Vec::new(),
1148                         excess_address_data: Vec::new(),
1149                         excess_data: Vec::new(),
1150                 };
1151                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1152                 let valid_announcement = NodeAnnouncement {
1153                         signature: secp_ctx.sign(&msghash, node_privkey),
1154                         contents: unsigned_announcement.clone()
1155                 };
1156
1157                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1158                         Ok(_) => (),
1159                         Err(_) => panic!()
1160                 };
1161         }
1162
1163         fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1164                 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1165                         SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1166                 }).collect();
1167
1168                 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1169
1170                 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1171                 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1172
1173                 (our_privkey, our_id, privkeys, pubkeys)
1174         }
1175
1176         fn id_to_feature_flags(id: u8) -> Vec<u8> {
1177                 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1178                 // test for it later.
1179                 let idx = (id - 1) * 2 + 1;
1180                 if idx > 8*3 {
1181                         vec![1 << (idx - 8*3), 0, 0, 0]
1182                 } else if idx > 8*2 {
1183                         vec![1 << (idx - 8*2), 0, 0]
1184                 } else if idx > 8*1 {
1185                         vec![1 << (idx - 8*1), 0]
1186                 } else {
1187                         vec![1 << idx]
1188                 }
1189         }
1190
1191         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>) {
1192                 let secp_ctx = Secp256k1::new();
1193                 let logger = Arc::new(test_utils::TestLogger::new());
1194                 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1195                 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1196                 // Build network from our_id to node7:
1197                 //
1198                 //        -1(1)2-  node0  -1(3)2-
1199                 //       /                       \
1200                 // our_id -1(12)2- node7 -1(13)2--- node2
1201                 //       \                       /
1202                 //        -1(2)2-  node1  -1(4)2-
1203                 //
1204                 //
1205                 // chan1  1-to-2: disabled
1206                 // chan1  2-to-1: enabled, 0 fee
1207                 //
1208                 // chan2  1-to-2: enabled, ignored fee
1209                 // chan2  2-to-1: enabled, 0 fee
1210                 //
1211                 // chan3  1-to-2: enabled, 0 fee
1212                 // chan3  2-to-1: enabled, 100 msat fee
1213                 //
1214                 // chan4  1-to-2: enabled, 100% fee
1215                 // chan4  2-to-1: enabled, 0 fee
1216                 //
1217                 // chan12 1-to-2: enabled, ignored fee
1218                 // chan12 2-to-1: enabled, 0 fee
1219                 //
1220                 // chan13 1-to-2: enabled, 200% fee
1221                 // chan13 2-to-1: enabled, 0 fee
1222                 //
1223                 //
1224                 //       -1(5)2- node3 -1(8)2--
1225                 //       |         2          |
1226                 //       |       (11)         |
1227                 //      /          1           \
1228                 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1229                 //      \                      /
1230                 //       -1(7)2- node5 -1(10)2-
1231                 //
1232                 // chan5  1-to-2: enabled, 100 msat fee
1233                 // chan5  2-to-1: enabled, 0 fee
1234                 //
1235                 // chan6  1-to-2: enabled, 0 fee
1236                 // chan6  2-to-1: enabled, 0 fee
1237                 //
1238                 // chan7  1-to-2: enabled, 100% fee
1239                 // chan7  2-to-1: enabled, 0 fee
1240                 //
1241                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
1242                 // chan8  2-to-1: enabled, 0 fee
1243                 //
1244                 // chan9  1-to-2: enabled, 1001 msat fee
1245                 // chan9  2-to-1: enabled, 0 fee
1246                 //
1247                 // chan10 1-to-2: enabled, 0 fee
1248                 // chan10 2-to-1: enabled, 0 fee
1249                 //
1250                 // chan11 1-to-2: enabled, 0 fee
1251                 // chan11 2-to-1: enabled, 0 fee
1252
1253                 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1254
1255                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1256                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1257                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1258                         short_channel_id: 1,
1259                         timestamp: 1,
1260                         flags: 1,
1261                         cltv_expiry_delta: 0,
1262                         htlc_minimum_msat: 0,
1263                         htlc_maximum_msat: OptionalField::Absent,
1264                         fee_base_msat: 0,
1265                         fee_proportional_millionths: 0,
1266                         excess_data: Vec::new()
1267                 });
1268
1269                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1270
1271                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1272                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1273                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1274                         short_channel_id: 2,
1275                         timestamp: 1,
1276                         flags: 0,
1277                         cltv_expiry_delta: u16::max_value(),
1278                         htlc_minimum_msat: 0,
1279                         htlc_maximum_msat: OptionalField::Absent,
1280                         fee_base_msat: u32::max_value(),
1281                         fee_proportional_millionths: u32::max_value(),
1282                         excess_data: Vec::new()
1283                 });
1284                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1285                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1286                         short_channel_id: 2,
1287                         timestamp: 1,
1288                         flags: 1,
1289                         cltv_expiry_delta: 0,
1290                         htlc_minimum_msat: 0,
1291                         htlc_maximum_msat: OptionalField::Absent,
1292                         fee_base_msat: 0,
1293                         fee_proportional_millionths: 0,
1294                         excess_data: Vec::new()
1295                 });
1296
1297                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1298
1299                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1300                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1301                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1302                         short_channel_id: 12,
1303                         timestamp: 1,
1304                         flags: 0,
1305                         cltv_expiry_delta: u16::max_value(),
1306                         htlc_minimum_msat: 0,
1307                         htlc_maximum_msat: OptionalField::Absent,
1308                         fee_base_msat: u32::max_value(),
1309                         fee_proportional_millionths: u32::max_value(),
1310                         excess_data: Vec::new()
1311                 });
1312                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1313                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1314                         short_channel_id: 12,
1315                         timestamp: 1,
1316                         flags: 1,
1317                         cltv_expiry_delta: 0,
1318                         htlc_minimum_msat: 0,
1319                         htlc_maximum_msat: OptionalField::Absent,
1320                         fee_base_msat: 0,
1321                         fee_proportional_millionths: 0,
1322                         excess_data: Vec::new()
1323                 });
1324
1325                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1326
1327                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1328                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1329                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1330                         short_channel_id: 3,
1331                         timestamp: 1,
1332                         flags: 0,
1333                         cltv_expiry_delta: (3 << 8) | 1,
1334                         htlc_minimum_msat: 0,
1335                         htlc_maximum_msat: OptionalField::Absent,
1336                         fee_base_msat: 0,
1337                         fee_proportional_millionths: 0,
1338                         excess_data: Vec::new()
1339                 });
1340                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1341                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1342                         short_channel_id: 3,
1343                         timestamp: 1,
1344                         flags: 1,
1345                         cltv_expiry_delta: (3 << 8) | 2,
1346                         htlc_minimum_msat: 0,
1347                         htlc_maximum_msat: OptionalField::Absent,
1348                         fee_base_msat: 100,
1349                         fee_proportional_millionths: 0,
1350                         excess_data: Vec::new()
1351                 });
1352
1353                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1354                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1355                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1356                         short_channel_id: 4,
1357                         timestamp: 1,
1358                         flags: 0,
1359                         cltv_expiry_delta: (4 << 8) | 1,
1360                         htlc_minimum_msat: 0,
1361                         htlc_maximum_msat: OptionalField::Absent,
1362                         fee_base_msat: 0,
1363                         fee_proportional_millionths: 1000000,
1364                         excess_data: Vec::new()
1365                 });
1366                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1367                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1368                         short_channel_id: 4,
1369                         timestamp: 1,
1370                         flags: 1,
1371                         cltv_expiry_delta: (4 << 8) | 2,
1372                         htlc_minimum_msat: 0,
1373                         htlc_maximum_msat: OptionalField::Absent,
1374                         fee_base_msat: 0,
1375                         fee_proportional_millionths: 0,
1376                         excess_data: Vec::new()
1377                 });
1378
1379                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1380                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1381                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1382                         short_channel_id: 13,
1383                         timestamp: 1,
1384                         flags: 0,
1385                         cltv_expiry_delta: (13 << 8) | 1,
1386                         htlc_minimum_msat: 0,
1387                         htlc_maximum_msat: OptionalField::Absent,
1388                         fee_base_msat: 0,
1389                         fee_proportional_millionths: 2000000,
1390                         excess_data: Vec::new()
1391                 });
1392                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1393                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1394                         short_channel_id: 13,
1395                         timestamp: 1,
1396                         flags: 1,
1397                         cltv_expiry_delta: (13 << 8) | 2,
1398                         htlc_minimum_msat: 0,
1399                         htlc_maximum_msat: OptionalField::Absent,
1400                         fee_base_msat: 0,
1401                         fee_proportional_millionths: 0,
1402                         excess_data: Vec::new()
1403                 });
1404
1405                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1406
1407                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1408                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1409                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1410                         short_channel_id: 6,
1411                         timestamp: 1,
1412                         flags: 0,
1413                         cltv_expiry_delta: (6 << 8) | 1,
1414                         htlc_minimum_msat: 0,
1415                         htlc_maximum_msat: OptionalField::Absent,
1416                         fee_base_msat: 0,
1417                         fee_proportional_millionths: 0,
1418                         excess_data: Vec::new()
1419                 });
1420                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1421                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1422                         short_channel_id: 6,
1423                         timestamp: 1,
1424                         flags: 1,
1425                         cltv_expiry_delta: (6 << 8) | 2,
1426                         htlc_minimum_msat: 0,
1427                         htlc_maximum_msat: OptionalField::Absent,
1428                         fee_base_msat: 0,
1429                         fee_proportional_millionths: 0,
1430                         excess_data: Vec::new(),
1431                 });
1432
1433                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1434                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1435                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1436                         short_channel_id: 11,
1437                         timestamp: 1,
1438                         flags: 0,
1439                         cltv_expiry_delta: (11 << 8) | 1,
1440                         htlc_minimum_msat: 0,
1441                         htlc_maximum_msat: OptionalField::Absent,
1442                         fee_base_msat: 0,
1443                         fee_proportional_millionths: 0,
1444                         excess_data: Vec::new()
1445                 });
1446                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1447                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1448                         short_channel_id: 11,
1449                         timestamp: 1,
1450                         flags: 1,
1451                         cltv_expiry_delta: (11 << 8) | 2,
1452                         htlc_minimum_msat: 0,
1453                         htlc_maximum_msat: OptionalField::Absent,
1454                         fee_base_msat: 0,
1455                         fee_proportional_millionths: 0,
1456                         excess_data: Vec::new()
1457                 });
1458
1459                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1460
1461                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1462
1463                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1464                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1465                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1466                         short_channel_id: 7,
1467                         timestamp: 1,
1468                         flags: 0,
1469                         cltv_expiry_delta: (7 << 8) | 1,
1470                         htlc_minimum_msat: 0,
1471                         htlc_maximum_msat: OptionalField::Absent,
1472                         fee_base_msat: 0,
1473                         fee_proportional_millionths: 1000000,
1474                         excess_data: Vec::new()
1475                 });
1476                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1477                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1478                         short_channel_id: 7,
1479                         timestamp: 1,
1480                         flags: 1,
1481                         cltv_expiry_delta: (7 << 8) | 2,
1482                         htlc_minimum_msat: 0,
1483                         htlc_maximum_msat: OptionalField::Absent,
1484                         fee_base_msat: 0,
1485                         fee_proportional_millionths: 0,
1486                         excess_data: Vec::new()
1487                 });
1488
1489                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1490
1491                 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1492         }
1493
1494         #[test]
1495         fn simple_route_test() {
1496                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1497                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1498
1499                 // Simple route to 2 via 1
1500
1501                 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)) {
1502                         assert_eq!(err, "Cannot send a payment of 0 msat");
1503                 } else { panic!(); }
1504
1505                 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();
1506                 assert_eq!(route.paths[0].len(), 2);
1507
1508                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1509                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1510                 assert_eq!(route.paths[0][0].fee_msat, 100);
1511                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1512                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1513                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1514
1515                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1516                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1517                 assert_eq!(route.paths[0][1].fee_msat, 100);
1518                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1519                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1520                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1521         }
1522
1523         #[test]
1524         fn invalid_first_hop_test() {
1525                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1526                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1527
1528                 // Simple route to 2 via 1
1529
1530                 let our_chans = vec![channelmanager::ChannelDetails {
1531                         channel_id: [0; 32],
1532                         short_channel_id: Some(2),
1533                         remote_network_id: our_id,
1534                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1535                         channel_value_satoshis: 100000,
1536                         user_id: 0,
1537                         outbound_capacity_msat: 100000,
1538                         inbound_capacity_msat: 100000,
1539                         is_live: true,
1540                         counterparty_forwarding_info: None,
1541                 }];
1542
1543                 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)) {
1544                         assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1545                 } else { panic!(); }
1546
1547                 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();
1548                 assert_eq!(route.paths[0].len(), 2);
1549         }
1550
1551         #[test]
1552         fn htlc_minimum_test() {
1553                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1554                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1555
1556                 // Simple route to 2 via 1
1557
1558                 // Disable other paths
1559                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1560                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1561                         short_channel_id: 12,
1562                         timestamp: 2,
1563                         flags: 2, // to disable
1564                         cltv_expiry_delta: 0,
1565                         htlc_minimum_msat: 0,
1566                         htlc_maximum_msat: OptionalField::Absent,
1567                         fee_base_msat: 0,
1568                         fee_proportional_millionths: 0,
1569                         excess_data: Vec::new()
1570                 });
1571                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1572                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1573                         short_channel_id: 3,
1574                         timestamp: 2,
1575                         flags: 2, // to disable
1576                         cltv_expiry_delta: 0,
1577                         htlc_minimum_msat: 0,
1578                         htlc_maximum_msat: OptionalField::Absent,
1579                         fee_base_msat: 0,
1580                         fee_proportional_millionths: 0,
1581                         excess_data: Vec::new()
1582                 });
1583                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1584                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1585                         short_channel_id: 13,
1586                         timestamp: 2,
1587                         flags: 2, // to disable
1588                         cltv_expiry_delta: 0,
1589                         htlc_minimum_msat: 0,
1590                         htlc_maximum_msat: OptionalField::Absent,
1591                         fee_base_msat: 0,
1592                         fee_proportional_millionths: 0,
1593                         excess_data: Vec::new()
1594                 });
1595                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1596                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1597                         short_channel_id: 6,
1598                         timestamp: 2,
1599                         flags: 2, // to disable
1600                         cltv_expiry_delta: 0,
1601                         htlc_minimum_msat: 0,
1602                         htlc_maximum_msat: OptionalField::Absent,
1603                         fee_base_msat: 0,
1604                         fee_proportional_millionths: 0,
1605                         excess_data: Vec::new()
1606                 });
1607                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1608                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1609                         short_channel_id: 7,
1610                         timestamp: 2,
1611                         flags: 2, // to disable
1612                         cltv_expiry_delta: 0,
1613                         htlc_minimum_msat: 0,
1614                         htlc_maximum_msat: OptionalField::Absent,
1615                         fee_base_msat: 0,
1616                         fee_proportional_millionths: 0,
1617                         excess_data: Vec::new()
1618                 });
1619
1620                 // Check against amount_to_transfer_over_msat.
1621                 // Set minimal HTLC of 200_000_000 msat.
1622                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1623                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1624                         short_channel_id: 2,
1625                         timestamp: 3,
1626                         flags: 0,
1627                         cltv_expiry_delta: 0,
1628                         htlc_minimum_msat: 200_000_000,
1629                         htlc_maximum_msat: OptionalField::Absent,
1630                         fee_base_msat: 0,
1631                         fee_proportional_millionths: 0,
1632                         excess_data: Vec::new()
1633                 });
1634
1635                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1636                 // be used.
1637                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1638                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1639                         short_channel_id: 4,
1640                         timestamp: 3,
1641                         flags: 0,
1642                         cltv_expiry_delta: 0,
1643                         htlc_minimum_msat: 0,
1644                         htlc_maximum_msat: OptionalField::Present(199_999_999),
1645                         fee_base_msat: 0,
1646                         fee_proportional_millionths: 0,
1647                         excess_data: Vec::new()
1648                 });
1649
1650                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1651                 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)) {
1652                         assert_eq!(err, "Failed to find a path to the given destination");
1653                 } else { panic!(); }
1654
1655                 // Lift the restriction on the first hop.
1656                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1657                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1658                         short_channel_id: 2,
1659                         timestamp: 4,
1660                         flags: 0,
1661                         cltv_expiry_delta: 0,
1662                         htlc_minimum_msat: 0,
1663                         htlc_maximum_msat: OptionalField::Absent,
1664                         fee_base_msat: 0,
1665                         fee_proportional_millionths: 0,
1666                         excess_data: Vec::new()
1667                 });
1668
1669                 // A payment above the minimum should pass
1670                 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();
1671                 assert_eq!(route.paths[0].len(), 2);
1672         }
1673
1674         #[test]
1675         fn htlc_minimum_overpay_test() {
1676                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1677                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1678
1679                 // A route to node#2 via two paths.
1680                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1681                 // Thus, they can't send 60 without overpaying.
1682                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1683                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1684                         short_channel_id: 2,
1685                         timestamp: 2,
1686                         flags: 0,
1687                         cltv_expiry_delta: 0,
1688                         htlc_minimum_msat: 35_000,
1689                         htlc_maximum_msat: OptionalField::Present(40_000),
1690                         fee_base_msat: 0,
1691                         fee_proportional_millionths: 0,
1692                         excess_data: Vec::new()
1693                 });
1694                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1695                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1696                         short_channel_id: 12,
1697                         timestamp: 3,
1698                         flags: 0,
1699                         cltv_expiry_delta: 0,
1700                         htlc_minimum_msat: 35_000,
1701                         htlc_maximum_msat: OptionalField::Present(40_000),
1702                         fee_base_msat: 0,
1703                         fee_proportional_millionths: 0,
1704                         excess_data: Vec::new()
1705                 });
1706
1707                 // Make 0 fee.
1708                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1709                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1710                         short_channel_id: 13,
1711                         timestamp: 2,
1712                         flags: 0,
1713                         cltv_expiry_delta: 0,
1714                         htlc_minimum_msat: 0,
1715                         htlc_maximum_msat: OptionalField::Absent,
1716                         fee_base_msat: 0,
1717                         fee_proportional_millionths: 0,
1718                         excess_data: Vec::new()
1719                 });
1720                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1721                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1722                         short_channel_id: 4,
1723                         timestamp: 2,
1724                         flags: 0,
1725                         cltv_expiry_delta: 0,
1726                         htlc_minimum_msat: 0,
1727                         htlc_maximum_msat: OptionalField::Absent,
1728                         fee_base_msat: 0,
1729                         fee_proportional_millionths: 0,
1730                         excess_data: Vec::new()
1731                 });
1732
1733                 // Disable other paths
1734                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1735                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1736                         short_channel_id: 1,
1737                         timestamp: 3,
1738                         flags: 2, // to disable
1739                         cltv_expiry_delta: 0,
1740                         htlc_minimum_msat: 0,
1741                         htlc_maximum_msat: OptionalField::Absent,
1742                         fee_base_msat: 0,
1743                         fee_proportional_millionths: 0,
1744                         excess_data: Vec::new()
1745                 });
1746
1747                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1748                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1749                 // Overpay fees to hit htlc_minimum_msat.
1750                 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1751                 // TODO: this could be better balanced to overpay 10k and not 15k.
1752                 assert_eq!(overpaid_fees, 15_000);
1753
1754                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1755                 // while taking even more fee to match htlc_minimum_msat.
1756                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1757                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1758                         short_channel_id: 12,
1759                         timestamp: 4,
1760                         flags: 0,
1761                         cltv_expiry_delta: 0,
1762                         htlc_minimum_msat: 65_000,
1763                         htlc_maximum_msat: OptionalField::Present(80_000),
1764                         fee_base_msat: 0,
1765                         fee_proportional_millionths: 0,
1766                         excess_data: Vec::new()
1767                 });
1768                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1769                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1770                         short_channel_id: 2,
1771                         timestamp: 3,
1772                         flags: 0,
1773                         cltv_expiry_delta: 0,
1774                         htlc_minimum_msat: 0,
1775                         htlc_maximum_msat: OptionalField::Absent,
1776                         fee_base_msat: 0,
1777                         fee_proportional_millionths: 0,
1778                         excess_data: Vec::new()
1779                 });
1780                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1781                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1782                         short_channel_id: 4,
1783                         timestamp: 4,
1784                         flags: 0,
1785                         cltv_expiry_delta: 0,
1786                         htlc_minimum_msat: 0,
1787                         htlc_maximum_msat: OptionalField::Absent,
1788                         fee_base_msat: 0,
1789                         fee_proportional_millionths: 100_000,
1790                         excess_data: Vec::new()
1791                 });
1792
1793                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1794                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1795                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1796                 assert_eq!(route.paths.len(), 1);
1797                 assert_eq!(route.paths[0][0].short_channel_id, 12);
1798                 let fees = route.paths[0][0].fee_msat;
1799                 assert_eq!(fees, 5_000);
1800
1801                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1802                         Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1803                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1804                 // the other channel.
1805                 assert_eq!(route.paths.len(), 1);
1806                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1807                 let fees = route.paths[0][0].fee_msat;
1808                 assert_eq!(fees, 5_000);
1809         }
1810
1811         #[test]
1812         fn disable_channels_test() {
1813                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1814                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1815
1816                 // // Disable channels 4 and 12 by flags=2
1817                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1818                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1819                         short_channel_id: 4,
1820                         timestamp: 2,
1821                         flags: 2, // to disable
1822                         cltv_expiry_delta: 0,
1823                         htlc_minimum_msat: 0,
1824                         htlc_maximum_msat: OptionalField::Absent,
1825                         fee_base_msat: 0,
1826                         fee_proportional_millionths: 0,
1827                         excess_data: Vec::new()
1828                 });
1829                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1830                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1831                         short_channel_id: 12,
1832                         timestamp: 2,
1833                         flags: 2, // to disable
1834                         cltv_expiry_delta: 0,
1835                         htlc_minimum_msat: 0,
1836                         htlc_maximum_msat: OptionalField::Absent,
1837                         fee_base_msat: 0,
1838                         fee_proportional_millionths: 0,
1839                         excess_data: Vec::new()
1840                 });
1841
1842                 // If all the channels require some features we don't understand, route should fail
1843                 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)) {
1844                         assert_eq!(err, "Failed to find a path to the given destination");
1845                 } else { panic!(); }
1846
1847                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1848                 let our_chans = vec![channelmanager::ChannelDetails {
1849                         channel_id: [0; 32],
1850                         short_channel_id: Some(42),
1851                         remote_network_id: nodes[7].clone(),
1852                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1853                         channel_value_satoshis: 0,
1854                         user_id: 0,
1855                         outbound_capacity_msat: 250_000_000,
1856                         inbound_capacity_msat: 0,
1857                         is_live: true,
1858                         counterparty_forwarding_info: None,
1859                 }];
1860                 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();
1861                 assert_eq!(route.paths[0].len(), 2);
1862
1863                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1864                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1865                 assert_eq!(route.paths[0][0].fee_msat, 200);
1866                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1867                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1868                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1869
1870                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1871                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1872                 assert_eq!(route.paths[0][1].fee_msat, 100);
1873                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1874                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1875                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1876         }
1877
1878         #[test]
1879         fn disable_node_test() {
1880                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1881                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1882
1883                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1884                 let mut unknown_features = NodeFeatures::known();
1885                 unknown_features.set_required_unknown_bits();
1886                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1887                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1888                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1889
1890                 // If all nodes require some features we don't understand, route should fail
1891                 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)) {
1892                         assert_eq!(err, "Failed to find a path to the given destination");
1893                 } else { panic!(); }
1894
1895                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1896                 let our_chans = vec![channelmanager::ChannelDetails {
1897                         channel_id: [0; 32],
1898                         short_channel_id: Some(42),
1899                         remote_network_id: nodes[7].clone(),
1900                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1901                         channel_value_satoshis: 0,
1902                         user_id: 0,
1903                         outbound_capacity_msat: 250_000_000,
1904                         inbound_capacity_msat: 0,
1905                         is_live: true,
1906                         counterparty_forwarding_info: None,
1907                 }];
1908                 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();
1909                 assert_eq!(route.paths[0].len(), 2);
1910
1911                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1912                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1913                 assert_eq!(route.paths[0][0].fee_msat, 200);
1914                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1915                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1916                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1917
1918                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1919                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1920                 assert_eq!(route.paths[0][1].fee_msat, 100);
1921                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1922                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1923                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1924
1925                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1926                 // naively) assume that the user checked the feature bits on the invoice, which override
1927                 // the node_announcement.
1928         }
1929
1930         #[test]
1931         fn our_chans_test() {
1932                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1933                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1934
1935                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1936                 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();
1937                 assert_eq!(route.paths[0].len(), 3);
1938
1939                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1940                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1941                 assert_eq!(route.paths[0][0].fee_msat, 200);
1942                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1943                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1944                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1945
1946                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1947                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1948                 assert_eq!(route.paths[0][1].fee_msat, 100);
1949                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1950                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1951                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1952
1953                 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1954                 assert_eq!(route.paths[0][2].short_channel_id, 3);
1955                 assert_eq!(route.paths[0][2].fee_msat, 100);
1956                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1957                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1958                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1959
1960                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1961                 let our_chans = vec![channelmanager::ChannelDetails {
1962                         channel_id: [0; 32],
1963                         short_channel_id: Some(42),
1964                         remote_network_id: nodes[7].clone(),
1965                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1966                         channel_value_satoshis: 0,
1967                         user_id: 0,
1968                         outbound_capacity_msat: 250_000_000,
1969                         inbound_capacity_msat: 0,
1970                         is_live: true,
1971                         counterparty_forwarding_info: None,
1972                 }];
1973                 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();
1974                 assert_eq!(route.paths[0].len(), 2);
1975
1976                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1977                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1978                 assert_eq!(route.paths[0][0].fee_msat, 200);
1979                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1980                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1981                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1982
1983                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1984                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1985                 assert_eq!(route.paths[0][1].fee_msat, 100);
1986                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1987                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1988                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1989         }
1990
1991         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1992                 let zero_fees = RoutingFees {
1993                         base_msat: 0,
1994                         proportional_millionths: 0,
1995                 };
1996                 vec!(RouteHint {
1997                         src_node_id: nodes[3].clone(),
1998                         short_channel_id: 8,
1999                         fees: zero_fees,
2000                         cltv_expiry_delta: (8 << 8) | 1,
2001                         htlc_minimum_msat: None,
2002                         htlc_maximum_msat: None,
2003                 }, RouteHint {
2004                         src_node_id: nodes[4].clone(),
2005                         short_channel_id: 9,
2006                         fees: RoutingFees {
2007                                 base_msat: 1001,
2008                                 proportional_millionths: 0,
2009                         },
2010                         cltv_expiry_delta: (9 << 8) | 1,
2011                         htlc_minimum_msat: None,
2012                         htlc_maximum_msat: None,
2013                 }, RouteHint {
2014                         src_node_id: nodes[5].clone(),
2015                         short_channel_id: 10,
2016                         fees: zero_fees,
2017                         cltv_expiry_delta: (10 << 8) | 1,
2018                         htlc_minimum_msat: None,
2019                         htlc_maximum_msat: None,
2020                 })
2021         }
2022
2023         #[test]
2024         fn last_hops_test() {
2025                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2026                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2027
2028                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2029
2030                 // First check that lst hop can't have its source as the payee.
2031                 let invalid_last_hop = RouteHint {
2032                         src_node_id: nodes[6],
2033                         short_channel_id: 8,
2034                         fees: RoutingFees {
2035                                 base_msat: 1000,
2036                                 proportional_millionths: 0,
2037                         },
2038                         cltv_expiry_delta: (8 << 8) | 1,
2039                         htlc_minimum_msat: None,
2040                         htlc_maximum_msat: None,
2041                 };
2042
2043                 let mut invalid_last_hops = last_hops(&nodes);
2044                 invalid_last_hops.push(invalid_last_hop);
2045                 {
2046                         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)) {
2047                                 assert_eq!(err, "Last hop cannot have a payee as a source.");
2048                         } else { panic!(); }
2049                 }
2050
2051                 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();
2052                 assert_eq!(route.paths[0].len(), 5);
2053
2054                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2055                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2056                 assert_eq!(route.paths[0][0].fee_msat, 100);
2057                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2058                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2059                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2060
2061                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2062                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2063                 assert_eq!(route.paths[0][1].fee_msat, 0);
2064                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2065                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2066                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2067
2068                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2069                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2070                 assert_eq!(route.paths[0][2].fee_msat, 0);
2071                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2072                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2073                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2074
2075                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2076                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2077                 assert_eq!(route.paths[0][3].fee_msat, 0);
2078                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2079                 // If we have a peer in the node map, we'll use their features here since we don't have
2080                 // a way of figuring out their features from the invoice:
2081                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2082                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2083
2084                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2085                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2086                 assert_eq!(route.paths[0][4].fee_msat, 100);
2087                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2088                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2089                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2090         }
2091
2092         #[test]
2093         fn our_chans_last_hop_connect_test() {
2094                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2095                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2096
2097                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2098                 let our_chans = vec![channelmanager::ChannelDetails {
2099                         channel_id: [0; 32],
2100                         short_channel_id: Some(42),
2101                         remote_network_id: nodes[3].clone(),
2102                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2103                         channel_value_satoshis: 0,
2104                         user_id: 0,
2105                         outbound_capacity_msat: 250_000_000,
2106                         inbound_capacity_msat: 0,
2107                         is_live: true,
2108                         counterparty_forwarding_info: None,
2109                 }];
2110                 let mut last_hops = last_hops(&nodes);
2111                 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();
2112                 assert_eq!(route.paths[0].len(), 2);
2113
2114                 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2115                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2116                 assert_eq!(route.paths[0][0].fee_msat, 0);
2117                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2118                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2119                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2120
2121                 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2122                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2123                 assert_eq!(route.paths[0][1].fee_msat, 100);
2124                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2125                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2126                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2127
2128                 last_hops[0].fees.base_msat = 1000;
2129
2130                 // Revert to via 6 as the fee on 8 goes up
2131                 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();
2132                 assert_eq!(route.paths[0].len(), 4);
2133
2134                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2135                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2136                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2137                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2138                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2139                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2140
2141                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2142                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2143                 assert_eq!(route.paths[0][1].fee_msat, 100);
2144                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2145                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2146                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2147
2148                 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2149                 assert_eq!(route.paths[0][2].short_channel_id, 7);
2150                 assert_eq!(route.paths[0][2].fee_msat, 0);
2151                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2152                 // If we have a peer in the node map, we'll use their features here since we don't have
2153                 // a way of figuring out their features from the invoice:
2154                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2155                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2156
2157                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2158                 assert_eq!(route.paths[0][3].short_channel_id, 10);
2159                 assert_eq!(route.paths[0][3].fee_msat, 100);
2160                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2161                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2162                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2163
2164                 // ...but still use 8 for larger payments as 6 has a variable feerate
2165                 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();
2166                 assert_eq!(route.paths[0].len(), 5);
2167
2168                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2169                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2170                 assert_eq!(route.paths[0][0].fee_msat, 3000);
2171                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2172                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2173                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2174
2175                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2176                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2177                 assert_eq!(route.paths[0][1].fee_msat, 0);
2178                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2179                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2180                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2181
2182                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2183                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2184                 assert_eq!(route.paths[0][2].fee_msat, 0);
2185                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2186                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2187                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2188
2189                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2190                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2191                 assert_eq!(route.paths[0][3].fee_msat, 1000);
2192                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2193                 // If we have a peer in the node map, we'll use their features here since we don't have
2194                 // a way of figuring out their features from the invoice:
2195                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2196                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2197
2198                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2199                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2200                 assert_eq!(route.paths[0][4].fee_msat, 2000);
2201                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2202                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2203                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2204         }
2205
2206         #[test]
2207         fn unannounced_path_test() {
2208                 // We should be able to send a payment to a destination without any help of a routing graph
2209                 // if we have a channel with a common counterparty that appears in the first and last hop
2210                 // hints.
2211                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2212                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2213                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2214
2215                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2216                 let last_hops = vec![RouteHint {
2217                         src_node_id: middle_node_id,
2218                         short_channel_id: 8,
2219                         fees: RoutingFees {
2220                                 base_msat: 1000,
2221                                 proportional_millionths: 0,
2222                         },
2223                         cltv_expiry_delta: (8 << 8) | 1,
2224                         htlc_minimum_msat: None,
2225                         htlc_maximum_msat: None,
2226                 }];
2227                 let our_chans = vec![channelmanager::ChannelDetails {
2228                         channel_id: [0; 32],
2229                         short_channel_id: Some(42),
2230                         remote_network_id: middle_node_id,
2231                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2232                         channel_value_satoshis: 100000,
2233                         user_id: 0,
2234                         outbound_capacity_msat: 100000,
2235                         inbound_capacity_msat: 100000,
2236                         is_live: true,
2237                         counterparty_forwarding_info: None,
2238                 }];
2239                 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();
2240
2241                 assert_eq!(route.paths[0].len(), 2);
2242
2243                 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2244                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2245                 assert_eq!(route.paths[0][0].fee_msat, 1000);
2246                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2247                 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2248                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2249
2250                 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2251                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2252                 assert_eq!(route.paths[0][1].fee_msat, 100);
2253                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2254                 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2255                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2256         }
2257
2258         #[test]
2259         fn available_amount_while_routing_test() {
2260                 // Tests whether we choose the correct available channel amount while routing.
2261
2262                 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2263                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2264
2265                 // We will use a simple single-path route from
2266                 // our node to node2 via node0: channels {1, 3}.
2267
2268                 // First disable all other paths.
2269                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2270                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2271                         short_channel_id: 2,
2272                         timestamp: 2,
2273                         flags: 2,
2274                         cltv_expiry_delta: 0,
2275                         htlc_minimum_msat: 0,
2276                         htlc_maximum_msat: OptionalField::Present(100_000),
2277                         fee_base_msat: 0,
2278                         fee_proportional_millionths: 0,
2279                         excess_data: Vec::new()
2280                 });
2281                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2282                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2283                         short_channel_id: 12,
2284                         timestamp: 2,
2285                         flags: 2,
2286                         cltv_expiry_delta: 0,
2287                         htlc_minimum_msat: 0,
2288                         htlc_maximum_msat: OptionalField::Present(100_000),
2289                         fee_base_msat: 0,
2290                         fee_proportional_millionths: 0,
2291                         excess_data: Vec::new()
2292                 });
2293
2294                 // Make the first channel (#1) very permissive,
2295                 // and we will be testing all limits on the second channel.
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: 1,
2299                         timestamp: 2,
2300                         flags: 0,
2301                         cltv_expiry_delta: 0,
2302                         htlc_minimum_msat: 0,
2303                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2304                         fee_base_msat: 0,
2305                         fee_proportional_millionths: 0,
2306                         excess_data: Vec::new()
2307                 });
2308
2309                 // First, let's see if routing works if we have absolutely no idea about the available amount.
2310                 // In this case, it should be set to 250_000 sats.
2311                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2312                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2313                         short_channel_id: 3,
2314                         timestamp: 2,
2315                         flags: 0,
2316                         cltv_expiry_delta: 0,
2317                         htlc_minimum_msat: 0,
2318                         htlc_maximum_msat: OptionalField::Absent,
2319                         fee_base_msat: 0,
2320                         fee_proportional_millionths: 0,
2321                         excess_data: Vec::new()
2322                 });
2323
2324                 {
2325                         // Attempt to route more than available results in a failure.
2326                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2327                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2328                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2329                         } else { panic!(); }
2330                 }
2331
2332                 {
2333                         // Now, attempt to route an exact amount we have should be fine.
2334                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2335                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2336                         assert_eq!(route.paths.len(), 1);
2337                         let path = route.paths.last().unwrap();
2338                         assert_eq!(path.len(), 2);
2339                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2340                         assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2341                 }
2342
2343                 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2344                 // Disable channel #1 and use another first hop.
2345                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2346                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2347                         short_channel_id: 1,
2348                         timestamp: 3,
2349                         flags: 2,
2350                         cltv_expiry_delta: 0,
2351                         htlc_minimum_msat: 0,
2352                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2353                         fee_base_msat: 0,
2354                         fee_proportional_millionths: 0,
2355                         excess_data: Vec::new()
2356                 });
2357
2358                 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2359                 let our_chans = vec![channelmanager::ChannelDetails {
2360                         channel_id: [0; 32],
2361                         short_channel_id: Some(42),
2362                         remote_network_id: nodes[0].clone(),
2363                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2364                         channel_value_satoshis: 0,
2365                         user_id: 0,
2366                         outbound_capacity_msat: 200_000_000,
2367                         inbound_capacity_msat: 0,
2368                         is_live: true,
2369                         counterparty_forwarding_info: None,
2370                 }];
2371
2372                 {
2373                         // Attempt to route more than available results in a failure.
2374                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2375                                         Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2376                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2377                         } else { panic!(); }
2378                 }
2379
2380                 {
2381                         // Now, attempt to route an exact amount we have should be fine.
2382                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2383                                 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2384                         assert_eq!(route.paths.len(), 1);
2385                         let path = route.paths.last().unwrap();
2386                         assert_eq!(path.len(), 2);
2387                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2388                         assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2389                 }
2390
2391                 // Enable channel #1 back.
2392                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2393                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2394                         short_channel_id: 1,
2395                         timestamp: 4,
2396                         flags: 0,
2397                         cltv_expiry_delta: 0,
2398                         htlc_minimum_msat: 0,
2399                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2400                         fee_base_msat: 0,
2401                         fee_proportional_millionths: 0,
2402                         excess_data: Vec::new()
2403                 });
2404
2405
2406                 // Now let's see if routing works if we know only htlc_maximum_msat.
2407                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2408                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2409                         short_channel_id: 3,
2410                         timestamp: 3,
2411                         flags: 0,
2412                         cltv_expiry_delta: 0,
2413                         htlc_minimum_msat: 0,
2414                         htlc_maximum_msat: OptionalField::Present(15_000),
2415                         fee_base_msat: 0,
2416                         fee_proportional_millionths: 0,
2417                         excess_data: Vec::new()
2418                 });
2419
2420                 {
2421                         // Attempt to route more than available results in a failure.
2422                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2423                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2424                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2425                         } else { panic!(); }
2426                 }
2427
2428                 {
2429                         // Now, attempt to route an exact amount we have should be fine.
2430                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2431                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2432                         assert_eq!(route.paths.len(), 1);
2433                         let path = route.paths.last().unwrap();
2434                         assert_eq!(path.len(), 2);
2435                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2436                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2437                 }
2438
2439                 // Now let's see if routing works if we know only capacity from the UTXO.
2440
2441                 // We can't change UTXO capacity on the fly, so we'll disable
2442                 // the existing channel and add another one with the capacity we need.
2443                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2444                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2445                         short_channel_id: 3,
2446                         timestamp: 4,
2447                         flags: 2,
2448                         cltv_expiry_delta: 0,
2449                         htlc_minimum_msat: 0,
2450                         htlc_maximum_msat: OptionalField::Absent,
2451                         fee_base_msat: 0,
2452                         fee_proportional_millionths: 0,
2453                         excess_data: Vec::new()
2454                 });
2455
2456                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2457                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2458                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2459                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2460                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2461
2462                 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2463                 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2464
2465                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2466                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2467                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2468                         short_channel_id: 333,
2469                         timestamp: 1,
2470                         flags: 0,
2471                         cltv_expiry_delta: (3 << 8) | 1,
2472                         htlc_minimum_msat: 0,
2473                         htlc_maximum_msat: OptionalField::Absent,
2474                         fee_base_msat: 0,
2475                         fee_proportional_millionths: 0,
2476                         excess_data: Vec::new()
2477                 });
2478                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2479                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2480                         short_channel_id: 333,
2481                         timestamp: 1,
2482                         flags: 1,
2483                         cltv_expiry_delta: (3 << 8) | 2,
2484                         htlc_minimum_msat: 0,
2485                         htlc_maximum_msat: OptionalField::Absent,
2486                         fee_base_msat: 100,
2487                         fee_proportional_millionths: 0,
2488                         excess_data: Vec::new()
2489                 });
2490
2491                 {
2492                         // Attempt to route more than available results in a failure.
2493                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2494                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2495                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2496                         } else { panic!(); }
2497                 }
2498
2499                 {
2500                         // Now, attempt to route an exact amount we have should be fine.
2501                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2502                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2503                         assert_eq!(route.paths.len(), 1);
2504                         let path = route.paths.last().unwrap();
2505                         assert_eq!(path.len(), 2);
2506                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2507                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2508                 }
2509
2510                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2511                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2512                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2513                         short_channel_id: 333,
2514                         timestamp: 6,
2515                         flags: 0,
2516                         cltv_expiry_delta: 0,
2517                         htlc_minimum_msat: 0,
2518                         htlc_maximum_msat: OptionalField::Present(10_000),
2519                         fee_base_msat: 0,
2520                         fee_proportional_millionths: 0,
2521                         excess_data: Vec::new()
2522                 });
2523
2524                 {
2525                         // Attempt to route more than available results in a failure.
2526                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2527                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2528                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2529                         } else { panic!(); }
2530                 }
2531
2532                 {
2533                         // Now, attempt to route an exact amount we have should be fine.
2534                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2535                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2536                         assert_eq!(route.paths.len(), 1);
2537                         let path = route.paths.last().unwrap();
2538                         assert_eq!(path.len(), 2);
2539                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2540                         assert_eq!(path.last().unwrap().fee_msat, 10_000);
2541                 }
2542         }
2543
2544         #[test]
2545         fn available_liquidity_last_hop_test() {
2546                 // Check that available liquidity properly limits the path even when only
2547                 // one of the latter hops is limited.
2548                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2549                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2550
2551                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2552                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2553                 // Total capacity: 50 sats.
2554
2555                 // Disable other potential paths.
2556                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2557                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2558                         short_channel_id: 2,
2559                         timestamp: 2,
2560                         flags: 2,
2561                         cltv_expiry_delta: 0,
2562                         htlc_minimum_msat: 0,
2563                         htlc_maximum_msat: OptionalField::Present(100_000),
2564                         fee_base_msat: 0,
2565                         fee_proportional_millionths: 0,
2566                         excess_data: Vec::new()
2567                 });
2568                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2569                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2570                         short_channel_id: 7,
2571                         timestamp: 2,
2572                         flags: 2,
2573                         cltv_expiry_delta: 0,
2574                         htlc_minimum_msat: 0,
2575                         htlc_maximum_msat: OptionalField::Present(100_000),
2576                         fee_base_msat: 0,
2577                         fee_proportional_millionths: 0,
2578                         excess_data: Vec::new()
2579                 });
2580
2581                 // Limit capacities
2582
2583                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2584                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2585                         short_channel_id: 12,
2586                         timestamp: 2,
2587                         flags: 0,
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                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2596                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2597                         short_channel_id: 13,
2598                         timestamp: 2,
2599                         flags: 0,
2600                         cltv_expiry_delta: 0,
2601                         htlc_minimum_msat: 0,
2602                         htlc_maximum_msat: OptionalField::Present(100_000),
2603                         fee_base_msat: 0,
2604                         fee_proportional_millionths: 0,
2605                         excess_data: Vec::new()
2606                 });
2607
2608                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2609                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2610                         short_channel_id: 6,
2611                         timestamp: 2,
2612                         flags: 0,
2613                         cltv_expiry_delta: 0,
2614                         htlc_minimum_msat: 0,
2615                         htlc_maximum_msat: OptionalField::Present(50_000),
2616                         fee_base_msat: 0,
2617                         fee_proportional_millionths: 0,
2618                         excess_data: Vec::new()
2619                 });
2620                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2621                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2622                         short_channel_id: 11,
2623                         timestamp: 2,
2624                         flags: 0,
2625                         cltv_expiry_delta: 0,
2626                         htlc_minimum_msat: 0,
2627                         htlc_maximum_msat: OptionalField::Present(100_000),
2628                         fee_base_msat: 0,
2629                         fee_proportional_millionths: 0,
2630                         excess_data: Vec::new()
2631                 });
2632                 {
2633                         // Attempt to route more than available results in a failure.
2634                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2635                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2636                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2637                         } else { panic!(); }
2638                 }
2639
2640                 {
2641                         // Now, attempt to route 49 sats (just a bit below the capacity).
2642                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2643                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2644                         assert_eq!(route.paths.len(), 1);
2645                         let mut total_amount_paid_msat = 0;
2646                         for path in &route.paths {
2647                                 assert_eq!(path.len(), 4);
2648                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2649                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2650                         }
2651                         assert_eq!(total_amount_paid_msat, 49_000);
2652                 }
2653
2654                 {
2655                         // Attempt to route an exact amount is also fine
2656                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2657                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2658                         assert_eq!(route.paths.len(), 1);
2659                         let mut total_amount_paid_msat = 0;
2660                         for path in &route.paths {
2661                                 assert_eq!(path.len(), 4);
2662                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2663                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2664                         }
2665                         assert_eq!(total_amount_paid_msat, 50_000);
2666                 }
2667         }
2668
2669         #[test]
2670         fn ignore_fee_first_hop_test() {
2671                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2672                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2673
2674                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2675                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2676                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2677                         short_channel_id: 1,
2678                         timestamp: 2,
2679                         flags: 0,
2680                         cltv_expiry_delta: 0,
2681                         htlc_minimum_msat: 0,
2682                         htlc_maximum_msat: OptionalField::Present(100_000),
2683                         fee_base_msat: 1_000_000,
2684                         fee_proportional_millionths: 0,
2685                         excess_data: Vec::new()
2686                 });
2687                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2688                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2689                         short_channel_id: 3,
2690                         timestamp: 2,
2691                         flags: 0,
2692                         cltv_expiry_delta: 0,
2693                         htlc_minimum_msat: 0,
2694                         htlc_maximum_msat: OptionalField::Present(50_000),
2695                         fee_base_msat: 0,
2696                         fee_proportional_millionths: 0,
2697                         excess_data: Vec::new()
2698                 });
2699
2700                 {
2701                         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();
2702                         assert_eq!(route.paths.len(), 1);
2703                         let mut total_amount_paid_msat = 0;
2704                         for path in &route.paths {
2705                                 assert_eq!(path.len(), 2);
2706                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2707                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2708                         }
2709                         assert_eq!(total_amount_paid_msat, 50_000);
2710                 }
2711         }
2712
2713         #[test]
2714         fn simple_mpp_route_test() {
2715                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2716                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2717
2718                 // We need a route consisting of 3 paths:
2719                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2720                 // To achieve this, the amount being transferred should be around
2721                 // the total capacity of these 3 paths.
2722
2723                 // First, we set limits on these (previously unlimited) channels.
2724                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2725
2726                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2727                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2728                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2729                         short_channel_id: 1,
2730                         timestamp: 2,
2731                         flags: 0,
2732                         cltv_expiry_delta: 0,
2733                         htlc_minimum_msat: 0,
2734                         htlc_maximum_msat: OptionalField::Present(100_000),
2735                         fee_base_msat: 0,
2736                         fee_proportional_millionths: 0,
2737                         excess_data: Vec::new()
2738                 });
2739                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2740                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2741                         short_channel_id: 3,
2742                         timestamp: 2,
2743                         flags: 0,
2744                         cltv_expiry_delta: 0,
2745                         htlc_minimum_msat: 0,
2746                         htlc_maximum_msat: OptionalField::Present(50_000),
2747                         fee_base_msat: 0,
2748                         fee_proportional_millionths: 0,
2749                         excess_data: Vec::new()
2750                 });
2751
2752                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2753                 // (total limit 60).
2754                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2755                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2756                         short_channel_id: 12,
2757                         timestamp: 2,
2758                         flags: 0,
2759                         cltv_expiry_delta: 0,
2760                         htlc_minimum_msat: 0,
2761                         htlc_maximum_msat: OptionalField::Present(60_000),
2762                         fee_base_msat: 0,
2763                         fee_proportional_millionths: 0,
2764                         excess_data: Vec::new()
2765                 });
2766                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2767                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2768                         short_channel_id: 13,
2769                         timestamp: 2,
2770                         flags: 0,
2771                         cltv_expiry_delta: 0,
2772                         htlc_minimum_msat: 0,
2773                         htlc_maximum_msat: OptionalField::Present(60_000),
2774                         fee_base_msat: 0,
2775                         fee_proportional_millionths: 0,
2776                         excess_data: Vec::new()
2777                 });
2778
2779                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2780                 // (total capacity 180 sats).
2781                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2782                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2783                         short_channel_id: 2,
2784                         timestamp: 2,
2785                         flags: 0,
2786                         cltv_expiry_delta: 0,
2787                         htlc_minimum_msat: 0,
2788                         htlc_maximum_msat: OptionalField::Present(200_000),
2789                         fee_base_msat: 0,
2790                         fee_proportional_millionths: 0,
2791                         excess_data: Vec::new()
2792                 });
2793                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2794                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2795                         short_channel_id: 4,
2796                         timestamp: 2,
2797                         flags: 0,
2798                         cltv_expiry_delta: 0,
2799                         htlc_minimum_msat: 0,
2800                         htlc_maximum_msat: OptionalField::Present(180_000),
2801                         fee_base_msat: 0,
2802                         fee_proportional_millionths: 0,
2803                         excess_data: Vec::new()
2804                 });
2805
2806                 {
2807                         // Attempt to route more than available results in a failure.
2808                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2809                                         &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2810                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2811                         } else { panic!(); }
2812                 }
2813
2814                 {
2815                         // Now, attempt to route 250 sats (just a bit below the capacity).
2816                         // Our algorithm should provide us with these 3 paths.
2817                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2818                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2819                         assert_eq!(route.paths.len(), 3);
2820                         let mut total_amount_paid_msat = 0;
2821                         for path in &route.paths {
2822                                 assert_eq!(path.len(), 2);
2823                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2824                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2825                         }
2826                         assert_eq!(total_amount_paid_msat, 250_000);
2827                 }
2828
2829                 {
2830                         // Attempt to route an exact amount is also fine
2831                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2832                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2833                         assert_eq!(route.paths.len(), 3);
2834                         let mut total_amount_paid_msat = 0;
2835                         for path in &route.paths {
2836                                 assert_eq!(path.len(), 2);
2837                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2838                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2839                         }
2840                         assert_eq!(total_amount_paid_msat, 290_000);
2841                 }
2842         }
2843
2844         #[test]
2845         fn long_mpp_route_test() {
2846                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2847                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2848
2849                 // We need a route consisting of 3 paths:
2850                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2851                 // Note that these paths overlap (channels 5, 12, 13).
2852                 // We will route 300 sats.
2853                 // Each path will have 100 sats capacity, those channels which
2854                 // are used twice will have 200 sats capacity.
2855
2856                 // Disable other potential paths.
2857                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2858                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2859                         short_channel_id: 2,
2860                         timestamp: 2,
2861                         flags: 2,
2862                         cltv_expiry_delta: 0,
2863                         htlc_minimum_msat: 0,
2864                         htlc_maximum_msat: OptionalField::Present(100_000),
2865                         fee_base_msat: 0,
2866                         fee_proportional_millionths: 0,
2867                         excess_data: Vec::new()
2868                 });
2869                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2870                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2871                         short_channel_id: 7,
2872                         timestamp: 2,
2873                         flags: 2,
2874                         cltv_expiry_delta: 0,
2875                         htlc_minimum_msat: 0,
2876                         htlc_maximum_msat: OptionalField::Present(100_000),
2877                         fee_base_msat: 0,
2878                         fee_proportional_millionths: 0,
2879                         excess_data: Vec::new()
2880                 });
2881
2882                 // Path via {node0, node2} is channels {1, 3, 5}.
2883                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2884                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2885                         short_channel_id: 1,
2886                         timestamp: 2,
2887                         flags: 0,
2888                         cltv_expiry_delta: 0,
2889                         htlc_minimum_msat: 0,
2890                         htlc_maximum_msat: OptionalField::Present(100_000),
2891                         fee_base_msat: 0,
2892                         fee_proportional_millionths: 0,
2893                         excess_data: Vec::new()
2894                 });
2895                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2896                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2897                         short_channel_id: 3,
2898                         timestamp: 2,
2899                         flags: 0,
2900                         cltv_expiry_delta: 0,
2901                         htlc_minimum_msat: 0,
2902                         htlc_maximum_msat: OptionalField::Present(100_000),
2903                         fee_base_msat: 0,
2904                         fee_proportional_millionths: 0,
2905                         excess_data: Vec::new()
2906                 });
2907
2908                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2909                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2910                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2911                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2912                         short_channel_id: 5,
2913                         timestamp: 2,
2914                         flags: 0,
2915                         cltv_expiry_delta: 0,
2916                         htlc_minimum_msat: 0,
2917                         htlc_maximum_msat: OptionalField::Present(200_000),
2918                         fee_base_msat: 0,
2919                         fee_proportional_millionths: 0,
2920                         excess_data: Vec::new()
2921                 });
2922
2923                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2924                 // Add 100 sats to the capacities of {12, 13}, because these channels
2925                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2926                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2927                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2928                         short_channel_id: 12,
2929                         timestamp: 2,
2930                         flags: 0,
2931                         cltv_expiry_delta: 0,
2932                         htlc_minimum_msat: 0,
2933                         htlc_maximum_msat: OptionalField::Present(200_000),
2934                         fee_base_msat: 0,
2935                         fee_proportional_millionths: 0,
2936                         excess_data: Vec::new()
2937                 });
2938                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2939                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2940                         short_channel_id: 13,
2941                         timestamp: 2,
2942                         flags: 0,
2943                         cltv_expiry_delta: 0,
2944                         htlc_minimum_msat: 0,
2945                         htlc_maximum_msat: OptionalField::Present(200_000),
2946                         fee_base_msat: 0,
2947                         fee_proportional_millionths: 0,
2948                         excess_data: Vec::new()
2949                 });
2950
2951                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2952                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2953                         short_channel_id: 6,
2954                         timestamp: 2,
2955                         flags: 0,
2956                         cltv_expiry_delta: 0,
2957                         htlc_minimum_msat: 0,
2958                         htlc_maximum_msat: OptionalField::Present(100_000),
2959                         fee_base_msat: 0,
2960                         fee_proportional_millionths: 0,
2961                         excess_data: Vec::new()
2962                 });
2963                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2964                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2965                         short_channel_id: 11,
2966                         timestamp: 2,
2967                         flags: 0,
2968                         cltv_expiry_delta: 0,
2969                         htlc_minimum_msat: 0,
2970                         htlc_maximum_msat: OptionalField::Present(100_000),
2971                         fee_base_msat: 0,
2972                         fee_proportional_millionths: 0,
2973                         excess_data: Vec::new()
2974                 });
2975
2976                 // Path via {node7, node2} is channels {12, 13, 5}.
2977                 // We already limited them to 200 sats (they are used twice for 100 sats).
2978                 // Nothing to do here.
2979
2980                 {
2981                         // Attempt to route more than available results in a failure.
2982                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2983                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
2984                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2985                         } else { panic!(); }
2986                 }
2987
2988                 {
2989                         // Now, attempt to route 300 sats (exact amount we can route).
2990                         // Our algorithm should provide us with these 3 paths, 100 sats each.
2991                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2992                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
2993                         assert_eq!(route.paths.len(), 3);
2994
2995                         let mut total_amount_paid_msat = 0;
2996                         for path in &route.paths {
2997                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2998                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2999                         }
3000                         assert_eq!(total_amount_paid_msat, 300_000);
3001                 }
3002
3003         }
3004
3005         #[test]
3006         fn mpp_cheaper_route_test() {
3007                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3008                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3009
3010                 // This test checks that if we have two cheaper paths and one more expensive path,
3011                 // so that liquidity-wise any 2 of 3 combination is sufficient,
3012                 // two cheaper paths will be taken.
3013                 // These paths have equal available liquidity.
3014
3015                 // We need a combination of 3 paths:
3016                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3017                 // Note that these paths overlap (channels 5, 12, 13).
3018                 // Each path will have 100 sats capacity, those channels which
3019                 // are used twice will have 200 sats capacity.
3020
3021                 // Disable other potential paths.
3022                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3023                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3024                         short_channel_id: 2,
3025                         timestamp: 2,
3026                         flags: 2,
3027                         cltv_expiry_delta: 0,
3028                         htlc_minimum_msat: 0,
3029                         htlc_maximum_msat: OptionalField::Present(100_000),
3030                         fee_base_msat: 0,
3031                         fee_proportional_millionths: 0,
3032                         excess_data: Vec::new()
3033                 });
3034                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3035                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3036                         short_channel_id: 7,
3037                         timestamp: 2,
3038                         flags: 2,
3039                         cltv_expiry_delta: 0,
3040                         htlc_minimum_msat: 0,
3041                         htlc_maximum_msat: OptionalField::Present(100_000),
3042                         fee_base_msat: 0,
3043                         fee_proportional_millionths: 0,
3044                         excess_data: Vec::new()
3045                 });
3046
3047                 // Path via {node0, node2} is channels {1, 3, 5}.
3048                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3049                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3050                         short_channel_id: 1,
3051                         timestamp: 2,
3052                         flags: 0,
3053                         cltv_expiry_delta: 0,
3054                         htlc_minimum_msat: 0,
3055                         htlc_maximum_msat: OptionalField::Present(100_000),
3056                         fee_base_msat: 0,
3057                         fee_proportional_millionths: 0,
3058                         excess_data: Vec::new()
3059                 });
3060                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3061                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3062                         short_channel_id: 3,
3063                         timestamp: 2,
3064                         flags: 0,
3065                         cltv_expiry_delta: 0,
3066                         htlc_minimum_msat: 0,
3067                         htlc_maximum_msat: OptionalField::Present(100_000),
3068                         fee_base_msat: 0,
3069                         fee_proportional_millionths: 0,
3070                         excess_data: Vec::new()
3071                 });
3072
3073                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3074                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3075                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3076                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3077                         short_channel_id: 5,
3078                         timestamp: 2,
3079                         flags: 0,
3080                         cltv_expiry_delta: 0,
3081                         htlc_minimum_msat: 0,
3082                         htlc_maximum_msat: OptionalField::Present(200_000),
3083                         fee_base_msat: 0,
3084                         fee_proportional_millionths: 0,
3085                         excess_data: Vec::new()
3086                 });
3087
3088                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3089                 // Add 100 sats to the capacities of {12, 13}, because these channels
3090                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3091                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3092                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3093                         short_channel_id: 12,
3094                         timestamp: 2,
3095                         flags: 0,
3096                         cltv_expiry_delta: 0,
3097                         htlc_minimum_msat: 0,
3098                         htlc_maximum_msat: OptionalField::Present(200_000),
3099                         fee_base_msat: 0,
3100                         fee_proportional_millionths: 0,
3101                         excess_data: Vec::new()
3102                 });
3103                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3104                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3105                         short_channel_id: 13,
3106                         timestamp: 2,
3107                         flags: 0,
3108                         cltv_expiry_delta: 0,
3109                         htlc_minimum_msat: 0,
3110                         htlc_maximum_msat: OptionalField::Present(200_000),
3111                         fee_base_msat: 0,
3112                         fee_proportional_millionths: 0,
3113                         excess_data: Vec::new()
3114                 });
3115
3116                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3117                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3118                         short_channel_id: 6,
3119                         timestamp: 2,
3120                         flags: 0,
3121                         cltv_expiry_delta: 0,
3122                         htlc_minimum_msat: 0,
3123                         htlc_maximum_msat: OptionalField::Present(100_000),
3124                         fee_base_msat: 1_000,
3125                         fee_proportional_millionths: 0,
3126                         excess_data: Vec::new()
3127                 });
3128                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3129                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3130                         short_channel_id: 11,
3131                         timestamp: 2,
3132                         flags: 0,
3133                         cltv_expiry_delta: 0,
3134                         htlc_minimum_msat: 0,
3135                         htlc_maximum_msat: OptionalField::Present(100_000),
3136                         fee_base_msat: 0,
3137                         fee_proportional_millionths: 0,
3138                         excess_data: Vec::new()
3139                 });
3140
3141                 // Path via {node7, node2} is channels {12, 13, 5}.
3142                 // We already limited them to 200 sats (they are used twice for 100 sats).
3143                 // Nothing to do here.
3144
3145                 {
3146                         // Now, attempt to route 180 sats.
3147                         // Our algorithm should provide us with these 2 paths.
3148                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3149                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3150                         assert_eq!(route.paths.len(), 2);
3151
3152                         let mut total_value_transferred_msat = 0;
3153                         let mut total_paid_msat = 0;
3154                         for path in &route.paths {
3155                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3156                                 total_value_transferred_msat += path.last().unwrap().fee_msat;
3157                                 for hop in path {
3158                                         total_paid_msat += hop.fee_msat;
3159                                 }
3160                         }
3161                         // If we paid fee, this would be higher.
3162                         assert_eq!(total_value_transferred_msat, 180_000);
3163                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3164                         assert_eq!(total_fees_paid, 0);
3165                 }
3166         }
3167
3168         #[test]
3169         fn fees_on_mpp_route_test() {
3170                 // This test makes sure that MPP algorithm properly takes into account
3171                 // fees charged on the channels, by making the fees impactful:
3172                 // if the fee is not properly accounted for, the behavior is different.
3173                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3174                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3175
3176                 // We need a route consisting of 2 paths:
3177                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3178                 // We will route 200 sats, Each path will have 100 sats capacity.
3179
3180                 // This test is not particularly stable: e.g.,
3181                 // there's a way to route via {node0, node2, node4}.
3182                 // It works while pathfinding is deterministic, but can be broken otherwise.
3183                 // It's fine to ignore this concern for now.
3184
3185                 // Disable other potential paths.
3186                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3187                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3188                         short_channel_id: 2,
3189                         timestamp: 2,
3190                         flags: 2,
3191                         cltv_expiry_delta: 0,
3192                         htlc_minimum_msat: 0,
3193                         htlc_maximum_msat: OptionalField::Present(100_000),
3194                         fee_base_msat: 0,
3195                         fee_proportional_millionths: 0,
3196                         excess_data: Vec::new()
3197                 });
3198
3199                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3200                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3201                         short_channel_id: 7,
3202                         timestamp: 2,
3203                         flags: 2,
3204                         cltv_expiry_delta: 0,
3205                         htlc_minimum_msat: 0,
3206                         htlc_maximum_msat: OptionalField::Present(100_000),
3207                         fee_base_msat: 0,
3208                         fee_proportional_millionths: 0,
3209                         excess_data: Vec::new()
3210                 });
3211
3212                 // Path via {node0, node2} is channels {1, 3, 5}.
3213                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3214                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3215                         short_channel_id: 1,
3216                         timestamp: 2,
3217                         flags: 0,
3218                         cltv_expiry_delta: 0,
3219                         htlc_minimum_msat: 0,
3220                         htlc_maximum_msat: OptionalField::Present(100_000),
3221                         fee_base_msat: 0,
3222                         fee_proportional_millionths: 0,
3223                         excess_data: Vec::new()
3224                 });
3225                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3226                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3227                         short_channel_id: 3,
3228                         timestamp: 2,
3229                         flags: 0,
3230                         cltv_expiry_delta: 0,
3231                         htlc_minimum_msat: 0,
3232                         htlc_maximum_msat: OptionalField::Present(100_000),
3233                         fee_base_msat: 0,
3234                         fee_proportional_millionths: 0,
3235                         excess_data: Vec::new()
3236                 });
3237
3238                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3239                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3240                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3241                         short_channel_id: 5,
3242                         timestamp: 2,
3243                         flags: 0,
3244                         cltv_expiry_delta: 0,
3245                         htlc_minimum_msat: 0,
3246                         htlc_maximum_msat: OptionalField::Present(100_000),
3247                         fee_base_msat: 0,
3248                         fee_proportional_millionths: 0,
3249                         excess_data: Vec::new()
3250                 });
3251
3252                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3253                 // All channels should be 100 sats capacity. But for the fee experiment,
3254                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3255                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3256                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3257                 // so no matter how large are other channels,
3258                 // the whole path will be limited by 100 sats with just these 2 conditions:
3259                 // - channel 12 capacity is 250 sats
3260                 // - fee for channel 6 is 150 sats
3261                 // Let's test this by enforcing these 2 conditions and removing other limits.
3262                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3263                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3264                         short_channel_id: 12,
3265                         timestamp: 2,
3266                         flags: 0,
3267                         cltv_expiry_delta: 0,
3268                         htlc_minimum_msat: 0,
3269                         htlc_maximum_msat: OptionalField::Present(250_000),
3270                         fee_base_msat: 0,
3271                         fee_proportional_millionths: 0,
3272                         excess_data: Vec::new()
3273                 });
3274                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3275                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3276                         short_channel_id: 13,
3277                         timestamp: 2,
3278                         flags: 0,
3279                         cltv_expiry_delta: 0,
3280                         htlc_minimum_msat: 0,
3281                         htlc_maximum_msat: OptionalField::Absent,
3282                         fee_base_msat: 0,
3283                         fee_proportional_millionths: 0,
3284                         excess_data: Vec::new()
3285                 });
3286
3287                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3288                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3289                         short_channel_id: 6,
3290                         timestamp: 2,
3291                         flags: 0,
3292                         cltv_expiry_delta: 0,
3293                         htlc_minimum_msat: 0,
3294                         htlc_maximum_msat: OptionalField::Absent,
3295                         fee_base_msat: 150_000,
3296                         fee_proportional_millionths: 0,
3297                         excess_data: Vec::new()
3298                 });
3299                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3300                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3301                         short_channel_id: 11,
3302                         timestamp: 2,
3303                         flags: 0,
3304                         cltv_expiry_delta: 0,
3305                         htlc_minimum_msat: 0,
3306                         htlc_maximum_msat: OptionalField::Absent,
3307                         fee_base_msat: 0,
3308                         fee_proportional_millionths: 0,
3309                         excess_data: Vec::new()
3310                 });
3311
3312                 {
3313                         // Attempt to route more than available results in a failure.
3314                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3315                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3316                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3317                         } else { panic!(); }
3318                 }
3319
3320                 {
3321                         // Now, attempt to route 200 sats (exact amount we can route).
3322                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3323                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3324                         assert_eq!(route.paths.len(), 2);
3325
3326                         let mut total_amount_paid_msat = 0;
3327                         for path in &route.paths {
3328                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3329                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3330                         }
3331                         assert_eq!(total_amount_paid_msat, 200_000);
3332                 }
3333
3334         }
3335
3336         #[test]
3337         fn drop_lowest_channel_mpp_route_test() {
3338                 // This test checks that low-capacity channel is dropped when after
3339                 // path finding we realize that we found more capacity than we need.
3340                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3341                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3342
3343                 // We need a route consisting of 3 paths:
3344                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3345
3346                 // The first and the second paths should be sufficient, but the third should be
3347                 // cheaper, so that we select it but drop later.
3348
3349                 // First, we set limits on these (previously unlimited) channels.
3350                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3351
3352                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3353                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3354                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3355                         short_channel_id: 1,
3356                         timestamp: 2,
3357                         flags: 0,
3358                         cltv_expiry_delta: 0,
3359                         htlc_minimum_msat: 0,
3360                         htlc_maximum_msat: OptionalField::Present(100_000),
3361                         fee_base_msat: 0,
3362                         fee_proportional_millionths: 0,
3363                         excess_data: Vec::new()
3364                 });
3365                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3366                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3367                         short_channel_id: 3,
3368                         timestamp: 2,
3369                         flags: 0,
3370                         cltv_expiry_delta: 0,
3371                         htlc_minimum_msat: 0,
3372                         htlc_maximum_msat: OptionalField::Present(50_000),
3373                         fee_base_msat: 100,
3374                         fee_proportional_millionths: 0,
3375                         excess_data: Vec::new()
3376                 });
3377
3378                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3379                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3380                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3381                         short_channel_id: 12,
3382                         timestamp: 2,
3383                         flags: 0,
3384                         cltv_expiry_delta: 0,
3385                         htlc_minimum_msat: 0,
3386                         htlc_maximum_msat: OptionalField::Present(60_000),
3387                         fee_base_msat: 100,
3388                         fee_proportional_millionths: 0,
3389                         excess_data: Vec::new()
3390                 });
3391                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3392                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3393                         short_channel_id: 13,
3394                         timestamp: 2,
3395                         flags: 0,
3396                         cltv_expiry_delta: 0,
3397                         htlc_minimum_msat: 0,
3398                         htlc_maximum_msat: OptionalField::Present(60_000),
3399                         fee_base_msat: 0,
3400                         fee_proportional_millionths: 0,
3401                         excess_data: Vec::new()
3402                 });
3403
3404                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3405                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3406                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3407                         short_channel_id: 2,
3408                         timestamp: 2,
3409                         flags: 0,
3410                         cltv_expiry_delta: 0,
3411                         htlc_minimum_msat: 0,
3412                         htlc_maximum_msat: OptionalField::Present(20_000),
3413                         fee_base_msat: 0,
3414                         fee_proportional_millionths: 0,
3415                         excess_data: Vec::new()
3416                 });
3417                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3418                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3419                         short_channel_id: 4,
3420                         timestamp: 2,
3421                         flags: 0,
3422                         cltv_expiry_delta: 0,
3423                         htlc_minimum_msat: 0,
3424                         htlc_maximum_msat: OptionalField::Present(20_000),
3425                         fee_base_msat: 0,
3426                         fee_proportional_millionths: 0,
3427                         excess_data: Vec::new()
3428                 });
3429
3430                 {
3431                         // Attempt to route more than available results in a failure.
3432                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3433                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3434                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3435                         } else { panic!(); }
3436                 }
3437
3438                 {
3439                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3440                         // Our algorithm should provide us with these 3 paths.
3441                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3442                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3443                         assert_eq!(route.paths.len(), 3);
3444                         let mut total_amount_paid_msat = 0;
3445                         for path in &route.paths {
3446                                 assert_eq!(path.len(), 2);
3447                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3448                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3449                         }
3450                         assert_eq!(total_amount_paid_msat, 125_000);
3451                 }
3452
3453                 {
3454                         // Attempt to route without the last small cheap channel
3455                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3456                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3457                         assert_eq!(route.paths.len(), 2);
3458                         let mut total_amount_paid_msat = 0;
3459                         for path in &route.paths {
3460                                 assert_eq!(path.len(), 2);
3461                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3462                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3463                         }
3464                         assert_eq!(total_amount_paid_msat, 90_000);
3465                 }
3466         }
3467
3468         #[test]
3469         fn exact_fee_liquidity_limit() {
3470                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3471                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3472                 // we calculated fees on a higher value, resulting in us ignoring such paths.
3473                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3474                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3475
3476                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3477                 // send.
3478                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3479                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3480                         short_channel_id: 2,
3481                         timestamp: 2,
3482                         flags: 0,
3483                         cltv_expiry_delta: 0,
3484                         htlc_minimum_msat: 0,
3485                         htlc_maximum_msat: OptionalField::Present(85_000),
3486                         fee_base_msat: 0,
3487                         fee_proportional_millionths: 0,
3488                         excess_data: Vec::new()
3489                 });
3490
3491                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3492                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3493                         short_channel_id: 12,
3494                         timestamp: 2,
3495                         flags: 0,
3496                         cltv_expiry_delta: (4 << 8) | 1,
3497                         htlc_minimum_msat: 0,
3498                         htlc_maximum_msat: OptionalField::Present(270_000),
3499                         fee_base_msat: 0,
3500                         fee_proportional_millionths: 1000000,
3501                         excess_data: Vec::new()
3502                 });
3503
3504                 {
3505                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3506                         // 200% fee charged channel 13 in the 1-to-2 direction.
3507                         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();
3508                         assert_eq!(route.paths.len(), 1);
3509                         assert_eq!(route.paths[0].len(), 2);
3510
3511                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3512                         assert_eq!(route.paths[0][0].short_channel_id, 12);
3513                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3514                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3515                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3516                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3517
3518                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3519                         assert_eq!(route.paths[0][1].short_channel_id, 13);
3520                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
3521                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3522                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3523                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3524                 }
3525         }
3526
3527         #[test]
3528         fn htlc_max_reduction_below_min() {
3529                 // Test that if, while walking the graph, we reduce the value being sent to meet an
3530                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3531                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3532                 // resulting in us thinking there is no possible path, even if other paths exist.
3533                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3534                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3535
3536                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3537                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3538                 // then try to send 90_000.
3539                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3540                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3541                         short_channel_id: 2,
3542                         timestamp: 2,
3543                         flags: 0,
3544                         cltv_expiry_delta: 0,
3545                         htlc_minimum_msat: 0,
3546                         htlc_maximum_msat: OptionalField::Present(80_000),
3547                         fee_base_msat: 0,
3548                         fee_proportional_millionths: 0,
3549                         excess_data: Vec::new()
3550                 });
3551                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3552                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3553                         short_channel_id: 4,
3554                         timestamp: 2,
3555                         flags: 0,
3556                         cltv_expiry_delta: (4 << 8) | 1,
3557                         htlc_minimum_msat: 90_000,
3558                         htlc_maximum_msat: OptionalField::Absent,
3559                         fee_base_msat: 0,
3560                         fee_proportional_millionths: 0,
3561                         excess_data: Vec::new()
3562                 });
3563
3564                 {
3565                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3566                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3567                         // expensive) channels 12-13 path.
3568                         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();
3569                         assert_eq!(route.paths.len(), 1);
3570                         assert_eq!(route.paths[0].len(), 2);
3571
3572                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3573                         assert_eq!(route.paths[0][0].short_channel_id, 12);
3574                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3575                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3576                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3577                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3578
3579                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3580                         assert_eq!(route.paths[0][1].short_channel_id, 13);
3581                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
3582                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3583                         assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3584                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3585                 }
3586         }
3587 }
3588
3589 #[cfg(all(test, feature = "unstable"))]
3590 mod benches {
3591         use super::*;
3592         use util::logger::{Logger, Record};
3593
3594         use std::fs::File;
3595         use test::Bencher;
3596
3597         struct DummyLogger {}
3598         impl Logger for DummyLogger {
3599                 fn log(&self, _record: &Record) {}
3600         }
3601
3602         #[bench]
3603         fn generate_routes(bench: &mut Bencher) {
3604                 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");
3605                 let graph = NetworkGraph::read(&mut d).unwrap();
3606
3607                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3608                 let mut path_endpoints = Vec::new();
3609                 let mut seed: usize = 0xdeadbeef;
3610                 'load_endpoints: for _ in 0..100 {
3611                         loop {
3612                                 seed *= 0xdeadbeef;
3613                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3614                                 seed *= 0xdeadbeef;
3615                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3616                                 let amt = seed as u64 % 1_000_000;
3617                                 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3618                                         path_endpoints.push((src, dst, amt));
3619                                         continue 'load_endpoints;
3620                                 }
3621                         }
3622                 }
3623
3624                 // ...then benchmark finding paths between the nodes we learned.
3625                 let mut idx = 0;
3626                 bench.iter(|| {
3627                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3628                         assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3629                         idx += 1;
3630                 });
3631         }
3632
3633         #[bench]
3634         fn generate_mpp_routes(bench: &mut Bencher) {
3635                 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");
3636                 let graph = NetworkGraph::read(&mut d).unwrap();
3637
3638                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3639                 let mut path_endpoints = Vec::new();
3640                 let mut seed: usize = 0xdeadbeef;
3641                 'load_endpoints: for _ in 0..100 {
3642                         loop {
3643                                 seed *= 0xdeadbeef;
3644                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3645                                 seed *= 0xdeadbeef;
3646                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3647                                 let amt = seed as u64 % 1_000_000;
3648                                 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3649                                         path_endpoints.push((src, dst, amt));
3650                                         continue 'load_endpoints;
3651                                 }
3652                         }
3653                 }
3654
3655                 // ...then benchmark finding paths between the nodes we learned.
3656                 let mut idx = 0;
3657                 bench.iter(|| {
3658                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3659                         assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());
3660                         idx += 1;
3661                 });
3662         }
3663 }