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