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