9da2d981e8442feaba72e94cac58cdcd1e5cfcc0
[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                         to_self_reserve_satoshis: None,
1650                         to_remote_reserve_satoshis: 0,
1651                         confirmations_required: None,
1652                         spend_csv_on_our_commitment_funds: None,
1653                         is_outbound: true, is_funding_locked: true,
1654                         is_usable: true, is_public: true,
1655                         counterparty_forwarding_info: None,
1656                 }];
1657
1658                 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)) {
1659                         assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1660                 } else { panic!(); }
1661
1662                 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();
1663                 assert_eq!(route.paths[0].len(), 2);
1664         }
1665
1666         #[test]
1667         fn htlc_minimum_test() {
1668                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1669                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1670
1671                 // Simple route to 2 via 1
1672
1673                 // Disable other paths
1674                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1675                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1676                         short_channel_id: 12,
1677                         timestamp: 2,
1678                         flags: 2, // to disable
1679                         cltv_expiry_delta: 0,
1680                         htlc_minimum_msat: 0,
1681                         htlc_maximum_msat: OptionalField::Absent,
1682                         fee_base_msat: 0,
1683                         fee_proportional_millionths: 0,
1684                         excess_data: Vec::new()
1685                 });
1686                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1687                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1688                         short_channel_id: 3,
1689                         timestamp: 2,
1690                         flags: 2, // to disable
1691                         cltv_expiry_delta: 0,
1692                         htlc_minimum_msat: 0,
1693                         htlc_maximum_msat: OptionalField::Absent,
1694                         fee_base_msat: 0,
1695                         fee_proportional_millionths: 0,
1696                         excess_data: Vec::new()
1697                 });
1698                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1699                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1700                         short_channel_id: 13,
1701                         timestamp: 2,
1702                         flags: 2, // to disable
1703                         cltv_expiry_delta: 0,
1704                         htlc_minimum_msat: 0,
1705                         htlc_maximum_msat: OptionalField::Absent,
1706                         fee_base_msat: 0,
1707                         fee_proportional_millionths: 0,
1708                         excess_data: Vec::new()
1709                 });
1710                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1711                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1712                         short_channel_id: 6,
1713                         timestamp: 2,
1714                         flags: 2, // to disable
1715                         cltv_expiry_delta: 0,
1716                         htlc_minimum_msat: 0,
1717                         htlc_maximum_msat: OptionalField::Absent,
1718                         fee_base_msat: 0,
1719                         fee_proportional_millionths: 0,
1720                         excess_data: Vec::new()
1721                 });
1722                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1723                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1724                         short_channel_id: 7,
1725                         timestamp: 2,
1726                         flags: 2, // to disable
1727                         cltv_expiry_delta: 0,
1728                         htlc_minimum_msat: 0,
1729                         htlc_maximum_msat: OptionalField::Absent,
1730                         fee_base_msat: 0,
1731                         fee_proportional_millionths: 0,
1732                         excess_data: Vec::new()
1733                 });
1734
1735                 // Check against amount_to_transfer_over_msat.
1736                 // Set minimal HTLC of 200_000_000 msat.
1737                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1738                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1739                         short_channel_id: 2,
1740                         timestamp: 3,
1741                         flags: 0,
1742                         cltv_expiry_delta: 0,
1743                         htlc_minimum_msat: 200_000_000,
1744                         htlc_maximum_msat: OptionalField::Absent,
1745                         fee_base_msat: 0,
1746                         fee_proportional_millionths: 0,
1747                         excess_data: Vec::new()
1748                 });
1749
1750                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1751                 // be used.
1752                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1753                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1754                         short_channel_id: 4,
1755                         timestamp: 3,
1756                         flags: 0,
1757                         cltv_expiry_delta: 0,
1758                         htlc_minimum_msat: 0,
1759                         htlc_maximum_msat: OptionalField::Present(199_999_999),
1760                         fee_base_msat: 0,
1761                         fee_proportional_millionths: 0,
1762                         excess_data: Vec::new()
1763                 });
1764
1765                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1766                 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)) {
1767                         assert_eq!(err, "Failed to find a path to the given destination");
1768                 } else { panic!(); }
1769
1770                 // Lift the restriction on the first hop.
1771                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1772                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1773                         short_channel_id: 2,
1774                         timestamp: 4,
1775                         flags: 0,
1776                         cltv_expiry_delta: 0,
1777                         htlc_minimum_msat: 0,
1778                         htlc_maximum_msat: OptionalField::Absent,
1779                         fee_base_msat: 0,
1780                         fee_proportional_millionths: 0,
1781                         excess_data: Vec::new()
1782                 });
1783
1784                 // A payment above the minimum should pass
1785                 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();
1786                 assert_eq!(route.paths[0].len(), 2);
1787         }
1788
1789         #[test]
1790         fn htlc_minimum_overpay_test() {
1791                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1792                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1793
1794                 // A route to node#2 via two paths.
1795                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1796                 // Thus, they can't send 60 without overpaying.
1797                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1798                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1799                         short_channel_id: 2,
1800                         timestamp: 2,
1801                         flags: 0,
1802                         cltv_expiry_delta: 0,
1803                         htlc_minimum_msat: 35_000,
1804                         htlc_maximum_msat: OptionalField::Present(40_000),
1805                         fee_base_msat: 0,
1806                         fee_proportional_millionths: 0,
1807                         excess_data: Vec::new()
1808                 });
1809                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1810                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1811                         short_channel_id: 12,
1812                         timestamp: 3,
1813                         flags: 0,
1814                         cltv_expiry_delta: 0,
1815                         htlc_minimum_msat: 35_000,
1816                         htlc_maximum_msat: OptionalField::Present(40_000),
1817                         fee_base_msat: 0,
1818                         fee_proportional_millionths: 0,
1819                         excess_data: Vec::new()
1820                 });
1821
1822                 // Make 0 fee.
1823                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1824                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1825                         short_channel_id: 13,
1826                         timestamp: 2,
1827                         flags: 0,
1828                         cltv_expiry_delta: 0,
1829                         htlc_minimum_msat: 0,
1830                         htlc_maximum_msat: OptionalField::Absent,
1831                         fee_base_msat: 0,
1832                         fee_proportional_millionths: 0,
1833                         excess_data: Vec::new()
1834                 });
1835                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1836                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1837                         short_channel_id: 4,
1838                         timestamp: 2,
1839                         flags: 0,
1840                         cltv_expiry_delta: 0,
1841                         htlc_minimum_msat: 0,
1842                         htlc_maximum_msat: OptionalField::Absent,
1843                         fee_base_msat: 0,
1844                         fee_proportional_millionths: 0,
1845                         excess_data: Vec::new()
1846                 });
1847
1848                 // Disable other paths
1849                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1850                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1851                         short_channel_id: 1,
1852                         timestamp: 3,
1853                         flags: 2, // to disable
1854                         cltv_expiry_delta: 0,
1855                         htlc_minimum_msat: 0,
1856                         htlc_maximum_msat: OptionalField::Absent,
1857                         fee_base_msat: 0,
1858                         fee_proportional_millionths: 0,
1859                         excess_data: Vec::new()
1860                 });
1861
1862                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1863                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1864                 // Overpay fees to hit htlc_minimum_msat.
1865                 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1866                 // TODO: this could be better balanced to overpay 10k and not 15k.
1867                 assert_eq!(overpaid_fees, 15_000);
1868
1869                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1870                 // while taking even more fee to match htlc_minimum_msat.
1871                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1872                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1873                         short_channel_id: 12,
1874                         timestamp: 4,
1875                         flags: 0,
1876                         cltv_expiry_delta: 0,
1877                         htlc_minimum_msat: 65_000,
1878                         htlc_maximum_msat: OptionalField::Present(80_000),
1879                         fee_base_msat: 0,
1880                         fee_proportional_millionths: 0,
1881                         excess_data: Vec::new()
1882                 });
1883                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1884                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1885                         short_channel_id: 2,
1886                         timestamp: 3,
1887                         flags: 0,
1888                         cltv_expiry_delta: 0,
1889                         htlc_minimum_msat: 0,
1890                         htlc_maximum_msat: OptionalField::Absent,
1891                         fee_base_msat: 0,
1892                         fee_proportional_millionths: 0,
1893                         excess_data: Vec::new()
1894                 });
1895                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1896                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1897                         short_channel_id: 4,
1898                         timestamp: 4,
1899                         flags: 0,
1900                         cltv_expiry_delta: 0,
1901                         htlc_minimum_msat: 0,
1902                         htlc_maximum_msat: OptionalField::Absent,
1903                         fee_base_msat: 0,
1904                         fee_proportional_millionths: 100_000,
1905                         excess_data: Vec::new()
1906                 });
1907
1908                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1909                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1910                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1911                 assert_eq!(route.paths.len(), 1);
1912                 assert_eq!(route.paths[0][0].short_channel_id, 12);
1913                 let fees = route.paths[0][0].fee_msat;
1914                 assert_eq!(fees, 5_000);
1915
1916                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1917                         Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1918                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1919                 // the other channel.
1920                 assert_eq!(route.paths.len(), 1);
1921                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1922                 let fees = route.paths[0][0].fee_msat;
1923                 assert_eq!(fees, 5_000);
1924         }
1925
1926         #[test]
1927         fn disable_channels_test() {
1928                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1929                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1930
1931                 // // Disable channels 4 and 12 by flags=2
1932                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1933                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1934                         short_channel_id: 4,
1935                         timestamp: 2,
1936                         flags: 2, // to disable
1937                         cltv_expiry_delta: 0,
1938                         htlc_minimum_msat: 0,
1939                         htlc_maximum_msat: OptionalField::Absent,
1940                         fee_base_msat: 0,
1941                         fee_proportional_millionths: 0,
1942                         excess_data: Vec::new()
1943                 });
1944                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1945                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1946                         short_channel_id: 12,
1947                         timestamp: 2,
1948                         flags: 2, // to disable
1949                         cltv_expiry_delta: 0,
1950                         htlc_minimum_msat: 0,
1951                         htlc_maximum_msat: OptionalField::Absent,
1952                         fee_base_msat: 0,
1953                         fee_proportional_millionths: 0,
1954                         excess_data: Vec::new()
1955                 });
1956
1957                 // If all the channels require some features we don't understand, route should fail
1958                 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)) {
1959                         assert_eq!(err, "Failed to find a path to the given destination");
1960                 } else { panic!(); }
1961
1962                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1963                 let our_chans = vec![channelmanager::ChannelDetails {
1964                         channel_id: [0; 32],
1965                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1966                         short_channel_id: Some(42),
1967                         remote_network_id: nodes[7].clone(),
1968                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1969                         channel_value_satoshis: 0,
1970                         user_id: 0,
1971                         outbound_capacity_msat: 250_000_000,
1972                         inbound_capacity_msat: 0,
1973                         to_self_reserve_satoshis: None,
1974                         to_remote_reserve_satoshis: 0,
1975                         confirmations_required: None,
1976                         spend_csv_on_our_commitment_funds: None,
1977                         is_outbound: true, is_funding_locked: true,
1978                         is_usable: true, is_public: true,
1979                         counterparty_forwarding_info: None,
1980                 }];
1981                 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();
1982                 assert_eq!(route.paths[0].len(), 2);
1983
1984                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1985                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1986                 assert_eq!(route.paths[0][0].fee_msat, 200);
1987                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1988                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1989                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1990
1991                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1992                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1993                 assert_eq!(route.paths[0][1].fee_msat, 100);
1994                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1995                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1996                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1997         }
1998
1999         #[test]
2000         fn disable_node_test() {
2001                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2002                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2003
2004                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2005                 let mut unknown_features = NodeFeatures::known();
2006                 unknown_features.set_required_unknown_bits();
2007                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2008                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2009                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2010
2011                 // If all nodes require some features we don't understand, route should fail
2012                 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)) {
2013                         assert_eq!(err, "Failed to find a path to the given destination");
2014                 } else { panic!(); }
2015
2016                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2017                 let our_chans = vec![channelmanager::ChannelDetails {
2018                         channel_id: [0; 32],
2019                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2020                         short_channel_id: Some(42),
2021                         remote_network_id: nodes[7].clone(),
2022                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2023                         channel_value_satoshis: 0,
2024                         user_id: 0,
2025                         outbound_capacity_msat: 250_000_000,
2026                         inbound_capacity_msat: 0,
2027                         to_self_reserve_satoshis: None,
2028                         to_remote_reserve_satoshis: 0,
2029                         confirmations_required: None,
2030                         spend_csv_on_our_commitment_funds: None,
2031                         is_outbound: true, is_funding_locked: true,
2032                         is_usable: true, is_public: true,
2033                         counterparty_forwarding_info: None,
2034                 }];
2035                 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();
2036                 assert_eq!(route.paths[0].len(), 2);
2037
2038                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2039                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2040                 assert_eq!(route.paths[0][0].fee_msat, 200);
2041                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2042                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2043                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2044
2045                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2046                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2047                 assert_eq!(route.paths[0][1].fee_msat, 100);
2048                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2049                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2050                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2051
2052                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2053                 // naively) assume that the user checked the feature bits on the invoice, which override
2054                 // the node_announcement.
2055         }
2056
2057         #[test]
2058         fn our_chans_test() {
2059                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2060                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2061
2062                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2063                 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();
2064                 assert_eq!(route.paths[0].len(), 3);
2065
2066                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2067                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2068                 assert_eq!(route.paths[0][0].fee_msat, 200);
2069                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2070                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2071                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2072
2073                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2074                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2075                 assert_eq!(route.paths[0][1].fee_msat, 100);
2076                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2077                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2078                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2079
2080                 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2081                 assert_eq!(route.paths[0][2].short_channel_id, 3);
2082                 assert_eq!(route.paths[0][2].fee_msat, 100);
2083                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2084                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2085                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2086
2087                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2088                 let our_chans = vec![channelmanager::ChannelDetails {
2089                         channel_id: [0; 32],
2090                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2091                         short_channel_id: Some(42),
2092                         remote_network_id: nodes[7].clone(),
2093                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2094                         channel_value_satoshis: 0,
2095                         user_id: 0,
2096                         outbound_capacity_msat: 250_000_000,
2097                         inbound_capacity_msat: 0,
2098                         to_self_reserve_satoshis: None,
2099                         to_remote_reserve_satoshis: 0,
2100                         confirmations_required: None,
2101                         spend_csv_on_our_commitment_funds: None,
2102                         is_outbound: true, is_funding_locked: true,
2103                         is_usable: true, is_public: true,
2104                         counterparty_forwarding_info: None,
2105                 }];
2106                 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();
2107                 assert_eq!(route.paths[0].len(), 2);
2108
2109                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2110                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2111                 assert_eq!(route.paths[0][0].fee_msat, 200);
2112                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2113                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2114                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2115
2116                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2117                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2118                 assert_eq!(route.paths[0][1].fee_msat, 100);
2119                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2120                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2121                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2122         }
2123
2124         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2125                 let zero_fees = RoutingFees {
2126                         base_msat: 0,
2127                         proportional_millionths: 0,
2128                 };
2129                 vec![RouteHint(vec![RouteHintHop {
2130                         src_node_id: nodes[3].clone(),
2131                         short_channel_id: 8,
2132                         fees: zero_fees,
2133                         cltv_expiry_delta: (8 << 8) | 1,
2134                         htlc_minimum_msat: None,
2135                         htlc_maximum_msat: None,
2136                 }]), RouteHint(vec![RouteHintHop {
2137                         src_node_id: nodes[4].clone(),
2138                         short_channel_id: 9,
2139                         fees: RoutingFees {
2140                                 base_msat: 1001,
2141                                 proportional_millionths: 0,
2142                         },
2143                         cltv_expiry_delta: (9 << 8) | 1,
2144                         htlc_minimum_msat: None,
2145                         htlc_maximum_msat: None,
2146                 }]), RouteHint(vec![RouteHintHop {
2147                         src_node_id: nodes[5].clone(),
2148                         short_channel_id: 10,
2149                         fees: zero_fees,
2150                         cltv_expiry_delta: (10 << 8) | 1,
2151                         htlc_minimum_msat: None,
2152                         htlc_maximum_msat: None,
2153                 }])]
2154         }
2155
2156         #[test]
2157         fn last_hops_test() {
2158                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2159                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2160
2161                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2162
2163                 // First check that last hop can't have its source as the payee.
2164                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2165                         src_node_id: nodes[6],
2166                         short_channel_id: 8,
2167                         fees: RoutingFees {
2168                                 base_msat: 1000,
2169                                 proportional_millionths: 0,
2170                         },
2171                         cltv_expiry_delta: (8 << 8) | 1,
2172                         htlc_minimum_msat: None,
2173                         htlc_maximum_msat: None,
2174                 }]);
2175
2176                 let mut invalid_last_hops = last_hops(&nodes);
2177                 invalid_last_hops.push(invalid_last_hop);
2178                 {
2179                         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)) {
2180                                 assert_eq!(err, "Last hop cannot have a payee as a source.");
2181                         } else { panic!(); }
2182                 }
2183
2184                 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();
2185                 assert_eq!(route.paths[0].len(), 5);
2186
2187                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2188                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2189                 assert_eq!(route.paths[0][0].fee_msat, 100);
2190                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2191                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2192                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2193
2194                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2195                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2196                 assert_eq!(route.paths[0][1].fee_msat, 0);
2197                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2198                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2199                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2200
2201                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2202                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2203                 assert_eq!(route.paths[0][2].fee_msat, 0);
2204                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2205                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2206                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2207
2208                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2209                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2210                 assert_eq!(route.paths[0][3].fee_msat, 0);
2211                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2212                 // If we have a peer in the node map, we'll use their features here since we don't have
2213                 // a way of figuring out their features from the invoice:
2214                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2215                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2216
2217                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2218                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2219                 assert_eq!(route.paths[0][4].fee_msat, 100);
2220                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2221                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2222                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2223         }
2224
2225         #[test]
2226         fn our_chans_last_hop_connect_test() {
2227                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2228                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2229
2230                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2231                 let our_chans = vec![channelmanager::ChannelDetails {
2232                         channel_id: [0; 32],
2233                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2234                         short_channel_id: Some(42),
2235                         remote_network_id: nodes[3].clone(),
2236                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2237                         channel_value_satoshis: 0,
2238                         user_id: 0,
2239                         outbound_capacity_msat: 250_000_000,
2240                         inbound_capacity_msat: 0,
2241                         to_self_reserve_satoshis: None,
2242                         to_remote_reserve_satoshis: 0,
2243                         confirmations_required: None,
2244                         spend_csv_on_our_commitment_funds: None,
2245                         is_outbound: true, is_funding_locked: true,
2246                         is_usable: true, is_public: true,
2247                         counterparty_forwarding_info: None,
2248                 }];
2249                 let mut last_hops = last_hops(&nodes);
2250                 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();
2251                 assert_eq!(route.paths[0].len(), 2);
2252
2253                 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2254                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2255                 assert_eq!(route.paths[0][0].fee_msat, 0);
2256                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2257                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2258                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2259
2260                 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2261                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2262                 assert_eq!(route.paths[0][1].fee_msat, 100);
2263                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2264                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2265                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2266
2267                 last_hops[0].0[0].fees.base_msat = 1000;
2268
2269                 // Revert to via 6 as the fee on 8 goes up
2270                 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();
2271                 assert_eq!(route.paths[0].len(), 4);
2272
2273                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2274                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2275                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2276                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2277                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2278                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2279
2280                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2281                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2282                 assert_eq!(route.paths[0][1].fee_msat, 100);
2283                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2284                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2285                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2286
2287                 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2288                 assert_eq!(route.paths[0][2].short_channel_id, 7);
2289                 assert_eq!(route.paths[0][2].fee_msat, 0);
2290                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2291                 // If we have a peer in the node map, we'll use their features here since we don't have
2292                 // a way of figuring out their features from the invoice:
2293                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2294                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2295
2296                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2297                 assert_eq!(route.paths[0][3].short_channel_id, 10);
2298                 assert_eq!(route.paths[0][3].fee_msat, 100);
2299                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2300                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2301                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2302
2303                 // ...but still use 8 for larger payments as 6 has a variable feerate
2304                 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();
2305                 assert_eq!(route.paths[0].len(), 5);
2306
2307                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2308                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2309                 assert_eq!(route.paths[0][0].fee_msat, 3000);
2310                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2311                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2312                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2313
2314                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2315                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2316                 assert_eq!(route.paths[0][1].fee_msat, 0);
2317                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2318                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2319                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2320
2321                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2322                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2323                 assert_eq!(route.paths[0][2].fee_msat, 0);
2324                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2325                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2326                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2327
2328                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2329                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2330                 assert_eq!(route.paths[0][3].fee_msat, 1000);
2331                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2332                 // If we have a peer in the node map, we'll use their features here since we don't have
2333                 // a way of figuring out their features from the invoice:
2334                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2335                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2336
2337                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2338                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2339                 assert_eq!(route.paths[0][4].fee_msat, 2000);
2340                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2341                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2342                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2343         }
2344
2345         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> {
2346                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2347                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2348                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2349
2350                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2351                 let last_hops = RouteHint(vec![RouteHintHop {
2352                         src_node_id: middle_node_id,
2353                         short_channel_id: 8,
2354                         fees: RoutingFees {
2355                                 base_msat: 1000,
2356                                 proportional_millionths: last_hop_fee_prop,
2357                         },
2358                         cltv_expiry_delta: (8 << 8) | 1,
2359                         htlc_minimum_msat: None,
2360                         htlc_maximum_msat: last_hop_htlc_max,
2361                 }]);
2362                 let our_chans = vec![channelmanager::ChannelDetails {
2363                         channel_id: [0; 32],
2364                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2365                         short_channel_id: Some(42),
2366                         remote_network_id: middle_node_id,
2367                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2368                         channel_value_satoshis: 100000,
2369                         user_id: 0,
2370                         outbound_capacity_msat: outbound_capacity_msat,
2371                         inbound_capacity_msat: 100000,
2372                         to_self_reserve_satoshis: None,
2373                         to_remote_reserve_satoshis: 0,
2374                         confirmations_required: None,
2375                         spend_csv_on_our_commitment_funds: None,
2376                         is_outbound: true, is_funding_locked: true,
2377                         is_usable: true, is_public: true,
2378                         counterparty_forwarding_info: None,
2379                 }];
2380                 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()))
2381         }
2382
2383         #[test]
2384         fn unannounced_path_test() {
2385                 // We should be able to send a payment to a destination without any help of a routing graph
2386                 // if we have a channel with a common counterparty that appears in the first and last hop
2387                 // hints.
2388                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2389
2390                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2391                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2392                 assert_eq!(route.paths[0].len(), 2);
2393
2394                 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2395                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2396                 assert_eq!(route.paths[0][0].fee_msat, 1001);
2397                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2398                 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2399                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2400
2401                 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2402                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2403                 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2404                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2405                 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2406                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2407         }
2408
2409         #[test]
2410         fn overflow_unannounced_path_test_liquidity_underflow() {
2411                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2412                 // the last-hop had a fee which overflowed a u64, we'd panic.
2413                 // This was due to us adding the first-hop from us unconditionally, causing us to think
2414                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2415                 // In this test, we previously hit a subtraction underflow due to having less available
2416                 // liquidity at the last hop than 0.
2417                 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());
2418         }
2419
2420         #[test]
2421         fn overflow_unannounced_path_test_feerate_overflow() {
2422                 // This tests for the same case as above, except instead of hitting a subtraction
2423                 // underflow, we hit a case where the fee charged at a hop overflowed.
2424                 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());
2425         }
2426
2427         #[test]
2428         fn available_amount_while_routing_test() {
2429                 // Tests whether we choose the correct available channel amount while routing.
2430
2431                 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2432                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2433
2434                 // We will use a simple single-path route from
2435                 // our node to node2 via node0: channels {1, 3}.
2436
2437                 // First disable all other paths.
2438                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2439                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2440                         short_channel_id: 2,
2441                         timestamp: 2,
2442                         flags: 2,
2443                         cltv_expiry_delta: 0,
2444                         htlc_minimum_msat: 0,
2445                         htlc_maximum_msat: OptionalField::Present(100_000),
2446                         fee_base_msat: 0,
2447                         fee_proportional_millionths: 0,
2448                         excess_data: Vec::new()
2449                 });
2450                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2451                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2452                         short_channel_id: 12,
2453                         timestamp: 2,
2454                         flags: 2,
2455                         cltv_expiry_delta: 0,
2456                         htlc_minimum_msat: 0,
2457                         htlc_maximum_msat: OptionalField::Present(100_000),
2458                         fee_base_msat: 0,
2459                         fee_proportional_millionths: 0,
2460                         excess_data: Vec::new()
2461                 });
2462
2463                 // Make the first channel (#1) very permissive,
2464                 // and we will be testing all limits on the second channel.
2465                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2466                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2467                         short_channel_id: 1,
2468                         timestamp: 2,
2469                         flags: 0,
2470                         cltv_expiry_delta: 0,
2471                         htlc_minimum_msat: 0,
2472                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2473                         fee_base_msat: 0,
2474                         fee_proportional_millionths: 0,
2475                         excess_data: Vec::new()
2476                 });
2477
2478                 // First, let's see if routing works if we have absolutely no idea about the available amount.
2479                 // In this case, it should be set to 250_000 sats.
2480                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2481                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2482                         short_channel_id: 3,
2483                         timestamp: 2,
2484                         flags: 0,
2485                         cltv_expiry_delta: 0,
2486                         htlc_minimum_msat: 0,
2487                         htlc_maximum_msat: OptionalField::Absent,
2488                         fee_base_msat: 0,
2489                         fee_proportional_millionths: 0,
2490                         excess_data: Vec::new()
2491                 });
2492
2493                 {
2494                         // Attempt to route more than available results in a failure.
2495                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2496                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2497                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2498                         } else { panic!(); }
2499                 }
2500
2501                 {
2502                         // Now, attempt to route an exact amount we have should be fine.
2503                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2504                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2505                         assert_eq!(route.paths.len(), 1);
2506                         let path = route.paths.last().unwrap();
2507                         assert_eq!(path.len(), 2);
2508                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2509                         assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2510                 }
2511
2512                 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2513                 // Disable channel #1 and use another first hop.
2514                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2515                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2516                         short_channel_id: 1,
2517                         timestamp: 3,
2518                         flags: 2,
2519                         cltv_expiry_delta: 0,
2520                         htlc_minimum_msat: 0,
2521                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2522                         fee_base_msat: 0,
2523                         fee_proportional_millionths: 0,
2524                         excess_data: Vec::new()
2525                 });
2526
2527                 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2528                 let our_chans = vec![channelmanager::ChannelDetails {
2529                         channel_id: [0; 32],
2530                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2531                         short_channel_id: Some(42),
2532                         remote_network_id: nodes[0].clone(),
2533                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2534                         channel_value_satoshis: 0,
2535                         user_id: 0,
2536                         outbound_capacity_msat: 200_000_000,
2537                         inbound_capacity_msat: 0,
2538                         to_self_reserve_satoshis: None,
2539                         to_remote_reserve_satoshis: 0,
2540                         confirmations_required: None,
2541                         spend_csv_on_our_commitment_funds: None,
2542                         is_outbound: true, is_funding_locked: true,
2543                         is_usable: true, is_public: true,
2544                         counterparty_forwarding_info: None,
2545                 }];
2546
2547                 {
2548                         // Attempt to route more than available results in a failure.
2549                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2550                                         Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2551                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2552                         } else { panic!(); }
2553                 }
2554
2555                 {
2556                         // Now, attempt to route an exact amount we have should be fine.
2557                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2558                                 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2559                         assert_eq!(route.paths.len(), 1);
2560                         let path = route.paths.last().unwrap();
2561                         assert_eq!(path.len(), 2);
2562                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2563                         assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2564                 }
2565
2566                 // Enable channel #1 back.
2567                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2568                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2569                         short_channel_id: 1,
2570                         timestamp: 4,
2571                         flags: 0,
2572                         cltv_expiry_delta: 0,
2573                         htlc_minimum_msat: 0,
2574                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2575                         fee_base_msat: 0,
2576                         fee_proportional_millionths: 0,
2577                         excess_data: Vec::new()
2578                 });
2579
2580
2581                 // Now let's see if routing works if we know only htlc_maximum_msat.
2582                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2583                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2584                         short_channel_id: 3,
2585                         timestamp: 3,
2586                         flags: 0,
2587                         cltv_expiry_delta: 0,
2588                         htlc_minimum_msat: 0,
2589                         htlc_maximum_msat: OptionalField::Present(15_000),
2590                         fee_base_msat: 0,
2591                         fee_proportional_millionths: 0,
2592                         excess_data: Vec::new()
2593                 });
2594
2595                 {
2596                         // Attempt to route more than available results in a failure.
2597                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2598                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2599                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2600                         } else { panic!(); }
2601                 }
2602
2603                 {
2604                         // Now, attempt to route an exact amount we have should be fine.
2605                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2606                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2607                         assert_eq!(route.paths.len(), 1);
2608                         let path = route.paths.last().unwrap();
2609                         assert_eq!(path.len(), 2);
2610                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2611                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2612                 }
2613
2614                 // Now let's see if routing works if we know only capacity from the UTXO.
2615
2616                 // We can't change UTXO capacity on the fly, so we'll disable
2617                 // the existing channel and add another one with the capacity we need.
2618                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2619                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2620                         short_channel_id: 3,
2621                         timestamp: 4,
2622                         flags: 2,
2623                         cltv_expiry_delta: 0,
2624                         htlc_minimum_msat: 0,
2625                         htlc_maximum_msat: OptionalField::Absent,
2626                         fee_base_msat: 0,
2627                         fee_proportional_millionths: 0,
2628                         excess_data: Vec::new()
2629                 });
2630
2631                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2632                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2633                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2634                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2635                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2636
2637                 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2638                 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2639
2640                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2641                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2642                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2643                         short_channel_id: 333,
2644                         timestamp: 1,
2645                         flags: 0,
2646                         cltv_expiry_delta: (3 << 8) | 1,
2647                         htlc_minimum_msat: 0,
2648                         htlc_maximum_msat: OptionalField::Absent,
2649                         fee_base_msat: 0,
2650                         fee_proportional_millionths: 0,
2651                         excess_data: Vec::new()
2652                 });
2653                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2654                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2655                         short_channel_id: 333,
2656                         timestamp: 1,
2657                         flags: 1,
2658                         cltv_expiry_delta: (3 << 8) | 2,
2659                         htlc_minimum_msat: 0,
2660                         htlc_maximum_msat: OptionalField::Absent,
2661                         fee_base_msat: 100,
2662                         fee_proportional_millionths: 0,
2663                         excess_data: Vec::new()
2664                 });
2665
2666                 {
2667                         // Attempt to route more than available results in a failure.
2668                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2669                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2670                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2671                         } else { panic!(); }
2672                 }
2673
2674                 {
2675                         // Now, attempt to route an exact amount we have should be fine.
2676                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2677                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2678                         assert_eq!(route.paths.len(), 1);
2679                         let path = route.paths.last().unwrap();
2680                         assert_eq!(path.len(), 2);
2681                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2682                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2683                 }
2684
2685                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2686                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2687                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2688                         short_channel_id: 333,
2689                         timestamp: 6,
2690                         flags: 0,
2691                         cltv_expiry_delta: 0,
2692                         htlc_minimum_msat: 0,
2693                         htlc_maximum_msat: OptionalField::Present(10_000),
2694                         fee_base_msat: 0,
2695                         fee_proportional_millionths: 0,
2696                         excess_data: Vec::new()
2697                 });
2698
2699                 {
2700                         // Attempt to route more than available results in a failure.
2701                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2702                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2703                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2704                         } else { panic!(); }
2705                 }
2706
2707                 {
2708                         // Now, attempt to route an exact amount we have should be fine.
2709                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2710                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2711                         assert_eq!(route.paths.len(), 1);
2712                         let path = route.paths.last().unwrap();
2713                         assert_eq!(path.len(), 2);
2714                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2715                         assert_eq!(path.last().unwrap().fee_msat, 10_000);
2716                 }
2717         }
2718
2719         #[test]
2720         fn available_liquidity_last_hop_test() {
2721                 // Check that available liquidity properly limits the path even when only
2722                 // one of the latter hops is limited.
2723                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2724                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2725
2726                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2727                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2728                 // Total capacity: 50 sats.
2729
2730                 // Disable other potential paths.
2731                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2732                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2733                         short_channel_id: 2,
2734                         timestamp: 2,
2735                         flags: 2,
2736                         cltv_expiry_delta: 0,
2737                         htlc_minimum_msat: 0,
2738                         htlc_maximum_msat: OptionalField::Present(100_000),
2739                         fee_base_msat: 0,
2740                         fee_proportional_millionths: 0,
2741                         excess_data: Vec::new()
2742                 });
2743                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2744                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2745                         short_channel_id: 7,
2746                         timestamp: 2,
2747                         flags: 2,
2748                         cltv_expiry_delta: 0,
2749                         htlc_minimum_msat: 0,
2750                         htlc_maximum_msat: OptionalField::Present(100_000),
2751                         fee_base_msat: 0,
2752                         fee_proportional_millionths: 0,
2753                         excess_data: Vec::new()
2754                 });
2755
2756                 // Limit capacities
2757
2758                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2759                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2760                         short_channel_id: 12,
2761                         timestamp: 2,
2762                         flags: 0,
2763                         cltv_expiry_delta: 0,
2764                         htlc_minimum_msat: 0,
2765                         htlc_maximum_msat: OptionalField::Present(100_000),
2766                         fee_base_msat: 0,
2767                         fee_proportional_millionths: 0,
2768                         excess_data: Vec::new()
2769                 });
2770                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2771                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2772                         short_channel_id: 13,
2773                         timestamp: 2,
2774                         flags: 0,
2775                         cltv_expiry_delta: 0,
2776                         htlc_minimum_msat: 0,
2777                         htlc_maximum_msat: OptionalField::Present(100_000),
2778                         fee_base_msat: 0,
2779                         fee_proportional_millionths: 0,
2780                         excess_data: Vec::new()
2781                 });
2782
2783                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2784                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2785                         short_channel_id: 6,
2786                         timestamp: 2,
2787                         flags: 0,
2788                         cltv_expiry_delta: 0,
2789                         htlc_minimum_msat: 0,
2790                         htlc_maximum_msat: OptionalField::Present(50_000),
2791                         fee_base_msat: 0,
2792                         fee_proportional_millionths: 0,
2793                         excess_data: Vec::new()
2794                 });
2795                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2796                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2797                         short_channel_id: 11,
2798                         timestamp: 2,
2799                         flags: 0,
2800                         cltv_expiry_delta: 0,
2801                         htlc_minimum_msat: 0,
2802                         htlc_maximum_msat: OptionalField::Present(100_000),
2803                         fee_base_msat: 0,
2804                         fee_proportional_millionths: 0,
2805                         excess_data: Vec::new()
2806                 });
2807                 {
2808                         // Attempt to route more than available results in a failure.
2809                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2810                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2811                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2812                         } else { panic!(); }
2813                 }
2814
2815                 {
2816                         // Now, attempt to route 49 sats (just a bit below the capacity).
2817                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2818                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2819                         assert_eq!(route.paths.len(), 1);
2820                         let mut total_amount_paid_msat = 0;
2821                         for path in &route.paths {
2822                                 assert_eq!(path.len(), 4);
2823                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2824                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2825                         }
2826                         assert_eq!(total_amount_paid_msat, 49_000);
2827                 }
2828
2829                 {
2830                         // Attempt to route an exact amount is also fine
2831                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2832                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2833                         assert_eq!(route.paths.len(), 1);
2834                         let mut total_amount_paid_msat = 0;
2835                         for path in &route.paths {
2836                                 assert_eq!(path.len(), 4);
2837                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2838                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2839                         }
2840                         assert_eq!(total_amount_paid_msat, 50_000);
2841                 }
2842         }
2843
2844         #[test]
2845         fn ignore_fee_first_hop_test() {
2846                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2847                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2848
2849                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2850                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2851                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2852                         short_channel_id: 1,
2853                         timestamp: 2,
2854                         flags: 0,
2855                         cltv_expiry_delta: 0,
2856                         htlc_minimum_msat: 0,
2857                         htlc_maximum_msat: OptionalField::Present(100_000),
2858                         fee_base_msat: 1_000_000,
2859                         fee_proportional_millionths: 0,
2860                         excess_data: Vec::new()
2861                 });
2862                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2863                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2864                         short_channel_id: 3,
2865                         timestamp: 2,
2866                         flags: 0,
2867                         cltv_expiry_delta: 0,
2868                         htlc_minimum_msat: 0,
2869                         htlc_maximum_msat: OptionalField::Present(50_000),
2870                         fee_base_msat: 0,
2871                         fee_proportional_millionths: 0,
2872                         excess_data: Vec::new()
2873                 });
2874
2875                 {
2876                         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();
2877                         assert_eq!(route.paths.len(), 1);
2878                         let mut total_amount_paid_msat = 0;
2879                         for path in &route.paths {
2880                                 assert_eq!(path.len(), 2);
2881                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2882                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2883                         }
2884                         assert_eq!(total_amount_paid_msat, 50_000);
2885                 }
2886         }
2887
2888         #[test]
2889         fn simple_mpp_route_test() {
2890                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2891                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2892
2893                 // We need a route consisting of 3 paths:
2894                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2895                 // To achieve this, the amount being transferred should be around
2896                 // the total capacity of these 3 paths.
2897
2898                 // First, we set limits on these (previously unlimited) channels.
2899                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2900
2901                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2902                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2903                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2904                         short_channel_id: 1,
2905                         timestamp: 2,
2906                         flags: 0,
2907                         cltv_expiry_delta: 0,
2908                         htlc_minimum_msat: 0,
2909                         htlc_maximum_msat: OptionalField::Present(100_000),
2910                         fee_base_msat: 0,
2911                         fee_proportional_millionths: 0,
2912                         excess_data: Vec::new()
2913                 });
2914                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2915                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2916                         short_channel_id: 3,
2917                         timestamp: 2,
2918                         flags: 0,
2919                         cltv_expiry_delta: 0,
2920                         htlc_minimum_msat: 0,
2921                         htlc_maximum_msat: OptionalField::Present(50_000),
2922                         fee_base_msat: 0,
2923                         fee_proportional_millionths: 0,
2924                         excess_data: Vec::new()
2925                 });
2926
2927                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2928                 // (total limit 60).
2929                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2930                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2931                         short_channel_id: 12,
2932                         timestamp: 2,
2933                         flags: 0,
2934                         cltv_expiry_delta: 0,
2935                         htlc_minimum_msat: 0,
2936                         htlc_maximum_msat: OptionalField::Present(60_000),
2937                         fee_base_msat: 0,
2938                         fee_proportional_millionths: 0,
2939                         excess_data: Vec::new()
2940                 });
2941                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2942                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2943                         short_channel_id: 13,
2944                         timestamp: 2,
2945                         flags: 0,
2946                         cltv_expiry_delta: 0,
2947                         htlc_minimum_msat: 0,
2948                         htlc_maximum_msat: OptionalField::Present(60_000),
2949                         fee_base_msat: 0,
2950                         fee_proportional_millionths: 0,
2951                         excess_data: Vec::new()
2952                 });
2953
2954                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2955                 // (total capacity 180 sats).
2956                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2957                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2958                         short_channel_id: 2,
2959                         timestamp: 2,
2960                         flags: 0,
2961                         cltv_expiry_delta: 0,
2962                         htlc_minimum_msat: 0,
2963                         htlc_maximum_msat: OptionalField::Present(200_000),
2964                         fee_base_msat: 0,
2965                         fee_proportional_millionths: 0,
2966                         excess_data: Vec::new()
2967                 });
2968                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2969                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2970                         short_channel_id: 4,
2971                         timestamp: 2,
2972                         flags: 0,
2973                         cltv_expiry_delta: 0,
2974                         htlc_minimum_msat: 0,
2975                         htlc_maximum_msat: OptionalField::Present(180_000),
2976                         fee_base_msat: 0,
2977                         fee_proportional_millionths: 0,
2978                         excess_data: Vec::new()
2979                 });
2980
2981                 {
2982                         // Attempt to route more than available results in a failure.
2983                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2984                                         &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2985                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2986                         } else { panic!(); }
2987                 }
2988
2989                 {
2990                         // Now, attempt to route 250 sats (just a bit below the capacity).
2991                         // Our algorithm should provide us with these 3 paths.
2992                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2993                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2994                         assert_eq!(route.paths.len(), 3);
2995                         let mut total_amount_paid_msat = 0;
2996                         for path in &route.paths {
2997                                 assert_eq!(path.len(), 2);
2998                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2999                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3000                         }
3001                         assert_eq!(total_amount_paid_msat, 250_000);
3002                 }
3003
3004                 {
3005                         // Attempt to route an exact amount is also fine
3006                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3007                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
3008                         assert_eq!(route.paths.len(), 3);
3009                         let mut total_amount_paid_msat = 0;
3010                         for path in &route.paths {
3011                                 assert_eq!(path.len(), 2);
3012                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3013                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3014                         }
3015                         assert_eq!(total_amount_paid_msat, 290_000);
3016                 }
3017         }
3018
3019         #[test]
3020         fn long_mpp_route_test() {
3021                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3022                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3023
3024                 // We need a route consisting of 3 paths:
3025                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3026                 // Note that these paths overlap (channels 5, 12, 13).
3027                 // We will route 300 sats.
3028                 // Each path will have 100 sats capacity, those channels which
3029                 // are used twice will have 200 sats capacity.
3030
3031                 // Disable other potential paths.
3032                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3033                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3034                         short_channel_id: 2,
3035                         timestamp: 2,
3036                         flags: 2,
3037                         cltv_expiry_delta: 0,
3038                         htlc_minimum_msat: 0,
3039                         htlc_maximum_msat: OptionalField::Present(100_000),
3040                         fee_base_msat: 0,
3041                         fee_proportional_millionths: 0,
3042                         excess_data: Vec::new()
3043                 });
3044                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3045                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3046                         short_channel_id: 7,
3047                         timestamp: 2,
3048                         flags: 2,
3049                         cltv_expiry_delta: 0,
3050                         htlc_minimum_msat: 0,
3051                         htlc_maximum_msat: OptionalField::Present(100_000),
3052                         fee_base_msat: 0,
3053                         fee_proportional_millionths: 0,
3054                         excess_data: Vec::new()
3055                 });
3056
3057                 // Path via {node0, node2} is channels {1, 3, 5}.
3058                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3059                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3060                         short_channel_id: 1,
3061                         timestamp: 2,
3062                         flags: 0,
3063                         cltv_expiry_delta: 0,
3064                         htlc_minimum_msat: 0,
3065                         htlc_maximum_msat: OptionalField::Present(100_000),
3066                         fee_base_msat: 0,
3067                         fee_proportional_millionths: 0,
3068                         excess_data: Vec::new()
3069                 });
3070                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3071                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3072                         short_channel_id: 3,
3073                         timestamp: 2,
3074                         flags: 0,
3075                         cltv_expiry_delta: 0,
3076                         htlc_minimum_msat: 0,
3077                         htlc_maximum_msat: OptionalField::Present(100_000),
3078                         fee_base_msat: 0,
3079                         fee_proportional_millionths: 0,
3080                         excess_data: Vec::new()
3081                 });
3082
3083                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3084                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3085                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3086                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3087                         short_channel_id: 5,
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                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3099                 // Add 100 sats to the capacities of {12, 13}, because these channels
3100                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3101                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3102                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3103                         short_channel_id: 12,
3104                         timestamp: 2,
3105                         flags: 0,
3106                         cltv_expiry_delta: 0,
3107                         htlc_minimum_msat: 0,
3108                         htlc_maximum_msat: OptionalField::Present(200_000),
3109                         fee_base_msat: 0,
3110                         fee_proportional_millionths: 0,
3111                         excess_data: Vec::new()
3112                 });
3113                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3114                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3115                         short_channel_id: 13,
3116                         timestamp: 2,
3117                         flags: 0,
3118                         cltv_expiry_delta: 0,
3119                         htlc_minimum_msat: 0,
3120                         htlc_maximum_msat: OptionalField::Present(200_000),
3121                         fee_base_msat: 0,
3122                         fee_proportional_millionths: 0,
3123                         excess_data: Vec::new()
3124                 });
3125
3126                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3127                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3128                         short_channel_id: 6,
3129                         timestamp: 2,
3130                         flags: 0,
3131                         cltv_expiry_delta: 0,
3132                         htlc_minimum_msat: 0,
3133                         htlc_maximum_msat: OptionalField::Present(100_000),
3134                         fee_base_msat: 0,
3135                         fee_proportional_millionths: 0,
3136                         excess_data: Vec::new()
3137                 });
3138                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3139                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3140                         short_channel_id: 11,
3141                         timestamp: 2,
3142                         flags: 0,
3143                         cltv_expiry_delta: 0,
3144                         htlc_minimum_msat: 0,
3145                         htlc_maximum_msat: OptionalField::Present(100_000),
3146                         fee_base_msat: 0,
3147                         fee_proportional_millionths: 0,
3148                         excess_data: Vec::new()
3149                 });
3150
3151                 // Path via {node7, node2} is channels {12, 13, 5}.
3152                 // We already limited them to 200 sats (they are used twice for 100 sats).
3153                 // Nothing to do here.
3154
3155                 {
3156                         // Attempt to route more than available results in a failure.
3157                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3158                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3159                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3160                         } else { panic!(); }
3161                 }
3162
3163                 {
3164                         // Now, attempt to route 300 sats (exact amount we can route).
3165                         // Our algorithm should provide us with these 3 paths, 100 sats each.
3166                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3167                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3168                         assert_eq!(route.paths.len(), 3);
3169
3170                         let mut total_amount_paid_msat = 0;
3171                         for path in &route.paths {
3172                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3173                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3174                         }
3175                         assert_eq!(total_amount_paid_msat, 300_000);
3176                 }
3177
3178         }
3179
3180         #[test]
3181         fn mpp_cheaper_route_test() {
3182                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3183                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3184
3185                 // This test checks that if we have two cheaper paths and one more expensive path,
3186                 // so that liquidity-wise any 2 of 3 combination is sufficient,
3187                 // two cheaper paths will be taken.
3188                 // These paths have equal available liquidity.
3189
3190                 // We need a combination of 3 paths:
3191                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3192                 // Note that these paths overlap (channels 5, 12, 13).
3193                 // Each path will have 100 sats capacity, those channels which
3194                 // are used twice will have 200 sats capacity.
3195
3196                 // Disable other potential paths.
3197                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3198                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3199                         short_channel_id: 2,
3200                         timestamp: 2,
3201                         flags: 2,
3202                         cltv_expiry_delta: 0,
3203                         htlc_minimum_msat: 0,
3204                         htlc_maximum_msat: OptionalField::Present(100_000),
3205                         fee_base_msat: 0,
3206                         fee_proportional_millionths: 0,
3207                         excess_data: Vec::new()
3208                 });
3209                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3210                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3211                         short_channel_id: 7,
3212                         timestamp: 2,
3213                         flags: 2,
3214                         cltv_expiry_delta: 0,
3215                         htlc_minimum_msat: 0,
3216                         htlc_maximum_msat: OptionalField::Present(100_000),
3217                         fee_base_msat: 0,
3218                         fee_proportional_millionths: 0,
3219                         excess_data: Vec::new()
3220                 });
3221
3222                 // Path via {node0, node2} is channels {1, 3, 5}.
3223                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3224                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3225                         short_channel_id: 1,
3226                         timestamp: 2,
3227                         flags: 0,
3228                         cltv_expiry_delta: 0,
3229                         htlc_minimum_msat: 0,
3230                         htlc_maximum_msat: OptionalField::Present(100_000),
3231                         fee_base_msat: 0,
3232                         fee_proportional_millionths: 0,
3233                         excess_data: Vec::new()
3234                 });
3235                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3236                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3237                         short_channel_id: 3,
3238                         timestamp: 2,
3239                         flags: 0,
3240                         cltv_expiry_delta: 0,
3241                         htlc_minimum_msat: 0,
3242                         htlc_maximum_msat: OptionalField::Present(100_000),
3243                         fee_base_msat: 0,
3244                         fee_proportional_millionths: 0,
3245                         excess_data: Vec::new()
3246                 });
3247
3248                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3249                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3250                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3251                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3252                         short_channel_id: 5,
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                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3264                 // Add 100 sats to the capacities of {12, 13}, because these channels
3265                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3266                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3267                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3268                         short_channel_id: 12,
3269                         timestamp: 2,
3270                         flags: 0,
3271                         cltv_expiry_delta: 0,
3272                         htlc_minimum_msat: 0,
3273                         htlc_maximum_msat: OptionalField::Present(200_000),
3274                         fee_base_msat: 0,
3275                         fee_proportional_millionths: 0,
3276                         excess_data: Vec::new()
3277                 });
3278                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3279                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3280                         short_channel_id: 13,
3281                         timestamp: 2,
3282                         flags: 0,
3283                         cltv_expiry_delta: 0,
3284                         htlc_minimum_msat: 0,
3285                         htlc_maximum_msat: OptionalField::Present(200_000),
3286                         fee_base_msat: 0,
3287                         fee_proportional_millionths: 0,
3288                         excess_data: Vec::new()
3289                 });
3290
3291                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3292                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3293                         short_channel_id: 6,
3294                         timestamp: 2,
3295                         flags: 0,
3296                         cltv_expiry_delta: 0,
3297                         htlc_minimum_msat: 0,
3298                         htlc_maximum_msat: OptionalField::Present(100_000),
3299                         fee_base_msat: 1_000,
3300                         fee_proportional_millionths: 0,
3301                         excess_data: Vec::new()
3302                 });
3303                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3304                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3305                         short_channel_id: 11,
3306                         timestamp: 2,
3307                         flags: 0,
3308                         cltv_expiry_delta: 0,
3309                         htlc_minimum_msat: 0,
3310                         htlc_maximum_msat: OptionalField::Present(100_000),
3311                         fee_base_msat: 0,
3312                         fee_proportional_millionths: 0,
3313                         excess_data: Vec::new()
3314                 });
3315
3316                 // Path via {node7, node2} is channels {12, 13, 5}.
3317                 // We already limited them to 200 sats (they are used twice for 100 sats).
3318                 // Nothing to do here.
3319
3320                 {
3321                         // Now, attempt to route 180 sats.
3322                         // Our algorithm should provide us with these 2 paths.
3323                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3324                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3325                         assert_eq!(route.paths.len(), 2);
3326
3327                         let mut total_value_transferred_msat = 0;
3328                         let mut total_paid_msat = 0;
3329                         for path in &route.paths {
3330                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3331                                 total_value_transferred_msat += path.last().unwrap().fee_msat;
3332                                 for hop in path {
3333                                         total_paid_msat += hop.fee_msat;
3334                                 }
3335                         }
3336                         // If we paid fee, this would be higher.
3337                         assert_eq!(total_value_transferred_msat, 180_000);
3338                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3339                         assert_eq!(total_fees_paid, 0);
3340                 }
3341         }
3342
3343         #[test]
3344         fn fees_on_mpp_route_test() {
3345                 // This test makes sure that MPP algorithm properly takes into account
3346                 // fees charged on the channels, by making the fees impactful:
3347                 // if the fee is not properly accounted for, the behavior is different.
3348                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3349                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3350
3351                 // We need a route consisting of 2 paths:
3352                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3353                 // We will route 200 sats, Each path will have 100 sats capacity.
3354
3355                 // This test is not particularly stable: e.g.,
3356                 // there's a way to route via {node0, node2, node4}.
3357                 // It works while pathfinding is deterministic, but can be broken otherwise.
3358                 // It's fine to ignore this concern for now.
3359
3360                 // Disable other potential paths.
3361                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3362                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3363                         short_channel_id: 2,
3364                         timestamp: 2,
3365                         flags: 2,
3366                         cltv_expiry_delta: 0,
3367                         htlc_minimum_msat: 0,
3368                         htlc_maximum_msat: OptionalField::Present(100_000),
3369                         fee_base_msat: 0,
3370                         fee_proportional_millionths: 0,
3371                         excess_data: Vec::new()
3372                 });
3373
3374                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3375                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3376                         short_channel_id: 7,
3377                         timestamp: 2,
3378                         flags: 2,
3379                         cltv_expiry_delta: 0,
3380                         htlc_minimum_msat: 0,
3381                         htlc_maximum_msat: OptionalField::Present(100_000),
3382                         fee_base_msat: 0,
3383                         fee_proportional_millionths: 0,
3384                         excess_data: Vec::new()
3385                 });
3386
3387                 // Path via {node0, node2} is channels {1, 3, 5}.
3388                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3389                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3390                         short_channel_id: 1,
3391                         timestamp: 2,
3392                         flags: 0,
3393                         cltv_expiry_delta: 0,
3394                         htlc_minimum_msat: 0,
3395                         htlc_maximum_msat: OptionalField::Present(100_000),
3396                         fee_base_msat: 0,
3397                         fee_proportional_millionths: 0,
3398                         excess_data: Vec::new()
3399                 });
3400                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3401                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3402                         short_channel_id: 3,
3403                         timestamp: 2,
3404                         flags: 0,
3405                         cltv_expiry_delta: 0,
3406                         htlc_minimum_msat: 0,
3407                         htlc_maximum_msat: OptionalField::Present(100_000),
3408                         fee_base_msat: 0,
3409                         fee_proportional_millionths: 0,
3410                         excess_data: Vec::new()
3411                 });
3412
3413                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3414                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3415                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3416                         short_channel_id: 5,
3417                         timestamp: 2,
3418                         flags: 0,
3419                         cltv_expiry_delta: 0,
3420                         htlc_minimum_msat: 0,
3421                         htlc_maximum_msat: OptionalField::Present(100_000),
3422                         fee_base_msat: 0,
3423                         fee_proportional_millionths: 0,
3424                         excess_data: Vec::new()
3425                 });
3426
3427                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3428                 // All channels should be 100 sats capacity. But for the fee experiment,
3429                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3430                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3431                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3432                 // so no matter how large are other channels,
3433                 // the whole path will be limited by 100 sats with just these 2 conditions:
3434                 // - channel 12 capacity is 250 sats
3435                 // - fee for channel 6 is 150 sats
3436                 // Let's test this by enforcing these 2 conditions and removing other limits.
3437                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3438                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3439                         short_channel_id: 12,
3440                         timestamp: 2,
3441                         flags: 0,
3442                         cltv_expiry_delta: 0,
3443                         htlc_minimum_msat: 0,
3444                         htlc_maximum_msat: OptionalField::Present(250_000),
3445                         fee_base_msat: 0,
3446                         fee_proportional_millionths: 0,
3447                         excess_data: Vec::new()
3448                 });
3449                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3450                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3451                         short_channel_id: 13,
3452                         timestamp: 2,
3453                         flags: 0,
3454                         cltv_expiry_delta: 0,
3455                         htlc_minimum_msat: 0,
3456                         htlc_maximum_msat: OptionalField::Absent,
3457                         fee_base_msat: 0,
3458                         fee_proportional_millionths: 0,
3459                         excess_data: Vec::new()
3460                 });
3461
3462                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3463                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3464                         short_channel_id: 6,
3465                         timestamp: 2,
3466                         flags: 0,
3467                         cltv_expiry_delta: 0,
3468                         htlc_minimum_msat: 0,
3469                         htlc_maximum_msat: OptionalField::Absent,
3470                         fee_base_msat: 150_000,
3471                         fee_proportional_millionths: 0,
3472                         excess_data: Vec::new()
3473                 });
3474                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3475                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3476                         short_channel_id: 11,
3477                         timestamp: 2,
3478                         flags: 0,
3479                         cltv_expiry_delta: 0,
3480                         htlc_minimum_msat: 0,
3481                         htlc_maximum_msat: OptionalField::Absent,
3482                         fee_base_msat: 0,
3483                         fee_proportional_millionths: 0,
3484                         excess_data: Vec::new()
3485                 });
3486
3487                 {
3488                         // Attempt to route more than available results in a failure.
3489                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3490                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3491                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3492                         } else { panic!(); }
3493                 }
3494
3495                 {
3496                         // Now, attempt to route 200 sats (exact amount we can route).
3497                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3498                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3499                         assert_eq!(route.paths.len(), 2);
3500
3501                         let mut total_amount_paid_msat = 0;
3502                         for path in &route.paths {
3503                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3504                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3505                         }
3506                         assert_eq!(total_amount_paid_msat, 200_000);
3507                 }
3508
3509         }
3510
3511         #[test]
3512         fn drop_lowest_channel_mpp_route_test() {
3513                 // This test checks that low-capacity channel is dropped when after
3514                 // path finding we realize that we found more capacity than we need.
3515                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3516                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3517
3518                 // We need a route consisting of 3 paths:
3519                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3520
3521                 // The first and the second paths should be sufficient, but the third should be
3522                 // cheaper, so that we select it but drop later.
3523
3524                 // First, we set limits on these (previously unlimited) channels.
3525                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3526
3527                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3528                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3529                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3530                         short_channel_id: 1,
3531                         timestamp: 2,
3532                         flags: 0,
3533                         cltv_expiry_delta: 0,
3534                         htlc_minimum_msat: 0,
3535                         htlc_maximum_msat: OptionalField::Present(100_000),
3536                         fee_base_msat: 0,
3537                         fee_proportional_millionths: 0,
3538                         excess_data: Vec::new()
3539                 });
3540                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3541                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3542                         short_channel_id: 3,
3543                         timestamp: 2,
3544                         flags: 0,
3545                         cltv_expiry_delta: 0,
3546                         htlc_minimum_msat: 0,
3547                         htlc_maximum_msat: OptionalField::Present(50_000),
3548                         fee_base_msat: 100,
3549                         fee_proportional_millionths: 0,
3550                         excess_data: Vec::new()
3551                 });
3552
3553                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3554                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3555                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3556                         short_channel_id: 12,
3557                         timestamp: 2,
3558                         flags: 0,
3559                         cltv_expiry_delta: 0,
3560                         htlc_minimum_msat: 0,
3561                         htlc_maximum_msat: OptionalField::Present(60_000),
3562                         fee_base_msat: 100,
3563                         fee_proportional_millionths: 0,
3564                         excess_data: Vec::new()
3565                 });
3566                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3567                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3568                         short_channel_id: 13,
3569                         timestamp: 2,
3570                         flags: 0,
3571                         cltv_expiry_delta: 0,
3572                         htlc_minimum_msat: 0,
3573                         htlc_maximum_msat: OptionalField::Present(60_000),
3574                         fee_base_msat: 0,
3575                         fee_proportional_millionths: 0,
3576                         excess_data: Vec::new()
3577                 });
3578
3579                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3580                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3581                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3582                         short_channel_id: 2,
3583                         timestamp: 2,
3584                         flags: 0,
3585                         cltv_expiry_delta: 0,
3586                         htlc_minimum_msat: 0,
3587                         htlc_maximum_msat: OptionalField::Present(20_000),
3588                         fee_base_msat: 0,
3589                         fee_proportional_millionths: 0,
3590                         excess_data: Vec::new()
3591                 });
3592                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3593                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3594                         short_channel_id: 4,
3595                         timestamp: 2,
3596                         flags: 0,
3597                         cltv_expiry_delta: 0,
3598                         htlc_minimum_msat: 0,
3599                         htlc_maximum_msat: OptionalField::Present(20_000),
3600                         fee_base_msat: 0,
3601                         fee_proportional_millionths: 0,
3602                         excess_data: Vec::new()
3603                 });
3604
3605                 {
3606                         // Attempt to route more than available results in a failure.
3607                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3608                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3609                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3610                         } else { panic!(); }
3611                 }
3612
3613                 {
3614                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3615                         // Our algorithm should provide us with these 3 paths.
3616                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3617                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3618                         assert_eq!(route.paths.len(), 3);
3619                         let mut total_amount_paid_msat = 0;
3620                         for path in &route.paths {
3621                                 assert_eq!(path.len(), 2);
3622                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3623                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3624                         }
3625                         assert_eq!(total_amount_paid_msat, 125_000);
3626                 }
3627
3628                 {
3629                         // Attempt to route without the last small cheap channel
3630                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3631                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3632                         assert_eq!(route.paths.len(), 2);
3633                         let mut total_amount_paid_msat = 0;
3634                         for path in &route.paths {
3635                                 assert_eq!(path.len(), 2);
3636                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3637                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3638                         }
3639                         assert_eq!(total_amount_paid_msat, 90_000);
3640                 }
3641         }
3642
3643         #[test]
3644         fn min_criteria_consistency() {
3645                 // Test that we don't use an inconsistent metric between updating and walking nodes during
3646                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3647                 // was updated with a different criterion from the heap sorting, resulting in loops in
3648                 // calculated paths. We test for that specific case here.
3649
3650                 // We construct a network that looks like this:
3651                 //
3652                 //            node2 -1(3)2- node3
3653                 //              2          2
3654                 //               (2)     (4)
3655                 //                  1   1
3656                 //    node1 -1(5)2- node4 -1(1)2- node6
3657                 //    2
3658                 //   (6)
3659                 //        1
3660                 // our_node
3661                 //
3662                 // We create a loop on the side of our real path - our destination is node 6, with a
3663                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3664                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3665                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3666                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3667                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3668                 // "previous hop" being set to node 3, creating a loop in the path.
3669                 let secp_ctx = Secp256k1::new();
3670                 let logger = Arc::new(test_utils::TestLogger::new());
3671                 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3672                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3673
3674                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3675                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3676                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3677                         short_channel_id: 6,
3678                         timestamp: 1,
3679                         flags: 0,
3680                         cltv_expiry_delta: (6 << 8) | 0,
3681                         htlc_minimum_msat: 0,
3682                         htlc_maximum_msat: OptionalField::Absent,
3683                         fee_base_msat: 0,
3684                         fee_proportional_millionths: 0,
3685                         excess_data: Vec::new()
3686                 });
3687                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3688
3689                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3690                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3691                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3692                         short_channel_id: 5,
3693                         timestamp: 1,
3694                         flags: 0,
3695                         cltv_expiry_delta: (5 << 8) | 0,
3696                         htlc_minimum_msat: 0,
3697                         htlc_maximum_msat: OptionalField::Absent,
3698                         fee_base_msat: 100,
3699                         fee_proportional_millionths: 0,
3700                         excess_data: Vec::new()
3701                 });
3702                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3703
3704                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3705                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3706                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3707                         short_channel_id: 4,
3708                         timestamp: 1,
3709                         flags: 0,
3710                         cltv_expiry_delta: (4 << 8) | 0,
3711                         htlc_minimum_msat: 0,
3712                         htlc_maximum_msat: OptionalField::Absent,
3713                         fee_base_msat: 0,
3714                         fee_proportional_millionths: 0,
3715                         excess_data: Vec::new()
3716                 });
3717                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3718
3719                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3720                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3721                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3722                         short_channel_id: 3,
3723                         timestamp: 1,
3724                         flags: 0,
3725                         cltv_expiry_delta: (3 << 8) | 0,
3726                         htlc_minimum_msat: 0,
3727                         htlc_maximum_msat: OptionalField::Absent,
3728                         fee_base_msat: 0,
3729                         fee_proportional_millionths: 0,
3730                         excess_data: Vec::new()
3731                 });
3732                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3733
3734                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3735                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3736                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3737                         short_channel_id: 2,
3738                         timestamp: 1,
3739                         flags: 0,
3740                         cltv_expiry_delta: (2 << 8) | 0,
3741                         htlc_minimum_msat: 0,
3742                         htlc_maximum_msat: OptionalField::Absent,
3743                         fee_base_msat: 0,
3744                         fee_proportional_millionths: 0,
3745                         excess_data: Vec::new()
3746                 });
3747
3748                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3749                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3750                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3751                         short_channel_id: 1,
3752                         timestamp: 1,
3753                         flags: 0,
3754                         cltv_expiry_delta: (1 << 8) | 0,
3755                         htlc_minimum_msat: 100,
3756                         htlc_maximum_msat: OptionalField::Absent,
3757                         fee_base_msat: 0,
3758                         fee_proportional_millionths: 0,
3759                         excess_data: Vec::new()
3760                 });
3761                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3762
3763                 {
3764                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
3765                         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();
3766                         assert_eq!(route.paths.len(), 1);
3767                         assert_eq!(route.paths[0].len(), 3);
3768
3769                         assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3770                         assert_eq!(route.paths[0][0].short_channel_id, 6);
3771                         assert_eq!(route.paths[0][0].fee_msat, 100);
3772                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3773                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3774                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3775
3776                         assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3777                         assert_eq!(route.paths[0][1].short_channel_id, 5);
3778                         assert_eq!(route.paths[0][1].fee_msat, 0);
3779                         assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3780                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3781                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3782
3783                         assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3784                         assert_eq!(route.paths[0][2].short_channel_id, 1);
3785                         assert_eq!(route.paths[0][2].fee_msat, 10_000);
3786                         assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3787                         assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3788                         assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3789                 }
3790         }
3791
3792
3793         #[test]
3794         fn exact_fee_liquidity_limit() {
3795                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3796                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3797                 // we calculated fees on a higher value, resulting in us ignoring such paths.
3798                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3799                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3800
3801                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3802                 // send.
3803                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3804                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3805                         short_channel_id: 2,
3806                         timestamp: 2,
3807                         flags: 0,
3808                         cltv_expiry_delta: 0,
3809                         htlc_minimum_msat: 0,
3810                         htlc_maximum_msat: OptionalField::Present(85_000),
3811                         fee_base_msat: 0,
3812                         fee_proportional_millionths: 0,
3813                         excess_data: Vec::new()
3814                 });
3815
3816                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3817                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3818                         short_channel_id: 12,
3819                         timestamp: 2,
3820                         flags: 0,
3821                         cltv_expiry_delta: (4 << 8) | 1,
3822                         htlc_minimum_msat: 0,
3823                         htlc_maximum_msat: OptionalField::Present(270_000),
3824                         fee_base_msat: 0,
3825                         fee_proportional_millionths: 1000000,
3826                         excess_data: Vec::new()
3827                 });
3828
3829                 {
3830                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3831                         // 200% fee charged channel 13 in the 1-to-2 direction.
3832                         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();
3833                         assert_eq!(route.paths.len(), 1);
3834                         assert_eq!(route.paths[0].len(), 2);
3835
3836                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3837                         assert_eq!(route.paths[0][0].short_channel_id, 12);
3838                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3839                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3840                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3841                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3842
3843                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3844                         assert_eq!(route.paths[0][1].short_channel_id, 13);
3845                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
3846                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3847                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3848                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3849                 }
3850         }
3851
3852         #[test]
3853         fn htlc_max_reduction_below_min() {
3854                 // Test that if, while walking the graph, we reduce the value being sent to meet an
3855                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3856                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3857                 // resulting in us thinking there is no possible path, even if other paths exist.
3858                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3859                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3860
3861                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3862                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3863                 // then try to send 90_000.
3864                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3865                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3866                         short_channel_id: 2,
3867                         timestamp: 2,
3868                         flags: 0,
3869                         cltv_expiry_delta: 0,
3870                         htlc_minimum_msat: 0,
3871                         htlc_maximum_msat: OptionalField::Present(80_000),
3872                         fee_base_msat: 0,
3873                         fee_proportional_millionths: 0,
3874                         excess_data: Vec::new()
3875                 });
3876                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3877                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3878                         short_channel_id: 4,
3879                         timestamp: 2,
3880                         flags: 0,
3881                         cltv_expiry_delta: (4 << 8) | 1,
3882                         htlc_minimum_msat: 90_000,
3883                         htlc_maximum_msat: OptionalField::Absent,
3884                         fee_base_msat: 0,
3885                         fee_proportional_millionths: 0,
3886                         excess_data: Vec::new()
3887                 });
3888
3889                 {
3890                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3891                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3892                         // expensive) channels 12-13 path.
3893                         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();
3894                         assert_eq!(route.paths.len(), 1);
3895                         assert_eq!(route.paths[0].len(), 2);
3896
3897                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3898                         assert_eq!(route.paths[0][0].short_channel_id, 12);
3899                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3900                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3901                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3902                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3903
3904                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3905                         assert_eq!(route.paths[0][1].short_channel_id, 13);
3906                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
3907                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3908                         assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3909                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3910                 }
3911         }
3912
3913         #[cfg(not(feature = "no_std"))]
3914         pub(super) fn random_init_seed() -> u64 {
3915                 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3916                 use core::hash::{BuildHasher, Hasher};
3917                 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3918                 println!("Using seed of {}", seed);
3919                 seed
3920         }
3921         #[cfg(not(feature = "no_std"))]
3922         use util::ser::Readable;
3923
3924         #[test]
3925         #[cfg(not(feature = "no_std"))]
3926         fn generate_routes() {
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, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3946                                         continue 'load_endpoints;
3947                                 }
3948                         }
3949                 }
3950         }
3951
3952         #[test]
3953         #[cfg(not(feature = "no_std"))]
3954         fn generate_routes_mpp() {
3955                 let mut d = match super::test_utils::get_route_file() {
3956                         Ok(f) => f,
3957                         Err(e) => {
3958                                 eprintln!("{}", e);
3959                                 return;
3960                         },
3961                 };
3962                 let graph = NetworkGraph::read(&mut d).unwrap();
3963
3964                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3965                 let mut seed = random_init_seed() as usize;
3966                 'load_endpoints: for _ in 0..10 {
3967                         loop {
3968                                 seed = seed.overflowing_mul(0xdeadbeef).0;
3969                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3970                                 seed = seed.overflowing_mul(0xdeadbeef).0;
3971                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3972                                 let amt = seed as u64 % 200_000_000;
3973                                 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3974                                         continue 'load_endpoints;
3975                                 }
3976                         }
3977                 }
3978         }
3979 }
3980
3981 #[cfg(all(test, not(feature = "no_std")))]
3982 pub(crate) mod test_utils {
3983         use std::fs::File;
3984         /// Tries to open a network graph file, or panics with a URL to fetch it.
3985         pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
3986                 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
3987                         .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
3988                         .or_else(|_| { // Fall back to guessing based on the binary location
3989                                 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3990                                 let mut path = std::env::current_exe().unwrap();
3991                                 path.pop(); // lightning-...
3992                                 path.pop(); // deps
3993                                 path.pop(); // debug
3994                                 path.pop(); // target
3995                                 path.push("lightning");
3996                                 path.push("net_graph-2021-05-31.bin");
3997                                 eprintln!("{}", path.to_str().unwrap());
3998                                 File::open(path)
3999                         })
4000                 .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");
4001                 #[cfg(require_route_graph_test)]
4002                 return Ok(res.unwrap());
4003                 #[cfg(not(require_route_graph_test))]
4004                 return res;
4005         }
4006 }
4007
4008 #[cfg(all(test, feature = "unstable", not(feature = "no_std")))]
4009 mod benches {
4010         use super::*;
4011         use util::logger::{Logger, Record};
4012
4013         use test::Bencher;
4014
4015         struct DummyLogger {}
4016         impl Logger for DummyLogger {
4017                 fn log(&self, _record: &Record) {}
4018         }
4019
4020         #[bench]
4021         fn generate_routes(bench: &mut Bencher) {
4022                 let mut d = test_utils::get_route_file().unwrap();
4023                 let graph = NetworkGraph::read(&mut d).unwrap();
4024
4025                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4026                 let mut path_endpoints = Vec::new();
4027                 let mut seed: usize = 0xdeadbeef;
4028                 'load_endpoints: for _ in 0..100 {
4029                         loop {
4030                                 seed *= 0xdeadbeef;
4031                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4032                                 seed *= 0xdeadbeef;
4033                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4034                                 let amt = seed as u64 % 1_000_000;
4035                                 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
4036                                         path_endpoints.push((src, dst, amt));
4037                                         continue 'load_endpoints;
4038                                 }
4039                         }
4040                 }
4041
4042                 // ...then benchmark finding paths between the nodes we learned.
4043                 let mut idx = 0;
4044                 bench.iter(|| {
4045                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4046                         assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
4047                         idx += 1;
4048                 });
4049         }
4050
4051         #[bench]
4052         fn generate_mpp_routes(bench: &mut Bencher) {
4053                 let mut d = test_utils::get_route_file().unwrap();
4054                 let graph = NetworkGraph::read(&mut d).unwrap();
4055
4056                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4057                 let mut path_endpoints = Vec::new();
4058                 let mut seed: usize = 0xdeadbeef;
4059                 'load_endpoints: for _ in 0..100 {
4060                         loop {
4061                                 seed *= 0xdeadbeef;
4062                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4063                                 seed *= 0xdeadbeef;
4064                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4065                                 let amt = seed as u64 % 1_000_000;
4066                                 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4067                                         path_endpoints.push((src, dst, amt));
4068                                         continue 'load_endpoints;
4069                                 }
4070                         }
4071                 }
4072
4073                 // ...then benchmark finding paths between the nodes we learned.
4074                 let mut idx = 0;
4075                 bench.iter(|| {
4076                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4077                         assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());
4078                         idx += 1;
4079                 });
4080         }
4081 }