38dc918d48c8cb7311f09fbfccbf217e2bd60f8b
[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                                         } else 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                                         // Means we succesfully traversed from the payer to the payee, now
1050                                         // save this path for the payment route. Also, update the liquidity
1051                                         // remaining on the used hops, so that we take them into account
1052                                         // while looking for more paths.
1053                                         if ordered_hops.last().unwrap().0.pubkey == *payee {
1054                                                 break 'path_walk;
1055                                         }
1056
1057                                         new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
1058                                                 Some(payment_hop) => payment_hop,
1059                                                 // We can't arrive at None because, if we ever add an entry to targets,
1060                                                 // we also fill in the entry in dist (see add_entry!).
1061                                                 None => unreachable!(),
1062                                         };
1063                                         // We "propagate" the fees one hop backward (topologically) here,
1064                                         // so that fees paid for a HTLC forwarding on the current channel are
1065                                         // associated with the previous channel (where they will be subtracted).
1066                                         ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1067                                         ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1068                                         ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1069                                 }
1070                                 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1071                                 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1072                                 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1073
1074                                 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1075                                         ordered_hops.len(), value_contribution_msat, ordered_hops);
1076
1077                                 let mut payment_path = PaymentPath {hops: ordered_hops};
1078
1079                                 // We could have possibly constructed a slightly inconsistent path: since we reduce
1080                                 // value being transferred along the way, we could have violated htlc_minimum_msat
1081                                 // on some channels we already passed (assuming dest->source direction). Here, we
1082                                 // recompute the fees again, so that if that's the case, we match the currently
1083                                 // underpaid htlc_minimum_msat with fees.
1084                                 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1085
1086                                 // Since a path allows to transfer as much value as
1087                                 // the smallest channel it has ("bottleneck"), we should recompute
1088                                 // the fees so sender HTLC don't overpay fees when traversing
1089                                 // larger channels than the bottleneck. This may happen because
1090                                 // when we were selecting those channels we were not aware how much value
1091                                 // this path will transfer, and the relative fee for them
1092                                 // might have been computed considering a larger value.
1093                                 // Remember that we used these channels so that we don't rely
1094                                 // on the same liquidity in future paths.
1095                                 let mut prevented_redundant_path_selection = false;
1096                                 for (payment_hop, _) in payment_path.hops.iter() {
1097                                         let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1098                                         let mut spent_on_hop_msat = value_contribution_msat;
1099                                         let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1100                                         spent_on_hop_msat += next_hops_fee_msat;
1101                                         if spent_on_hop_msat == *channel_liquidity_available_msat {
1102                                                 // If this path used all of this channel's available liquidity, we know
1103                                                 // this path will not be selected again in the next loop iteration.
1104                                                 prevented_redundant_path_selection = true;
1105                                         }
1106                                         *channel_liquidity_available_msat -= spent_on_hop_msat;
1107                                 }
1108                                 if !prevented_redundant_path_selection {
1109                                         // If we weren't capped by hitting a liquidity limit on a channel in the path,
1110                                         // we'll probably end up picking the same path again on the next iteration.
1111                                         // Decrease the available liquidity of a hop in the middle of the path.
1112                                         let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1113                                         log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1114                                         let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1115                                         *victim_liquidity = 0;
1116                                 }
1117
1118                                 // Track the total amount all our collected paths allow to send so that we:
1119                                 // - know when to stop looking for more paths
1120                                 // - know which of the hops are useless considering how much more sats we need
1121                                 //   (contributes_sufficient_value)
1122                                 already_collected_value_msat += value_contribution_msat;
1123
1124                                 payment_paths.push(payment_path);
1125                                 found_new_path = true;
1126                                 break 'path_construction;
1127                         }
1128
1129                         // If we found a path back to the payee, we shouldn't try to process it again. This is
1130                         // the equivalent of the `elem.was_processed` check in
1131                         // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1132                         if pubkey == *payee { continue 'path_construction; }
1133
1134                         // Otherwise, since the current target node is not us,
1135                         // keep "unrolling" the payment graph from payee to payer by
1136                         // finding a way to reach the current target from the payer side.
1137                         match network_nodes.get(&pubkey) {
1138                                 None => {},
1139                                 Some(node) => {
1140                                         add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1141                                 },
1142                         }
1143                 }
1144
1145                 if !allow_mpp {
1146                         // If we don't support MPP, no use trying to gather more value ever.
1147                         break 'paths_collection;
1148                 }
1149
1150                 // Step (4).
1151                 // Stop either when the recommended value is reached or if no new path was found in this
1152                 // iteration.
1153                 // In the latter case, making another path finding attempt won't help,
1154                 // because we deterministically terminated the search due to low liquidity.
1155                 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1156                         log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1157                                 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1158                         break 'paths_collection;
1159                 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1160                         // Further, if this was our first walk of the graph, and we weren't limited by an
1161                         // htlc_minimum_msat, return immediately because this path should suffice. If we were
1162                         // limited by an htlc_minimum_msat value, find another path with a higher value,
1163                         // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1164                         // still keeping a lower total fee than this path.
1165                         if !hit_minimum_limit {
1166                                 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1167                                 break 'paths_collection;
1168                         }
1169                         log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1170                         path_value_msat = recommended_value_msat;
1171                 }
1172         }
1173
1174         // Step (5).
1175         if payment_paths.len() == 0 {
1176                 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1177         }
1178
1179         if already_collected_value_msat < final_value_msat {
1180                 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1181         }
1182
1183         // Sort by total fees and take the best paths.
1184         payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1185         if payment_paths.len() > 50 {
1186                 payment_paths.truncate(50);
1187         }
1188
1189         // Draw multiple sufficient routes by randomly combining the selected paths.
1190         let mut drawn_routes = Vec::new();
1191         for i in 0..payment_paths.len() {
1192                 let mut cur_route = Vec::<PaymentPath>::new();
1193                 let mut aggregate_route_value_msat = 0;
1194
1195                 // Step (6).
1196                 // TODO: real random shuffle
1197                 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1198                 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1199
1200                 // Step (7).
1201                 for payment_path in cur_payment_paths {
1202                         cur_route.push(payment_path.clone());
1203                         aggregate_route_value_msat += payment_path.get_value_msat();
1204                         if aggregate_route_value_msat > final_value_msat {
1205                                 // Last path likely overpaid. Substract it from the most expensive
1206                                 // (in terms of proportional fee) path in this route and recompute fees.
1207                                 // This might be not the most economically efficient way, but fewer paths
1208                                 // also makes routing more reliable.
1209                                 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1210
1211                                 // First, drop some expensive low-value paths entirely if possible.
1212                                 // Sort by value so that we drop many really-low values first, since
1213                                 // fewer paths is better: the payment is less likely to fail.
1214                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1215                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1216                                 cur_route.sort_by_key(|path| path.get_value_msat());
1217                                 // We should make sure that at least 1 path left.
1218                                 let mut paths_left = cur_route.len();
1219                                 cur_route.retain(|path| {
1220                                         if paths_left == 1 {
1221                                                 return true
1222                                         }
1223                                         let mut keep = true;
1224                                         let path_value_msat = path.get_value_msat();
1225                                         if path_value_msat <= overpaid_value_msat {
1226                                                 keep = false;
1227                                                 overpaid_value_msat -= path_value_msat;
1228                                                 paths_left -= 1;
1229                                         }
1230                                         keep
1231                                 });
1232
1233                                 if overpaid_value_msat == 0 {
1234                                         break;
1235                                 }
1236
1237                                 assert!(cur_route.len() > 0);
1238
1239                                 // Step (8).
1240                                 // Now, substract the overpaid value from the most-expensive path.
1241                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1242                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1243                                 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1244                                 let expensive_payment_path = cur_route.first_mut().unwrap();
1245                                 // We already dropped all the small channels above, meaning all the
1246                                 // remaining channels are larger than remaining overpaid_value_msat.
1247                                 // Thus, this can't be negative.
1248                                 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1249                                 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1250                                 break;
1251                         }
1252                 }
1253                 drawn_routes.push(cur_route);
1254         }
1255
1256         // Step (9).
1257         // Select the best route by lowest total fee.
1258         drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1259         let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1260         for payment_path in drawn_routes.first().unwrap() {
1261                 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1262                         RouteHop {
1263                                 pubkey: payment_hop.pubkey,
1264                                 node_features: node_features.clone(),
1265                                 short_channel_id: payment_hop.short_channel_id,
1266                                 channel_features: payment_hop.channel_features.clone(),
1267                                 fee_msat: payment_hop.fee_msat,
1268                                 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1269                         }
1270                 }).collect());
1271         }
1272
1273         if let Some(features) = &payee_features {
1274                 for path in selected_paths.iter_mut() {
1275                         path.last_mut().unwrap().node_features = features.to_context();
1276                 }
1277         }
1278
1279         let route = Route { paths: selected_paths };
1280         log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1281         Ok(route)
1282 }
1283
1284 #[cfg(test)]
1285 mod tests {
1286         use routing::router::{get_route, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1287         use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1288         use chain::transaction::OutPoint;
1289         use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1290         use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1291            NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1292         use ln::channelmanager;
1293         use util::test_utils;
1294         use util::ser::Writeable;
1295
1296         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1297         use bitcoin::hashes::Hash;
1298         use bitcoin::network::constants::Network;
1299         use bitcoin::blockdata::constants::genesis_block;
1300         use bitcoin::blockdata::script::Builder;
1301         use bitcoin::blockdata::opcodes;
1302         use bitcoin::blockdata::transaction::TxOut;
1303
1304         use hex;
1305
1306         use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1307         use bitcoin::secp256k1::{Secp256k1, All};
1308
1309         use prelude::*;
1310         use sync::{self, Arc};
1311
1312         fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1313                         features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1314                 channelmanager::ChannelDetails {
1315                         channel_id: [0; 32],
1316                         counterparty: channelmanager::ChannelCounterparty {
1317                                 features,
1318                                 node_id,
1319                                 unspendable_punishment_reserve: 0,
1320                                 forwarding_info: None,
1321                         },
1322                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1323                         short_channel_id,
1324                         channel_value_satoshis: 0,
1325                         user_id: 0,
1326                         outbound_capacity_msat,
1327                         inbound_capacity_msat: 42,
1328                         unspendable_punishment_reserve: None,
1329                         confirmations_required: None,
1330                         force_close_spend_delay: None,
1331                         is_outbound: true, is_funding_locked: true,
1332                         is_usable: true, is_public: true,
1333                 }
1334         }
1335
1336         // Using the same keys for LN and BTC ids
1337         fn add_channel(
1338                 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1339                 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1340         ) {
1341                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1342                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1343
1344                 let unsigned_announcement = UnsignedChannelAnnouncement {
1345                         features,
1346                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1347                         short_channel_id,
1348                         node_id_1,
1349                         node_id_2,
1350                         bitcoin_key_1: node_id_1,
1351                         bitcoin_key_2: node_id_2,
1352                         excess_data: Vec::new(),
1353                 };
1354
1355                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1356                 let valid_announcement = ChannelAnnouncement {
1357                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1358                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1359                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1360                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1361                         contents: unsigned_announcement.clone(),
1362                 };
1363                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1364                         Ok(res) => assert!(res),
1365                         _ => panic!()
1366                 };
1367         }
1368
1369         fn update_channel(
1370                 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1371                 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1372         ) {
1373                 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1374                 let valid_channel_update = ChannelUpdate {
1375                         signature: secp_ctx.sign(&msghash, node_privkey),
1376                         contents: update.clone()
1377                 };
1378
1379                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1380                         Ok(res) => assert!(res),
1381                         Err(_) => panic!()
1382                 };
1383         }
1384
1385         fn add_or_update_node(
1386                 net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1387                 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1388         ) {
1389                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1390                 let unsigned_announcement = UnsignedNodeAnnouncement {
1391                         features,
1392                         timestamp,
1393                         node_id,
1394                         rgb: [0; 3],
1395                         alias: [0; 32],
1396                         addresses: Vec::new(),
1397                         excess_address_data: Vec::new(),
1398                         excess_data: Vec::new(),
1399                 };
1400                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1401                 let valid_announcement = NodeAnnouncement {
1402                         signature: secp_ctx.sign(&msghash, node_privkey),
1403                         contents: unsigned_announcement.clone()
1404                 };
1405
1406                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1407                         Ok(_) => (),
1408                         Err(_) => panic!()
1409                 };
1410         }
1411
1412         fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1413                 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1414                         SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1415                 }).collect();
1416
1417                 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1418
1419                 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1420                 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1421
1422                 (our_privkey, our_id, privkeys, pubkeys)
1423         }
1424
1425         fn id_to_feature_flags(id: u8) -> Vec<u8> {
1426                 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1427                 // test for it later.
1428                 let idx = (id - 1) * 2 + 1;
1429                 if idx > 8*3 {
1430                         vec![1 << (idx - 8*3), 0, 0, 0]
1431                 } else if idx > 8*2 {
1432                         vec![1 << (idx - 8*2), 0, 0]
1433                 } else if idx > 8*1 {
1434                         vec![1 << (idx - 8*1), 0]
1435                 } else {
1436                         vec![1 << idx]
1437                 }
1438         }
1439
1440         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>) {
1441                 let secp_ctx = Secp256k1::new();
1442                 let logger = Arc::new(test_utils::TestLogger::new());
1443                 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1444                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
1445                 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
1446                 // Build network from our_id to node6:
1447                 //
1448                 //        -1(1)2-  node0  -1(3)2-
1449                 //       /                       \
1450                 // our_id -1(12)2- node7 -1(13)2--- node2
1451                 //       \                       /
1452                 //        -1(2)2-  node1  -1(4)2-
1453                 //
1454                 //
1455                 // chan1  1-to-2: disabled
1456                 // chan1  2-to-1: enabled, 0 fee
1457                 //
1458                 // chan2  1-to-2: enabled, ignored fee
1459                 // chan2  2-to-1: enabled, 0 fee
1460                 //
1461                 // chan3  1-to-2: enabled, 0 fee
1462                 // chan3  2-to-1: enabled, 100 msat fee
1463                 //
1464                 // chan4  1-to-2: enabled, 100% fee
1465                 // chan4  2-to-1: enabled, 0 fee
1466                 //
1467                 // chan12 1-to-2: enabled, ignored fee
1468                 // chan12 2-to-1: enabled, 0 fee
1469                 //
1470                 // chan13 1-to-2: enabled, 200% fee
1471                 // chan13 2-to-1: enabled, 0 fee
1472                 //
1473                 //
1474                 //       -1(5)2- node3 -1(8)2--
1475                 //       |         2          |
1476                 //       |       (11)         |
1477                 //      /          1           \
1478                 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1479                 //      \                      /
1480                 //       -1(7)2- node5 -1(10)2-
1481                 //
1482                 // Channels 5, 8, 9 and 10 are private channels.
1483                 //
1484                 // chan5  1-to-2: enabled, 100 msat fee
1485                 // chan5  2-to-1: enabled, 0 fee
1486                 //
1487                 // chan6  1-to-2: enabled, 0 fee
1488                 // chan6  2-to-1: enabled, 0 fee
1489                 //
1490                 // chan7  1-to-2: enabled, 100% fee
1491                 // chan7  2-to-1: enabled, 0 fee
1492                 //
1493                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
1494                 // chan8  2-to-1: enabled, 0 fee
1495                 //
1496                 // chan9  1-to-2: enabled, 1001 msat fee
1497                 // chan9  2-to-1: enabled, 0 fee
1498                 //
1499                 // chan10 1-to-2: enabled, 0 fee
1500                 // chan10 2-to-1: enabled, 0 fee
1501                 //
1502                 // chan11 1-to-2: enabled, 0 fee
1503                 // chan11 2-to-1: enabled, 0 fee
1504
1505                 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1506
1507                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1508                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1509                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1510                         short_channel_id: 1,
1511                         timestamp: 1,
1512                         flags: 1,
1513                         cltv_expiry_delta: 0,
1514                         htlc_minimum_msat: 0,
1515                         htlc_maximum_msat: OptionalField::Absent,
1516                         fee_base_msat: 0,
1517                         fee_proportional_millionths: 0,
1518                         excess_data: Vec::new()
1519                 });
1520
1521                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1522
1523                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1524                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1525                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1526                         short_channel_id: 2,
1527                         timestamp: 1,
1528                         flags: 0,
1529                         cltv_expiry_delta: u16::max_value(),
1530                         htlc_minimum_msat: 0,
1531                         htlc_maximum_msat: OptionalField::Absent,
1532                         fee_base_msat: u32::max_value(),
1533                         fee_proportional_millionths: u32::max_value(),
1534                         excess_data: Vec::new()
1535                 });
1536                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1537                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1538                         short_channel_id: 2,
1539                         timestamp: 1,
1540                         flags: 1,
1541                         cltv_expiry_delta: 0,
1542                         htlc_minimum_msat: 0,
1543                         htlc_maximum_msat: OptionalField::Absent,
1544                         fee_base_msat: 0,
1545                         fee_proportional_millionths: 0,
1546                         excess_data: Vec::new()
1547                 });
1548
1549                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1550
1551                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1552                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1553                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1554                         short_channel_id: 12,
1555                         timestamp: 1,
1556                         flags: 0,
1557                         cltv_expiry_delta: u16::max_value(),
1558                         htlc_minimum_msat: 0,
1559                         htlc_maximum_msat: OptionalField::Absent,
1560                         fee_base_msat: u32::max_value(),
1561                         fee_proportional_millionths: u32::max_value(),
1562                         excess_data: Vec::new()
1563                 });
1564                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1565                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1566                         short_channel_id: 12,
1567                         timestamp: 1,
1568                         flags: 1,
1569                         cltv_expiry_delta: 0,
1570                         htlc_minimum_msat: 0,
1571                         htlc_maximum_msat: OptionalField::Absent,
1572                         fee_base_msat: 0,
1573                         fee_proportional_millionths: 0,
1574                         excess_data: Vec::new()
1575                 });
1576
1577                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1578
1579                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1580                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1581                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1582                         short_channel_id: 3,
1583                         timestamp: 1,
1584                         flags: 0,
1585                         cltv_expiry_delta: (3 << 8) | 1,
1586                         htlc_minimum_msat: 0,
1587                         htlc_maximum_msat: OptionalField::Absent,
1588                         fee_base_msat: 0,
1589                         fee_proportional_millionths: 0,
1590                         excess_data: Vec::new()
1591                 });
1592                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1593                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1594                         short_channel_id: 3,
1595                         timestamp: 1,
1596                         flags: 1,
1597                         cltv_expiry_delta: (3 << 8) | 2,
1598                         htlc_minimum_msat: 0,
1599                         htlc_maximum_msat: OptionalField::Absent,
1600                         fee_base_msat: 100,
1601                         fee_proportional_millionths: 0,
1602                         excess_data: Vec::new()
1603                 });
1604
1605                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1606                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1607                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1608                         short_channel_id: 4,
1609                         timestamp: 1,
1610                         flags: 0,
1611                         cltv_expiry_delta: (4 << 8) | 1,
1612                         htlc_minimum_msat: 0,
1613                         htlc_maximum_msat: OptionalField::Absent,
1614                         fee_base_msat: 0,
1615                         fee_proportional_millionths: 1000000,
1616                         excess_data: Vec::new()
1617                 });
1618                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1619                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1620                         short_channel_id: 4,
1621                         timestamp: 1,
1622                         flags: 1,
1623                         cltv_expiry_delta: (4 << 8) | 2,
1624                         htlc_minimum_msat: 0,
1625                         htlc_maximum_msat: OptionalField::Absent,
1626                         fee_base_msat: 0,
1627                         fee_proportional_millionths: 0,
1628                         excess_data: Vec::new()
1629                 });
1630
1631                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1632                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1633                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1634                         short_channel_id: 13,
1635                         timestamp: 1,
1636                         flags: 0,
1637                         cltv_expiry_delta: (13 << 8) | 1,
1638                         htlc_minimum_msat: 0,
1639                         htlc_maximum_msat: OptionalField::Absent,
1640                         fee_base_msat: 0,
1641                         fee_proportional_millionths: 2000000,
1642                         excess_data: Vec::new()
1643                 });
1644                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1645                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1646                         short_channel_id: 13,
1647                         timestamp: 1,
1648                         flags: 1,
1649                         cltv_expiry_delta: (13 << 8) | 2,
1650                         htlc_minimum_msat: 0,
1651                         htlc_maximum_msat: OptionalField::Absent,
1652                         fee_base_msat: 0,
1653                         fee_proportional_millionths: 0,
1654                         excess_data: Vec::new()
1655                 });
1656
1657                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1658
1659                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1660                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1661                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1662                         short_channel_id: 6,
1663                         timestamp: 1,
1664                         flags: 0,
1665                         cltv_expiry_delta: (6 << 8) | 1,
1666                         htlc_minimum_msat: 0,
1667                         htlc_maximum_msat: OptionalField::Absent,
1668                         fee_base_msat: 0,
1669                         fee_proportional_millionths: 0,
1670                         excess_data: Vec::new()
1671                 });
1672                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1673                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1674                         short_channel_id: 6,
1675                         timestamp: 1,
1676                         flags: 1,
1677                         cltv_expiry_delta: (6 << 8) | 2,
1678                         htlc_minimum_msat: 0,
1679                         htlc_maximum_msat: OptionalField::Absent,
1680                         fee_base_msat: 0,
1681                         fee_proportional_millionths: 0,
1682                         excess_data: Vec::new(),
1683                 });
1684
1685                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1686                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1687                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1688                         short_channel_id: 11,
1689                         timestamp: 1,
1690                         flags: 0,
1691                         cltv_expiry_delta: (11 << 8) | 1,
1692                         htlc_minimum_msat: 0,
1693                         htlc_maximum_msat: OptionalField::Absent,
1694                         fee_base_msat: 0,
1695                         fee_proportional_millionths: 0,
1696                         excess_data: Vec::new()
1697                 });
1698                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1699                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1700                         short_channel_id: 11,
1701                         timestamp: 1,
1702                         flags: 1,
1703                         cltv_expiry_delta: (11 << 8) | 2,
1704                         htlc_minimum_msat: 0,
1705                         htlc_maximum_msat: OptionalField::Absent,
1706                         fee_base_msat: 0,
1707                         fee_proportional_millionths: 0,
1708                         excess_data: Vec::new()
1709                 });
1710
1711                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1712
1713                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1714
1715                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1716                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1717                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1718                         short_channel_id: 7,
1719                         timestamp: 1,
1720                         flags: 0,
1721                         cltv_expiry_delta: (7 << 8) | 1,
1722                         htlc_minimum_msat: 0,
1723                         htlc_maximum_msat: OptionalField::Absent,
1724                         fee_base_msat: 0,
1725                         fee_proportional_millionths: 1000000,
1726                         excess_data: Vec::new()
1727                 });
1728                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1729                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1730                         short_channel_id: 7,
1731                         timestamp: 1,
1732                         flags: 1,
1733                         cltv_expiry_delta: (7 << 8) | 2,
1734                         htlc_minimum_msat: 0,
1735                         htlc_maximum_msat: OptionalField::Absent,
1736                         fee_base_msat: 0,
1737                         fee_proportional_millionths: 0,
1738                         excess_data: Vec::new()
1739                 });
1740
1741                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1742
1743                 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1744         }
1745
1746         #[test]
1747         fn simple_route_test() {
1748                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1749                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1750
1751                 // Simple route to 2 via 1
1752
1753                 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)) {
1754                         assert_eq!(err, "Cannot send a payment of 0 msat");
1755                 } else { panic!(); }
1756
1757                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1758                 assert_eq!(route.paths[0].len(), 2);
1759
1760                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1761                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1762                 assert_eq!(route.paths[0][0].fee_msat, 100);
1763                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1764                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1765                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1766
1767                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1768                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1769                 assert_eq!(route.paths[0][1].fee_msat, 100);
1770                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1771                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1772                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1773         }
1774
1775         #[test]
1776         fn invalid_first_hop_test() {
1777                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1778                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1779
1780                 // Simple route to 2 via 1
1781
1782                 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1783
1784                 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)) {
1785                         assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1786                 } else { panic!(); }
1787
1788                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1789                 assert_eq!(route.paths[0].len(), 2);
1790         }
1791
1792         #[test]
1793         fn htlc_minimum_test() {
1794                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1795                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1796
1797                 // Simple route to 2 via 1
1798
1799                 // Disable other paths
1800                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1801                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1802                         short_channel_id: 12,
1803                         timestamp: 2,
1804                         flags: 2, // to disable
1805                         cltv_expiry_delta: 0,
1806                         htlc_minimum_msat: 0,
1807                         htlc_maximum_msat: OptionalField::Absent,
1808                         fee_base_msat: 0,
1809                         fee_proportional_millionths: 0,
1810                         excess_data: Vec::new()
1811                 });
1812                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1813                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1814                         short_channel_id: 3,
1815                         timestamp: 2,
1816                         flags: 2, // to disable
1817                         cltv_expiry_delta: 0,
1818                         htlc_minimum_msat: 0,
1819                         htlc_maximum_msat: OptionalField::Absent,
1820                         fee_base_msat: 0,
1821                         fee_proportional_millionths: 0,
1822                         excess_data: Vec::new()
1823                 });
1824                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1825                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1826                         short_channel_id: 13,
1827                         timestamp: 2,
1828                         flags: 2, // to disable
1829                         cltv_expiry_delta: 0,
1830                         htlc_minimum_msat: 0,
1831                         htlc_maximum_msat: OptionalField::Absent,
1832                         fee_base_msat: 0,
1833                         fee_proportional_millionths: 0,
1834                         excess_data: Vec::new()
1835                 });
1836                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1837                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1838                         short_channel_id: 6,
1839                         timestamp: 2,
1840                         flags: 2, // to disable
1841                         cltv_expiry_delta: 0,
1842                         htlc_minimum_msat: 0,
1843                         htlc_maximum_msat: OptionalField::Absent,
1844                         fee_base_msat: 0,
1845                         fee_proportional_millionths: 0,
1846                         excess_data: Vec::new()
1847                 });
1848                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1849                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1850                         short_channel_id: 7,
1851                         timestamp: 2,
1852                         flags: 2, // to disable
1853                         cltv_expiry_delta: 0,
1854                         htlc_minimum_msat: 0,
1855                         htlc_maximum_msat: OptionalField::Absent,
1856                         fee_base_msat: 0,
1857                         fee_proportional_millionths: 0,
1858                         excess_data: Vec::new()
1859                 });
1860
1861                 // Check against amount_to_transfer_over_msat.
1862                 // Set minimal HTLC of 200_000_000 msat.
1863                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1864                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1865                         short_channel_id: 2,
1866                         timestamp: 3,
1867                         flags: 0,
1868                         cltv_expiry_delta: 0,
1869                         htlc_minimum_msat: 200_000_000,
1870                         htlc_maximum_msat: OptionalField::Absent,
1871                         fee_base_msat: 0,
1872                         fee_proportional_millionths: 0,
1873                         excess_data: Vec::new()
1874                 });
1875
1876                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1877                 // be used.
1878                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1879                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1880                         short_channel_id: 4,
1881                         timestamp: 3,
1882                         flags: 0,
1883                         cltv_expiry_delta: 0,
1884                         htlc_minimum_msat: 0,
1885                         htlc_maximum_msat: OptionalField::Present(199_999_999),
1886                         fee_base_msat: 0,
1887                         fee_proportional_millionths: 0,
1888                         excess_data: Vec::new()
1889                 });
1890
1891                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1892                 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)) {
1893                         assert_eq!(err, "Failed to find a path to the given destination");
1894                 } else { panic!(); }
1895
1896                 // Lift the restriction on the first hop.
1897                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1898                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1899                         short_channel_id: 2,
1900                         timestamp: 4,
1901                         flags: 0,
1902                         cltv_expiry_delta: 0,
1903                         htlc_minimum_msat: 0,
1904                         htlc_maximum_msat: OptionalField::Absent,
1905                         fee_base_msat: 0,
1906                         fee_proportional_millionths: 0,
1907                         excess_data: Vec::new()
1908                 });
1909
1910                 // A payment above the minimum should pass
1911                 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();
1912                 assert_eq!(route.paths[0].len(), 2);
1913         }
1914
1915         #[test]
1916         fn htlc_minimum_overpay_test() {
1917                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1918                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1919
1920                 // A route to node#2 via two paths.
1921                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1922                 // Thus, they can't send 60 without overpaying.
1923                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1924                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1925                         short_channel_id: 2,
1926                         timestamp: 2,
1927                         flags: 0,
1928                         cltv_expiry_delta: 0,
1929                         htlc_minimum_msat: 35_000,
1930                         htlc_maximum_msat: OptionalField::Present(40_000),
1931                         fee_base_msat: 0,
1932                         fee_proportional_millionths: 0,
1933                         excess_data: Vec::new()
1934                 });
1935                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1936                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1937                         short_channel_id: 12,
1938                         timestamp: 3,
1939                         flags: 0,
1940                         cltv_expiry_delta: 0,
1941                         htlc_minimum_msat: 35_000,
1942                         htlc_maximum_msat: OptionalField::Present(40_000),
1943                         fee_base_msat: 0,
1944                         fee_proportional_millionths: 0,
1945                         excess_data: Vec::new()
1946                 });
1947
1948                 // Make 0 fee.
1949                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1950                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1951                         short_channel_id: 13,
1952                         timestamp: 2,
1953                         flags: 0,
1954                         cltv_expiry_delta: 0,
1955                         htlc_minimum_msat: 0,
1956                         htlc_maximum_msat: OptionalField::Absent,
1957                         fee_base_msat: 0,
1958                         fee_proportional_millionths: 0,
1959                         excess_data: Vec::new()
1960                 });
1961                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1962                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1963                         short_channel_id: 4,
1964                         timestamp: 2,
1965                         flags: 0,
1966                         cltv_expiry_delta: 0,
1967                         htlc_minimum_msat: 0,
1968                         htlc_maximum_msat: OptionalField::Absent,
1969                         fee_base_msat: 0,
1970                         fee_proportional_millionths: 0,
1971                         excess_data: Vec::new()
1972                 });
1973
1974                 // Disable other paths
1975                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1976                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1977                         short_channel_id: 1,
1978                         timestamp: 3,
1979                         flags: 2, // to disable
1980                         cltv_expiry_delta: 0,
1981                         htlc_minimum_msat: 0,
1982                         htlc_maximum_msat: OptionalField::Absent,
1983                         fee_base_msat: 0,
1984                         fee_proportional_millionths: 0,
1985                         excess_data: Vec::new()
1986                 });
1987
1988                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
1989                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1990                 // Overpay fees to hit htlc_minimum_msat.
1991                 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1992                 // TODO: this could be better balanced to overpay 10k and not 15k.
1993                 assert_eq!(overpaid_fees, 15_000);
1994
1995                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1996                 // while taking even more fee to match htlc_minimum_msat.
1997                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1998                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1999                         short_channel_id: 12,
2000                         timestamp: 4,
2001                         flags: 0,
2002                         cltv_expiry_delta: 0,
2003                         htlc_minimum_msat: 65_000,
2004                         htlc_maximum_msat: OptionalField::Present(80_000),
2005                         fee_base_msat: 0,
2006                         fee_proportional_millionths: 0,
2007                         excess_data: Vec::new()
2008                 });
2009                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2010                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2011                         short_channel_id: 2,
2012                         timestamp: 3,
2013                         flags: 0,
2014                         cltv_expiry_delta: 0,
2015                         htlc_minimum_msat: 0,
2016                         htlc_maximum_msat: OptionalField::Absent,
2017                         fee_base_msat: 0,
2018                         fee_proportional_millionths: 0,
2019                         excess_data: Vec::new()
2020                 });
2021                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2022                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2023                         short_channel_id: 4,
2024                         timestamp: 4,
2025                         flags: 0,
2026                         cltv_expiry_delta: 0,
2027                         htlc_minimum_msat: 0,
2028                         htlc_maximum_msat: OptionalField::Absent,
2029                         fee_base_msat: 0,
2030                         fee_proportional_millionths: 100_000,
2031                         excess_data: Vec::new()
2032                 });
2033
2034                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2035                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
2036                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2037                 assert_eq!(route.paths.len(), 1);
2038                 assert_eq!(route.paths[0][0].short_channel_id, 12);
2039                 let fees = route.paths[0][0].fee_msat;
2040                 assert_eq!(fees, 5_000);
2041
2042                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2043                         Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2044                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2045                 // the other channel.
2046                 assert_eq!(route.paths.len(), 1);
2047                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2048                 let fees = route.paths[0][0].fee_msat;
2049                 assert_eq!(fees, 5_000);
2050         }
2051
2052         #[test]
2053         fn disable_channels_test() {
2054                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2055                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2056
2057                 // // Disable channels 4 and 12 by flags=2
2058                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2059                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2060                         short_channel_id: 4,
2061                         timestamp: 2,
2062                         flags: 2, // to disable
2063                         cltv_expiry_delta: 0,
2064                         htlc_minimum_msat: 0,
2065                         htlc_maximum_msat: OptionalField::Absent,
2066                         fee_base_msat: 0,
2067                         fee_proportional_millionths: 0,
2068                         excess_data: Vec::new()
2069                 });
2070                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2071                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2072                         short_channel_id: 12,
2073                         timestamp: 2,
2074                         flags: 2, // to disable
2075                         cltv_expiry_delta: 0,
2076                         htlc_minimum_msat: 0,
2077                         htlc_maximum_msat: OptionalField::Absent,
2078                         fee_base_msat: 0,
2079                         fee_proportional_millionths: 0,
2080                         excess_data: Vec::new()
2081                 });
2082
2083                 // If all the channels require some features we don't understand, route should fail
2084                 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)) {
2085                         assert_eq!(err, "Failed to find a path to the given destination");
2086                 } else { panic!(); }
2087
2088                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2089                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2090                 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();
2091                 assert_eq!(route.paths[0].len(), 2);
2092
2093                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2094                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2095                 assert_eq!(route.paths[0][0].fee_msat, 200);
2096                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2097                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2098                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2099
2100                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2101                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2102                 assert_eq!(route.paths[0][1].fee_msat, 100);
2103                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2104                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2105                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2106         }
2107
2108         #[test]
2109         fn disable_node_test() {
2110                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2111                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2112
2113                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2114                 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2115                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2116                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2117                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2118
2119                 // If all nodes require some features we don't understand, route should fail
2120                 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)) {
2121                         assert_eq!(err, "Failed to find a path to the given destination");
2122                 } else { panic!(); }
2123
2124                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2125                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2126                 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();
2127                 assert_eq!(route.paths[0].len(), 2);
2128
2129                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2130                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2131                 assert_eq!(route.paths[0][0].fee_msat, 200);
2132                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2133                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2134                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2135
2136                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2137                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2138                 assert_eq!(route.paths[0][1].fee_msat, 100);
2139                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2140                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2141                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2142
2143                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2144                 // naively) assume that the user checked the feature bits on the invoice, which override
2145                 // the node_announcement.
2146         }
2147
2148         #[test]
2149         fn our_chans_test() {
2150                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2151                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2152
2153                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2154                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2155                 assert_eq!(route.paths[0].len(), 3);
2156
2157                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2158                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2159                 assert_eq!(route.paths[0][0].fee_msat, 200);
2160                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2161                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2162                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2163
2164                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2165                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2166                 assert_eq!(route.paths[0][1].fee_msat, 100);
2167                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2168                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2169                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2170
2171                 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2172                 assert_eq!(route.paths[0][2].short_channel_id, 3);
2173                 assert_eq!(route.paths[0][2].fee_msat, 100);
2174                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2175                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2176                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2177
2178                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2179                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2180                 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();
2181                 assert_eq!(route.paths[0].len(), 2);
2182
2183                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2184                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2185                 assert_eq!(route.paths[0][0].fee_msat, 200);
2186                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2187                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2188                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2189
2190                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2191                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2192                 assert_eq!(route.paths[0][1].fee_msat, 100);
2193                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2194                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2195                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2196         }
2197
2198         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2199                 let zero_fees = RoutingFees {
2200                         base_msat: 0,
2201                         proportional_millionths: 0,
2202                 };
2203                 vec![RouteHint(vec![RouteHintHop {
2204                         src_node_id: nodes[3].clone(),
2205                         short_channel_id: 8,
2206                         fees: zero_fees,
2207                         cltv_expiry_delta: (8 << 8) | 1,
2208                         htlc_minimum_msat: None,
2209                         htlc_maximum_msat: None,
2210                 }
2211                 ]), RouteHint(vec![RouteHintHop {
2212                         src_node_id: nodes[4].clone(),
2213                         short_channel_id: 9,
2214                         fees: RoutingFees {
2215                                 base_msat: 1001,
2216                                 proportional_millionths: 0,
2217                         },
2218                         cltv_expiry_delta: (9 << 8) | 1,
2219                         htlc_minimum_msat: None,
2220                         htlc_maximum_msat: None,
2221                 }]), RouteHint(vec![RouteHintHop {
2222                         src_node_id: nodes[5].clone(),
2223                         short_channel_id: 10,
2224                         fees: zero_fees,
2225                         cltv_expiry_delta: (10 << 8) | 1,
2226                         htlc_minimum_msat: None,
2227                         htlc_maximum_msat: None,
2228                 }])]
2229         }
2230
2231         fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2232                 let zero_fees = RoutingFees {
2233                         base_msat: 0,
2234                         proportional_millionths: 0,
2235                 };
2236                 vec![RouteHint(vec![RouteHintHop {
2237                         src_node_id: nodes[2].clone(),
2238                         short_channel_id: 5,
2239                         fees: RoutingFees {
2240                                 base_msat: 100,
2241                                 proportional_millionths: 0,
2242                         },
2243                         cltv_expiry_delta: (5 << 8) | 1,
2244                         htlc_minimum_msat: None,
2245                         htlc_maximum_msat: None,
2246                 }, RouteHintHop {
2247                         src_node_id: nodes[3].clone(),
2248                         short_channel_id: 8,
2249                         fees: zero_fees,
2250                         cltv_expiry_delta: (8 << 8) | 1,
2251                         htlc_minimum_msat: None,
2252                         htlc_maximum_msat: None,
2253                 }
2254                 ]), RouteHint(vec![RouteHintHop {
2255                         src_node_id: nodes[4].clone(),
2256                         short_channel_id: 9,
2257                         fees: RoutingFees {
2258                                 base_msat: 1001,
2259                                 proportional_millionths: 0,
2260                         },
2261                         cltv_expiry_delta: (9 << 8) | 1,
2262                         htlc_minimum_msat: None,
2263                         htlc_maximum_msat: None,
2264                 }]), RouteHint(vec![RouteHintHop {
2265                         src_node_id: nodes[5].clone(),
2266                         short_channel_id: 10,
2267                         fees: zero_fees,
2268                         cltv_expiry_delta: (10 << 8) | 1,
2269                         htlc_minimum_msat: None,
2270                         htlc_maximum_msat: None,
2271                 }])]
2272         }
2273
2274         #[test]
2275         fn partial_route_hint_test() {
2276                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2277                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2278
2279                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2280                 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2281                 // RouteHint may be partially used by the algo to build the best path.
2282
2283                 // First check that last hop can't have its source as the payee.
2284                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2285                         src_node_id: nodes[6],
2286                         short_channel_id: 8,
2287                         fees: RoutingFees {
2288                                 base_msat: 1000,
2289                                 proportional_millionths: 0,
2290                         },
2291                         cltv_expiry_delta: (8 << 8) | 1,
2292                         htlc_minimum_msat: None,
2293                         htlc_maximum_msat: None,
2294                 }]);
2295
2296                 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2297                 invalid_last_hops.push(invalid_last_hop);
2298                 {
2299                         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)) {
2300                                 assert_eq!(err, "Last hop cannot have a payee as a source.");
2301                         } else { panic!(); }
2302                 }
2303
2304                 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();
2305                 assert_eq!(route.paths[0].len(), 5);
2306
2307                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2308                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2309                 assert_eq!(route.paths[0][0].fee_msat, 100);
2310                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2311                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2312                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2313
2314                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2315                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2316                 assert_eq!(route.paths[0][1].fee_msat, 0);
2317                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2318                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2319                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2320
2321                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2322                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2323                 assert_eq!(route.paths[0][2].fee_msat, 0);
2324                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2325                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2326                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2327
2328                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2329                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2330                 assert_eq!(route.paths[0][3].fee_msat, 0);
2331                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2332                 // If we have a peer in the node map, we'll use their features here since we don't have
2333                 // a way of figuring out their features from the invoice:
2334                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2335                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2336
2337                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2338                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2339                 assert_eq!(route.paths[0][4].fee_msat, 100);
2340                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2341                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2342                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2343         }
2344
2345         fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2346                 let zero_fees = RoutingFees {
2347                         base_msat: 0,
2348                         proportional_millionths: 0,
2349                 };
2350                 vec![RouteHint(vec![RouteHintHop {
2351                         src_node_id: nodes[3].clone(),
2352                         short_channel_id: 8,
2353                         fees: zero_fees,
2354                         cltv_expiry_delta: (8 << 8) | 1,
2355                         htlc_minimum_msat: None,
2356                         htlc_maximum_msat: None,
2357                 }]), RouteHint(vec![
2358
2359                 ]), RouteHint(vec![RouteHintHop {
2360                         src_node_id: nodes[5].clone(),
2361                         short_channel_id: 10,
2362                         fees: zero_fees,
2363                         cltv_expiry_delta: (10 << 8) | 1,
2364                         htlc_minimum_msat: None,
2365                         htlc_maximum_msat: None,
2366                 }])]
2367         }
2368
2369         #[test]
2370         fn ignores_empty_last_hops_test() {
2371                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2372                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2373
2374                 // Test handling of an empty RouteHint passed in Invoice.
2375
2376                 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();
2377                 assert_eq!(route.paths[0].len(), 5);
2378
2379                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2380                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2381                 assert_eq!(route.paths[0][0].fee_msat, 100);
2382                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2383                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2384                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2385
2386                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2387                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2388                 assert_eq!(route.paths[0][1].fee_msat, 0);
2389                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2390                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2391                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2392
2393                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2394                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2395                 assert_eq!(route.paths[0][2].fee_msat, 0);
2396                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2397                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2398                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2399
2400                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2401                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2402                 assert_eq!(route.paths[0][3].fee_msat, 0);
2403                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2404                 // If we have a peer in the node map, we'll use their features here since we don't have
2405                 // a way of figuring out their features from the invoice:
2406                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2407                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2408
2409                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2410                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2411                 assert_eq!(route.paths[0][4].fee_msat, 100);
2412                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2413                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2414                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2415         }
2416
2417         fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2418                 let zero_fees = RoutingFees {
2419                         base_msat: 0,
2420                         proportional_millionths: 0,
2421                 };
2422                 vec![RouteHint(vec![RouteHintHop {
2423                         src_node_id: nodes[2].clone(),
2424                         short_channel_id: 5,
2425                         fees: RoutingFees {
2426                                 base_msat: 100,
2427                                 proportional_millionths: 0,
2428                         },
2429                         cltv_expiry_delta: (5 << 8) | 1,
2430                         htlc_minimum_msat: None,
2431                         htlc_maximum_msat: None,
2432                 }, RouteHintHop {
2433                         src_node_id: nodes[3].clone(),
2434                         short_channel_id: 8,
2435                         fees: zero_fees,
2436                         cltv_expiry_delta: (8 << 8) | 1,
2437                         htlc_minimum_msat: None,
2438                         htlc_maximum_msat: None,
2439                 }]), RouteHint(vec![RouteHintHop {
2440                         src_node_id: nodes[5].clone(),
2441                         short_channel_id: 10,
2442                         fees: zero_fees,
2443                         cltv_expiry_delta: (10 << 8) | 1,
2444                         htlc_minimum_msat: None,
2445                         htlc_maximum_msat: None,
2446                 }])]
2447         }
2448
2449         #[test]
2450         fn multi_hint_last_hops_test() {
2451                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2452                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2453                 // Test through channels 2, 3, 5, 8.
2454                 // Test shows that multiple hop hints are considered.
2455
2456                 // Disabling channels 6 & 7 by flags=2
2457                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2458                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2459                         short_channel_id: 6,
2460                         timestamp: 2,
2461                         flags: 2, // to disable
2462                         cltv_expiry_delta: 0,
2463                         htlc_minimum_msat: 0,
2464                         htlc_maximum_msat: OptionalField::Absent,
2465                         fee_base_msat: 0,
2466                         fee_proportional_millionths: 0,
2467                         excess_data: Vec::new()
2468                 });
2469                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2470                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2471                         short_channel_id: 7,
2472                         timestamp: 2,
2473                         flags: 2, // to disable
2474                         cltv_expiry_delta: 0,
2475                         htlc_minimum_msat: 0,
2476                         htlc_maximum_msat: OptionalField::Absent,
2477                         fee_base_msat: 0,
2478                         fee_proportional_millionths: 0,
2479                         excess_data: Vec::new()
2480                 });
2481
2482                 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();
2483                 assert_eq!(route.paths[0].len(), 4);
2484
2485                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2486                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2487                 assert_eq!(route.paths[0][0].fee_msat, 200);
2488                 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2489                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2490                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2491
2492                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2493                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2494                 assert_eq!(route.paths[0][1].fee_msat, 100);
2495                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2496                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2497                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2498
2499                 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2500                 assert_eq!(route.paths[0][2].short_channel_id, 5);
2501                 assert_eq!(route.paths[0][2].fee_msat, 0);
2502                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2503                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2504                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2505
2506                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2507                 assert_eq!(route.paths[0][3].short_channel_id, 8);
2508                 assert_eq!(route.paths[0][3].fee_msat, 100);
2509                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2510                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2511                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2512         }
2513
2514         fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2515                 let zero_fees = RoutingFees {
2516                         base_msat: 0,
2517                         proportional_millionths: 0,
2518                 };
2519                 vec![RouteHint(vec![RouteHintHop {
2520                         src_node_id: nodes[4].clone(),
2521                         short_channel_id: 11,
2522                         fees: zero_fees,
2523                         cltv_expiry_delta: (11 << 8) | 1,
2524                         htlc_minimum_msat: None,
2525                         htlc_maximum_msat: None,
2526                 }, RouteHintHop {
2527                         src_node_id: nodes[3].clone(),
2528                         short_channel_id: 8,
2529                         fees: zero_fees,
2530                         cltv_expiry_delta: (8 << 8) | 1,
2531                         htlc_minimum_msat: None,
2532                         htlc_maximum_msat: None,
2533                 }]), RouteHint(vec![RouteHintHop {
2534                         src_node_id: nodes[4].clone(),
2535                         short_channel_id: 9,
2536                         fees: RoutingFees {
2537                                 base_msat: 1001,
2538                                 proportional_millionths: 0,
2539                         },
2540                         cltv_expiry_delta: (9 << 8) | 1,
2541                         htlc_minimum_msat: None,
2542                         htlc_maximum_msat: None,
2543                 }]), RouteHint(vec![RouteHintHop {
2544                         src_node_id: nodes[5].clone(),
2545                         short_channel_id: 10,
2546                         fees: zero_fees,
2547                         cltv_expiry_delta: (10 << 8) | 1,
2548                         htlc_minimum_msat: None,
2549                         htlc_maximum_msat: None,
2550                 }])]
2551         }
2552
2553         #[test]
2554         fn last_hops_with_public_channel_test() {
2555                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2556                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2557                 // This test shows that public routes can be present in the invoice
2558                 // which would be handled in the same manner.
2559
2560                 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();
2561                 assert_eq!(route.paths[0].len(), 5);
2562
2563                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2564                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2565                 assert_eq!(route.paths[0][0].fee_msat, 100);
2566                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2567                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2568                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2569
2570                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2571                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2572                 assert_eq!(route.paths[0][1].fee_msat, 0);
2573                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2574                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2575                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2576
2577                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2578                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2579                 assert_eq!(route.paths[0][2].fee_msat, 0);
2580                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2581                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2582                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2583
2584                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2585                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2586                 assert_eq!(route.paths[0][3].fee_msat, 0);
2587                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2588                 // If we have a peer in the node map, we'll use their features here since we don't have
2589                 // a way of figuring out their features from the invoice:
2590                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2591                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2592
2593                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2594                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2595                 assert_eq!(route.paths[0][4].fee_msat, 100);
2596                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2597                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2598                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2599         }
2600
2601         #[test]
2602         fn our_chans_last_hop_connect_test() {
2603                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2604                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2605
2606                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2607                 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2608                 let mut last_hops = last_hops(&nodes);
2609                 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();
2610                 assert_eq!(route.paths[0].len(), 2);
2611
2612                 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2613                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2614                 assert_eq!(route.paths[0][0].fee_msat, 0);
2615                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2616                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2617                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2618
2619                 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2620                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2621                 assert_eq!(route.paths[0][1].fee_msat, 100);
2622                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2623                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2624                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2625
2626                 last_hops[0].0[0].fees.base_msat = 1000;
2627
2628                 // Revert to via 6 as the fee on 8 goes up
2629                 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();
2630                 assert_eq!(route.paths[0].len(), 4);
2631
2632                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2633                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2634                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2635                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2636                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2637                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2638
2639                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2640                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2641                 assert_eq!(route.paths[0][1].fee_msat, 100);
2642                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2643                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2644                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2645
2646                 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2647                 assert_eq!(route.paths[0][2].short_channel_id, 7);
2648                 assert_eq!(route.paths[0][2].fee_msat, 0);
2649                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2650                 // If we have a peer in the node map, we'll use their features here since we don't have
2651                 // a way of figuring out their features from the invoice:
2652                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2653                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2654
2655                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2656                 assert_eq!(route.paths[0][3].short_channel_id, 10);
2657                 assert_eq!(route.paths[0][3].fee_msat, 100);
2658                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2659                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2660                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2661
2662                 // ...but still use 8 for larger payments as 6 has a variable feerate
2663                 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();
2664                 assert_eq!(route.paths[0].len(), 5);
2665
2666                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2667                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2668                 assert_eq!(route.paths[0][0].fee_msat, 3000);
2669                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2670                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2671                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2672
2673                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2674                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2675                 assert_eq!(route.paths[0][1].fee_msat, 0);
2676                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2677                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2678                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2679
2680                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2681                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2682                 assert_eq!(route.paths[0][2].fee_msat, 0);
2683                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2684                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2685                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2686
2687                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2688                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2689                 assert_eq!(route.paths[0][3].fee_msat, 1000);
2690                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2691                 // If we have a peer in the node map, we'll use their features here since we don't have
2692                 // a way of figuring out their features from the invoice:
2693                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2694                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2695
2696                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2697                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2698                 assert_eq!(route.paths[0][4].fee_msat, 2000);
2699                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2700                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2701                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2702         }
2703
2704         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> {
2705                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2706                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2707                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2708
2709                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2710                 let last_hops = RouteHint(vec![RouteHintHop {
2711                         src_node_id: middle_node_id,
2712                         short_channel_id: 8,
2713                         fees: RoutingFees {
2714                                 base_msat: 1000,
2715                                 proportional_millionths: last_hop_fee_prop,
2716                         },
2717                         cltv_expiry_delta: (8 << 8) | 1,
2718                         htlc_minimum_msat: None,
2719                         htlc_maximum_msat: last_hop_htlc_max,
2720                 }]);
2721                 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2722                 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()))
2723         }
2724
2725         #[test]
2726         fn unannounced_path_test() {
2727                 // We should be able to send a payment to a destination without any help of a routing graph
2728                 // if we have a channel with a common counterparty that appears in the first and last hop
2729                 // hints.
2730                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2731
2732                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2733                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2734                 assert_eq!(route.paths[0].len(), 2);
2735
2736                 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2737                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2738                 assert_eq!(route.paths[0][0].fee_msat, 1001);
2739                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2740                 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2741                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2742
2743                 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2744                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2745                 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2746                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2747                 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2748                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2749         }
2750
2751         #[test]
2752         fn overflow_unannounced_path_test_liquidity_underflow() {
2753                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2754                 // the last-hop had a fee which overflowed a u64, we'd panic.
2755                 // This was due to us adding the first-hop from us unconditionally, causing us to think
2756                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2757                 // In this test, we previously hit a subtraction underflow due to having less available
2758                 // liquidity at the last hop than 0.
2759                 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());
2760         }
2761
2762         #[test]
2763         fn overflow_unannounced_path_test_feerate_overflow() {
2764                 // This tests for the same case as above, except instead of hitting a subtraction
2765                 // underflow, we hit a case where the fee charged at a hop overflowed.
2766                 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());
2767         }
2768
2769         #[test]
2770         fn available_amount_while_routing_test() {
2771                 // Tests whether we choose the correct available channel amount while routing.
2772
2773                 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2774                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2775
2776                 // We will use a simple single-path route from
2777                 // our node to node2 via node0: channels {1, 3}.
2778
2779                 // First disable all other paths.
2780                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2781                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2782                         short_channel_id: 2,
2783                         timestamp: 2,
2784                         flags: 2,
2785                         cltv_expiry_delta: 0,
2786                         htlc_minimum_msat: 0,
2787                         htlc_maximum_msat: OptionalField::Present(100_000),
2788                         fee_base_msat: 0,
2789                         fee_proportional_millionths: 0,
2790                         excess_data: Vec::new()
2791                 });
2792                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2793                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2794                         short_channel_id: 12,
2795                         timestamp: 2,
2796                         flags: 2,
2797                         cltv_expiry_delta: 0,
2798                         htlc_minimum_msat: 0,
2799                         htlc_maximum_msat: OptionalField::Present(100_000),
2800                         fee_base_msat: 0,
2801                         fee_proportional_millionths: 0,
2802                         excess_data: Vec::new()
2803                 });
2804
2805                 // Make the first channel (#1) very permissive,
2806                 // and we will be testing all limits on the second channel.
2807                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2808                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2809                         short_channel_id: 1,
2810                         timestamp: 2,
2811                         flags: 0,
2812                         cltv_expiry_delta: 0,
2813                         htlc_minimum_msat: 0,
2814                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2815                         fee_base_msat: 0,
2816                         fee_proportional_millionths: 0,
2817                         excess_data: Vec::new()
2818                 });
2819
2820                 // First, let's see if routing works if we have absolutely no idea about the available amount.
2821                 // In this case, it should be set to 250_000 sats.
2822                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2823                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2824                         short_channel_id: 3,
2825                         timestamp: 2,
2826                         flags: 0,
2827                         cltv_expiry_delta: 0,
2828                         htlc_minimum_msat: 0,
2829                         htlc_maximum_msat: OptionalField::Absent,
2830                         fee_base_msat: 0,
2831                         fee_proportional_millionths: 0,
2832                         excess_data: Vec::new()
2833                 });
2834
2835                 {
2836                         // Attempt to route more than available results in a failure.
2837                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2838                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2839                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2840                         } else { panic!(); }
2841                 }
2842
2843                 {
2844                         // Now, attempt to route an exact amount we have should be fine.
2845                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2846                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2847                         assert_eq!(route.paths.len(), 1);
2848                         let path = route.paths.last().unwrap();
2849                         assert_eq!(path.len(), 2);
2850                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2851                         assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2852                 }
2853
2854                 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2855                 // Disable channel #1 and use another first hop.
2856                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2857                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2858                         short_channel_id: 1,
2859                         timestamp: 3,
2860                         flags: 2,
2861                         cltv_expiry_delta: 0,
2862                         htlc_minimum_msat: 0,
2863                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2864                         fee_base_msat: 0,
2865                         fee_proportional_millionths: 0,
2866                         excess_data: Vec::new()
2867                 });
2868
2869                 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2870                 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2871
2872                 {
2873                         // Attempt to route more than available results in a failure.
2874                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2875                                         Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2876                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2877                         } else { panic!(); }
2878                 }
2879
2880                 {
2881                         // Now, attempt to route an exact amount we have should be fine.
2882                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2883                                 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2884                         assert_eq!(route.paths.len(), 1);
2885                         let path = route.paths.last().unwrap();
2886                         assert_eq!(path.len(), 2);
2887                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2888                         assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2889                 }
2890
2891                 // Enable channel #1 back.
2892                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2893                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2894                         short_channel_id: 1,
2895                         timestamp: 4,
2896                         flags: 0,
2897                         cltv_expiry_delta: 0,
2898                         htlc_minimum_msat: 0,
2899                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2900                         fee_base_msat: 0,
2901                         fee_proportional_millionths: 0,
2902                         excess_data: Vec::new()
2903                 });
2904
2905
2906                 // Now let's see if routing works if we know only htlc_maximum_msat.
2907                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2908                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2909                         short_channel_id: 3,
2910                         timestamp: 3,
2911                         flags: 0,
2912                         cltv_expiry_delta: 0,
2913                         htlc_minimum_msat: 0,
2914                         htlc_maximum_msat: OptionalField::Present(15_000),
2915                         fee_base_msat: 0,
2916                         fee_proportional_millionths: 0,
2917                         excess_data: Vec::new()
2918                 });
2919
2920                 {
2921                         // Attempt to route more than available results in a failure.
2922                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2923                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2924                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2925                         } else { panic!(); }
2926                 }
2927
2928                 {
2929                         // Now, attempt to route an exact amount we have should be fine.
2930                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2931                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2932                         assert_eq!(route.paths.len(), 1);
2933                         let path = route.paths.last().unwrap();
2934                         assert_eq!(path.len(), 2);
2935                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2936                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2937                 }
2938
2939                 // Now let's see if routing works if we know only capacity from the UTXO.
2940
2941                 // We can't change UTXO capacity on the fly, so we'll disable
2942                 // the existing channel and add another one with the capacity we need.
2943                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2944                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2945                         short_channel_id: 3,
2946                         timestamp: 4,
2947                         flags: 2,
2948                         cltv_expiry_delta: 0,
2949                         htlc_minimum_msat: 0,
2950                         htlc_maximum_msat: OptionalField::Absent,
2951                         fee_base_msat: 0,
2952                         fee_proportional_millionths: 0,
2953                         excess_data: Vec::new()
2954                 });
2955
2956                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2957                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2958                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2959                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2960                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2961
2962                 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2963                 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2964
2965                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2966                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2967                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2968                         short_channel_id: 333,
2969                         timestamp: 1,
2970                         flags: 0,
2971                         cltv_expiry_delta: (3 << 8) | 1,
2972                         htlc_minimum_msat: 0,
2973                         htlc_maximum_msat: OptionalField::Absent,
2974                         fee_base_msat: 0,
2975                         fee_proportional_millionths: 0,
2976                         excess_data: Vec::new()
2977                 });
2978                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2979                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2980                         short_channel_id: 333,
2981                         timestamp: 1,
2982                         flags: 1,
2983                         cltv_expiry_delta: (3 << 8) | 2,
2984                         htlc_minimum_msat: 0,
2985                         htlc_maximum_msat: OptionalField::Absent,
2986                         fee_base_msat: 100,
2987                         fee_proportional_millionths: 0,
2988                         excess_data: Vec::new()
2989                 });
2990
2991                 {
2992                         // Attempt to route more than available results in a failure.
2993                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
2994                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2995                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2996                         } else { panic!(); }
2997                 }
2998
2999                 {
3000                         // Now, attempt to route an exact amount we have should be fine.
3001                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3002                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
3003                         assert_eq!(route.paths.len(), 1);
3004                         let path = route.paths.last().unwrap();
3005                         assert_eq!(path.len(), 2);
3006                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3007                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
3008                 }
3009
3010                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3011                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3012                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3013                         short_channel_id: 333,
3014                         timestamp: 6,
3015                         flags: 0,
3016                         cltv_expiry_delta: 0,
3017                         htlc_minimum_msat: 0,
3018                         htlc_maximum_msat: OptionalField::Present(10_000),
3019                         fee_base_msat: 0,
3020                         fee_proportional_millionths: 0,
3021                         excess_data: Vec::new()
3022                 });
3023
3024                 {
3025                         // Attempt to route more than available results in a failure.
3026                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3027                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
3028                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3029                         } else { panic!(); }
3030                 }
3031
3032                 {
3033                         // Now, attempt to route an exact amount we have should be fine.
3034                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3035                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
3036                         assert_eq!(route.paths.len(), 1);
3037                         let path = route.paths.last().unwrap();
3038                         assert_eq!(path.len(), 2);
3039                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3040                         assert_eq!(path.last().unwrap().fee_msat, 10_000);
3041                 }
3042         }
3043
3044         #[test]
3045         fn available_liquidity_last_hop_test() {
3046                 // Check that available liquidity properly limits the path even when only
3047                 // one of the latter hops is limited.
3048                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3049                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3050
3051                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3052                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3053                 // Total capacity: 50 sats.
3054
3055                 // Disable other potential paths.
3056                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3057                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3058                         short_channel_id: 2,
3059                         timestamp: 2,
3060                         flags: 2,
3061                         cltv_expiry_delta: 0,
3062                         htlc_minimum_msat: 0,
3063                         htlc_maximum_msat: OptionalField::Present(100_000),
3064                         fee_base_msat: 0,
3065                         fee_proportional_millionths: 0,
3066                         excess_data: Vec::new()
3067                 });
3068                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3069                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3070                         short_channel_id: 7,
3071                         timestamp: 2,
3072                         flags: 2,
3073                         cltv_expiry_delta: 0,
3074                         htlc_minimum_msat: 0,
3075                         htlc_maximum_msat: OptionalField::Present(100_000),
3076                         fee_base_msat: 0,
3077                         fee_proportional_millionths: 0,
3078                         excess_data: Vec::new()
3079                 });
3080
3081                 // Limit capacities
3082
3083                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3084                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3085                         short_channel_id: 12,
3086                         timestamp: 2,
3087                         flags: 0,
3088                         cltv_expiry_delta: 0,
3089                         htlc_minimum_msat: 0,
3090                         htlc_maximum_msat: OptionalField::Present(100_000),
3091                         fee_base_msat: 0,
3092                         fee_proportional_millionths: 0,
3093                         excess_data: Vec::new()
3094                 });
3095                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3096                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3097                         short_channel_id: 13,
3098                         timestamp: 2,
3099                         flags: 0,
3100                         cltv_expiry_delta: 0,
3101                         htlc_minimum_msat: 0,
3102                         htlc_maximum_msat: OptionalField::Present(100_000),
3103                         fee_base_msat: 0,
3104                         fee_proportional_millionths: 0,
3105                         excess_data: Vec::new()
3106                 });
3107
3108                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3109                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3110                         short_channel_id: 6,
3111                         timestamp: 2,
3112                         flags: 0,
3113                         cltv_expiry_delta: 0,
3114                         htlc_minimum_msat: 0,
3115                         htlc_maximum_msat: OptionalField::Present(50_000),
3116                         fee_base_msat: 0,
3117                         fee_proportional_millionths: 0,
3118                         excess_data: Vec::new()
3119                 });
3120                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3121                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3122                         short_channel_id: 11,
3123                         timestamp: 2,
3124                         flags: 0,
3125                         cltv_expiry_delta: 0,
3126                         htlc_minimum_msat: 0,
3127                         htlc_maximum_msat: OptionalField::Present(100_000),
3128                         fee_base_msat: 0,
3129                         fee_proportional_millionths: 0,
3130                         excess_data: Vec::new()
3131                 });
3132                 {
3133                         // Attempt to route more than available results in a failure.
3134                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3135                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
3136                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3137                         } else { panic!(); }
3138                 }
3139
3140                 {
3141                         // Now, attempt to route 49 sats (just a bit below the capacity).
3142                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3143                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
3144                         assert_eq!(route.paths.len(), 1);
3145                         let mut total_amount_paid_msat = 0;
3146                         for path in &route.paths {
3147                                 assert_eq!(path.len(), 4);
3148                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3149                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3150                         }
3151                         assert_eq!(total_amount_paid_msat, 49_000);
3152                 }
3153
3154                 {
3155                         // Attempt to route an exact amount is also fine
3156                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3157                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3158                         assert_eq!(route.paths.len(), 1);
3159                         let mut total_amount_paid_msat = 0;
3160                         for path in &route.paths {
3161                                 assert_eq!(path.len(), 4);
3162                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3163                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3164                         }
3165                         assert_eq!(total_amount_paid_msat, 50_000);
3166                 }
3167         }
3168
3169         #[test]
3170         fn ignore_fee_first_hop_test() {
3171                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3172                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3173
3174                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3175                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3176                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3177                         short_channel_id: 1,
3178                         timestamp: 2,
3179                         flags: 0,
3180                         cltv_expiry_delta: 0,
3181                         htlc_minimum_msat: 0,
3182                         htlc_maximum_msat: OptionalField::Present(100_000),
3183                         fee_base_msat: 1_000_000,
3184                         fee_proportional_millionths: 0,
3185                         excess_data: Vec::new()
3186                 });
3187                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3188                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3189                         short_channel_id: 3,
3190                         timestamp: 2,
3191                         flags: 0,
3192                         cltv_expiry_delta: 0,
3193                         htlc_minimum_msat: 0,
3194                         htlc_maximum_msat: OptionalField::Present(50_000),
3195                         fee_base_msat: 0,
3196                         fee_proportional_millionths: 0,
3197                         excess_data: Vec::new()
3198                 });
3199
3200                 {
3201                         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();
3202                         assert_eq!(route.paths.len(), 1);
3203                         let mut total_amount_paid_msat = 0;
3204                         for path in &route.paths {
3205                                 assert_eq!(path.len(), 2);
3206                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3207                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3208                         }
3209                         assert_eq!(total_amount_paid_msat, 50_000);
3210                 }
3211         }
3212
3213         #[test]
3214         fn simple_mpp_route_test() {
3215                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3216                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3217
3218                 // We need a route consisting of 3 paths:
3219                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3220                 // To achieve this, the amount being transferred should be around
3221                 // the total capacity of these 3 paths.
3222
3223                 // First, we set limits on these (previously unlimited) channels.
3224                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3225
3226                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3227                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3228                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3229                         short_channel_id: 1,
3230                         timestamp: 2,
3231                         flags: 0,
3232                         cltv_expiry_delta: 0,
3233                         htlc_minimum_msat: 0,
3234                         htlc_maximum_msat: OptionalField::Present(100_000),
3235                         fee_base_msat: 0,
3236                         fee_proportional_millionths: 0,
3237                         excess_data: Vec::new()
3238                 });
3239                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3240                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3241                         short_channel_id: 3,
3242                         timestamp: 2,
3243                         flags: 0,
3244                         cltv_expiry_delta: 0,
3245                         htlc_minimum_msat: 0,
3246                         htlc_maximum_msat: OptionalField::Present(50_000),
3247                         fee_base_msat: 0,
3248                         fee_proportional_millionths: 0,
3249                         excess_data: Vec::new()
3250                 });
3251
3252                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3253                 // (total limit 60).
3254                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3255                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3256                         short_channel_id: 12,
3257                         timestamp: 2,
3258                         flags: 0,
3259                         cltv_expiry_delta: 0,
3260                         htlc_minimum_msat: 0,
3261                         htlc_maximum_msat: OptionalField::Present(60_000),
3262                         fee_base_msat: 0,
3263                         fee_proportional_millionths: 0,
3264                         excess_data: Vec::new()
3265                 });
3266                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3267                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3268                         short_channel_id: 13,
3269                         timestamp: 2,
3270                         flags: 0,
3271                         cltv_expiry_delta: 0,
3272                         htlc_minimum_msat: 0,
3273                         htlc_maximum_msat: OptionalField::Present(60_000),
3274                         fee_base_msat: 0,
3275                         fee_proportional_millionths: 0,
3276                         excess_data: Vec::new()
3277                 });
3278
3279                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3280                 // (total capacity 180 sats).
3281                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3282                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3283                         short_channel_id: 2,
3284                         timestamp: 2,
3285                         flags: 0,
3286                         cltv_expiry_delta: 0,
3287                         htlc_minimum_msat: 0,
3288                         htlc_maximum_msat: OptionalField::Present(200_000),
3289                         fee_base_msat: 0,
3290                         fee_proportional_millionths: 0,
3291                         excess_data: Vec::new()
3292                 });
3293                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3294                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3295                         short_channel_id: 4,
3296                         timestamp: 2,
3297                         flags: 0,
3298                         cltv_expiry_delta: 0,
3299                         htlc_minimum_msat: 0,
3300                         htlc_maximum_msat: OptionalField::Present(180_000),
3301                         fee_base_msat: 0,
3302                         fee_proportional_millionths: 0,
3303                         excess_data: Vec::new()
3304                 });
3305
3306                 {
3307                         // Attempt to route more than available results in a failure.
3308                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph,
3309                                         &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
3310                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3311                         } else { panic!(); }
3312                 }
3313
3314                 {
3315                         // Now, attempt to route 250 sats (just a bit below the capacity).
3316                         // Our algorithm should provide us with these 3 paths.
3317                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3318                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
3319                         assert_eq!(route.paths.len(), 3);
3320                         let mut total_amount_paid_msat = 0;
3321                         for path in &route.paths {
3322                                 assert_eq!(path.len(), 2);
3323                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3324                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3325                         }
3326                         assert_eq!(total_amount_paid_msat, 250_000);
3327                 }
3328
3329                 {
3330                         // Attempt to route an exact amount is also fine
3331                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3332                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
3333                         assert_eq!(route.paths.len(), 3);
3334                         let mut total_amount_paid_msat = 0;
3335                         for path in &route.paths {
3336                                 assert_eq!(path.len(), 2);
3337                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3338                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3339                         }
3340                         assert_eq!(total_amount_paid_msat, 290_000);
3341                 }
3342         }
3343
3344         #[test]
3345         fn long_mpp_route_test() {
3346                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3347                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3348
3349                 // We need a route consisting of 3 paths:
3350                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3351                 // Note that these paths overlap (channels 5, 12, 13).
3352                 // We will route 300 sats.
3353                 // Each path will have 100 sats capacity, those channels which
3354                 // are used twice will have 200 sats capacity.
3355
3356                 // Disable other potential paths.
3357                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3358                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3359                         short_channel_id: 2,
3360                         timestamp: 2,
3361                         flags: 2,
3362                         cltv_expiry_delta: 0,
3363                         htlc_minimum_msat: 0,
3364                         htlc_maximum_msat: OptionalField::Present(100_000),
3365                         fee_base_msat: 0,
3366                         fee_proportional_millionths: 0,
3367                         excess_data: Vec::new()
3368                 });
3369                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3370                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3371                         short_channel_id: 7,
3372                         timestamp: 2,
3373                         flags: 2,
3374                         cltv_expiry_delta: 0,
3375                         htlc_minimum_msat: 0,
3376                         htlc_maximum_msat: OptionalField::Present(100_000),
3377                         fee_base_msat: 0,
3378                         fee_proportional_millionths: 0,
3379                         excess_data: Vec::new()
3380                 });
3381
3382                 // Path via {node0, node2} is channels {1, 3, 5}.
3383                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3384                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3385                         short_channel_id: 1,
3386                         timestamp: 2,
3387                         flags: 0,
3388                         cltv_expiry_delta: 0,
3389                         htlc_minimum_msat: 0,
3390                         htlc_maximum_msat: OptionalField::Present(100_000),
3391                         fee_base_msat: 0,
3392                         fee_proportional_millionths: 0,
3393                         excess_data: Vec::new()
3394                 });
3395                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3396                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3397                         short_channel_id: 3,
3398                         timestamp: 2,
3399                         flags: 0,
3400                         cltv_expiry_delta: 0,
3401                         htlc_minimum_msat: 0,
3402                         htlc_maximum_msat: OptionalField::Present(100_000),
3403                         fee_base_msat: 0,
3404                         fee_proportional_millionths: 0,
3405                         excess_data: Vec::new()
3406                 });
3407
3408                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3409                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3410                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3411                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3412                         short_channel_id: 5,
3413                         timestamp: 2,
3414                         flags: 0,
3415                         cltv_expiry_delta: 0,
3416                         htlc_minimum_msat: 0,
3417                         htlc_maximum_msat: OptionalField::Present(200_000),
3418                         fee_base_msat: 0,
3419                         fee_proportional_millionths: 0,
3420                         excess_data: Vec::new()
3421                 });
3422
3423                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3424                 // Add 100 sats to the capacities of {12, 13}, because these channels
3425                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3426                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3427                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3428                         short_channel_id: 12,
3429                         timestamp: 2,
3430                         flags: 0,
3431                         cltv_expiry_delta: 0,
3432                         htlc_minimum_msat: 0,
3433                         htlc_maximum_msat: OptionalField::Present(200_000),
3434                         fee_base_msat: 0,
3435                         fee_proportional_millionths: 0,
3436                         excess_data: Vec::new()
3437                 });
3438                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3439                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3440                         short_channel_id: 13,
3441                         timestamp: 2,
3442                         flags: 0,
3443                         cltv_expiry_delta: 0,
3444                         htlc_minimum_msat: 0,
3445                         htlc_maximum_msat: OptionalField::Present(200_000),
3446                         fee_base_msat: 0,
3447                         fee_proportional_millionths: 0,
3448                         excess_data: Vec::new()
3449                 });
3450
3451                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3452                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3453                         short_channel_id: 6,
3454                         timestamp: 2,
3455                         flags: 0,
3456                         cltv_expiry_delta: 0,
3457                         htlc_minimum_msat: 0,
3458                         htlc_maximum_msat: OptionalField::Present(100_000),
3459                         fee_base_msat: 0,
3460                         fee_proportional_millionths: 0,
3461                         excess_data: Vec::new()
3462                 });
3463                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3464                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3465                         short_channel_id: 11,
3466                         timestamp: 2,
3467                         flags: 0,
3468                         cltv_expiry_delta: 0,
3469                         htlc_minimum_msat: 0,
3470                         htlc_maximum_msat: OptionalField::Present(100_000),
3471                         fee_base_msat: 0,
3472                         fee_proportional_millionths: 0,
3473                         excess_data: Vec::new()
3474                 });
3475
3476                 // Path via {node7, node2} is channels {12, 13, 5}.
3477                 // We already limited them to 200 sats (they are used twice for 100 sats).
3478                 // Nothing to do here.
3479
3480                 {
3481                         // Attempt to route more than available results in a failure.
3482                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3483                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3484                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3485                         } else { panic!(); }
3486                 }
3487
3488                 {
3489                         // Now, attempt to route 300 sats (exact amount we can route).
3490                         // Our algorithm should provide us with these 3 paths, 100 sats each.
3491                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3492                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3493                         assert_eq!(route.paths.len(), 3);
3494
3495                         let mut total_amount_paid_msat = 0;
3496                         for path in &route.paths {
3497                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3498                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3499                         }
3500                         assert_eq!(total_amount_paid_msat, 300_000);
3501                 }
3502
3503         }
3504
3505         #[test]
3506         fn mpp_cheaper_route_test() {
3507                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3508                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3509
3510                 // This test checks that if we have two cheaper paths and one more expensive path,
3511                 // so that liquidity-wise any 2 of 3 combination is sufficient,
3512                 // two cheaper paths will be taken.
3513                 // These paths have equal available liquidity.
3514
3515                 // We need a combination of 3 paths:
3516                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3517                 // Note that these paths overlap (channels 5, 12, 13).
3518                 // Each path will have 100 sats capacity, those channels which
3519                 // are used twice will have 200 sats capacity.
3520
3521                 // Disable other potential paths.
3522                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3523                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3524                         short_channel_id: 2,
3525                         timestamp: 2,
3526                         flags: 2,
3527                         cltv_expiry_delta: 0,
3528                         htlc_minimum_msat: 0,
3529                         htlc_maximum_msat: OptionalField::Present(100_000),
3530                         fee_base_msat: 0,
3531                         fee_proportional_millionths: 0,
3532                         excess_data: Vec::new()
3533                 });
3534                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3535                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3536                         short_channel_id: 7,
3537                         timestamp: 2,
3538                         flags: 2,
3539                         cltv_expiry_delta: 0,
3540                         htlc_minimum_msat: 0,
3541                         htlc_maximum_msat: OptionalField::Present(100_000),
3542                         fee_base_msat: 0,
3543                         fee_proportional_millionths: 0,
3544                         excess_data: Vec::new()
3545                 });
3546
3547                 // Path via {node0, node2} is channels {1, 3, 5}.
3548                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3549                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3550                         short_channel_id: 1,
3551                         timestamp: 2,
3552                         flags: 0,
3553                         cltv_expiry_delta: 0,
3554                         htlc_minimum_msat: 0,
3555                         htlc_maximum_msat: OptionalField::Present(100_000),
3556                         fee_base_msat: 0,
3557                         fee_proportional_millionths: 0,
3558                         excess_data: Vec::new()
3559                 });
3560                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3561                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3562                         short_channel_id: 3,
3563                         timestamp: 2,
3564                         flags: 0,
3565                         cltv_expiry_delta: 0,
3566                         htlc_minimum_msat: 0,
3567                         htlc_maximum_msat: OptionalField::Present(100_000),
3568                         fee_base_msat: 0,
3569                         fee_proportional_millionths: 0,
3570                         excess_data: Vec::new()
3571                 });
3572
3573                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3574                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3575                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3576                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3577                         short_channel_id: 5,
3578                         timestamp: 2,
3579                         flags: 0,
3580                         cltv_expiry_delta: 0,
3581                         htlc_minimum_msat: 0,
3582                         htlc_maximum_msat: OptionalField::Present(200_000),
3583                         fee_base_msat: 0,
3584                         fee_proportional_millionths: 0,
3585                         excess_data: Vec::new()
3586                 });
3587
3588                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3589                 // Add 100 sats to the capacities of {12, 13}, because these channels
3590                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3591                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3592                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3593                         short_channel_id: 12,
3594                         timestamp: 2,
3595                         flags: 0,
3596                         cltv_expiry_delta: 0,
3597                         htlc_minimum_msat: 0,
3598                         htlc_maximum_msat: OptionalField::Present(200_000),
3599                         fee_base_msat: 0,
3600                         fee_proportional_millionths: 0,
3601                         excess_data: Vec::new()
3602                 });
3603                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3604                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3605                         short_channel_id: 13,
3606                         timestamp: 2,
3607                         flags: 0,
3608                         cltv_expiry_delta: 0,
3609                         htlc_minimum_msat: 0,
3610                         htlc_maximum_msat: OptionalField::Present(200_000),
3611                         fee_base_msat: 0,
3612                         fee_proportional_millionths: 0,
3613                         excess_data: Vec::new()
3614                 });
3615
3616                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3617                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3618                         short_channel_id: 6,
3619                         timestamp: 2,
3620                         flags: 0,
3621                         cltv_expiry_delta: 0,
3622                         htlc_minimum_msat: 0,
3623                         htlc_maximum_msat: OptionalField::Present(100_000),
3624                         fee_base_msat: 1_000,
3625                         fee_proportional_millionths: 0,
3626                         excess_data: Vec::new()
3627                 });
3628                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3629                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3630                         short_channel_id: 11,
3631                         timestamp: 2,
3632                         flags: 0,
3633                         cltv_expiry_delta: 0,
3634                         htlc_minimum_msat: 0,
3635                         htlc_maximum_msat: OptionalField::Present(100_000),
3636                         fee_base_msat: 0,
3637                         fee_proportional_millionths: 0,
3638                         excess_data: Vec::new()
3639                 });
3640
3641                 // Path via {node7, node2} is channels {12, 13, 5}.
3642                 // We already limited them to 200 sats (they are used twice for 100 sats).
3643                 // Nothing to do here.
3644
3645                 {
3646                         // Now, attempt to route 180 sats.
3647                         // Our algorithm should provide us with these 2 paths.
3648                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3649                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3650                         assert_eq!(route.paths.len(), 2);
3651
3652                         let mut total_value_transferred_msat = 0;
3653                         let mut total_paid_msat = 0;
3654                         for path in &route.paths {
3655                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3656                                 total_value_transferred_msat += path.last().unwrap().fee_msat;
3657                                 for hop in path {
3658                                         total_paid_msat += hop.fee_msat;
3659                                 }
3660                         }
3661                         // If we paid fee, this would be higher.
3662                         assert_eq!(total_value_transferred_msat, 180_000);
3663                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3664                         assert_eq!(total_fees_paid, 0);
3665                 }
3666         }
3667
3668         #[test]
3669         fn fees_on_mpp_route_test() {
3670                 // This test makes sure that MPP algorithm properly takes into account
3671                 // fees charged on the channels, by making the fees impactful:
3672                 // if the fee is not properly accounted for, the behavior is different.
3673                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3674                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3675
3676                 // We need a route consisting of 2 paths:
3677                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3678                 // We will route 200 sats, Each path will have 100 sats capacity.
3679
3680                 // This test is not particularly stable: e.g.,
3681                 // there's a way to route via {node0, node2, node4}.
3682                 // It works while pathfinding is deterministic, but can be broken otherwise.
3683                 // It's fine to ignore this concern for now.
3684
3685                 // Disable other potential paths.
3686                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3687                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3688                         short_channel_id: 2,
3689                         timestamp: 2,
3690                         flags: 2,
3691                         cltv_expiry_delta: 0,
3692                         htlc_minimum_msat: 0,
3693                         htlc_maximum_msat: OptionalField::Present(100_000),
3694                         fee_base_msat: 0,
3695                         fee_proportional_millionths: 0,
3696                         excess_data: Vec::new()
3697                 });
3698
3699                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3700                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3701                         short_channel_id: 7,
3702                         timestamp: 2,
3703                         flags: 2,
3704                         cltv_expiry_delta: 0,
3705                         htlc_minimum_msat: 0,
3706                         htlc_maximum_msat: OptionalField::Present(100_000),
3707                         fee_base_msat: 0,
3708                         fee_proportional_millionths: 0,
3709                         excess_data: Vec::new()
3710                 });
3711
3712                 // Path via {node0, node2} is channels {1, 3, 5}.
3713                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3714                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3715                         short_channel_id: 1,
3716                         timestamp: 2,
3717                         flags: 0,
3718                         cltv_expiry_delta: 0,
3719                         htlc_minimum_msat: 0,
3720                         htlc_maximum_msat: OptionalField::Present(100_000),
3721                         fee_base_msat: 0,
3722                         fee_proportional_millionths: 0,
3723                         excess_data: Vec::new()
3724                 });
3725                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3726                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3727                         short_channel_id: 3,
3728                         timestamp: 2,
3729                         flags: 0,
3730                         cltv_expiry_delta: 0,
3731                         htlc_minimum_msat: 0,
3732                         htlc_maximum_msat: OptionalField::Present(100_000),
3733                         fee_base_msat: 0,
3734                         fee_proportional_millionths: 0,
3735                         excess_data: Vec::new()
3736                 });
3737
3738                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3739                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3740                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3741                         short_channel_id: 5,
3742                         timestamp: 2,
3743                         flags: 0,
3744                         cltv_expiry_delta: 0,
3745                         htlc_minimum_msat: 0,
3746                         htlc_maximum_msat: OptionalField::Present(100_000),
3747                         fee_base_msat: 0,
3748                         fee_proportional_millionths: 0,
3749                         excess_data: Vec::new()
3750                 });
3751
3752                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3753                 // All channels should be 100 sats capacity. But for the fee experiment,
3754                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3755                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3756                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3757                 // so no matter how large are other channels,
3758                 // the whole path will be limited by 100 sats with just these 2 conditions:
3759                 // - channel 12 capacity is 250 sats
3760                 // - fee for channel 6 is 150 sats
3761                 // Let's test this by enforcing these 2 conditions and removing other limits.
3762                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3763                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3764                         short_channel_id: 12,
3765                         timestamp: 2,
3766                         flags: 0,
3767                         cltv_expiry_delta: 0,
3768                         htlc_minimum_msat: 0,
3769                         htlc_maximum_msat: OptionalField::Present(250_000),
3770                         fee_base_msat: 0,
3771                         fee_proportional_millionths: 0,
3772                         excess_data: Vec::new()
3773                 });
3774                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3775                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3776                         short_channel_id: 13,
3777                         timestamp: 2,
3778                         flags: 0,
3779                         cltv_expiry_delta: 0,
3780                         htlc_minimum_msat: 0,
3781                         htlc_maximum_msat: OptionalField::Absent,
3782                         fee_base_msat: 0,
3783                         fee_proportional_millionths: 0,
3784                         excess_data: Vec::new()
3785                 });
3786
3787                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3788                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3789                         short_channel_id: 6,
3790                         timestamp: 2,
3791                         flags: 0,
3792                         cltv_expiry_delta: 0,
3793                         htlc_minimum_msat: 0,
3794                         htlc_maximum_msat: OptionalField::Absent,
3795                         fee_base_msat: 150_000,
3796                         fee_proportional_millionths: 0,
3797                         excess_data: Vec::new()
3798                 });
3799                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3800                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3801                         short_channel_id: 11,
3802                         timestamp: 2,
3803                         flags: 0,
3804                         cltv_expiry_delta: 0,
3805                         htlc_minimum_msat: 0,
3806                         htlc_maximum_msat: OptionalField::Absent,
3807                         fee_base_msat: 0,
3808                         fee_proportional_millionths: 0,
3809                         excess_data: Vec::new()
3810                 });
3811
3812                 {
3813                         // Attempt to route more than available results in a failure.
3814                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3815                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3816                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3817                         } else { panic!(); }
3818                 }
3819
3820                 {
3821                         // Now, attempt to route 200 sats (exact amount we can route).
3822                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[3],
3823                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3824                         assert_eq!(route.paths.len(), 2);
3825
3826                         let mut total_amount_paid_msat = 0;
3827                         for path in &route.paths {
3828                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3829                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3830                         }
3831                         assert_eq!(total_amount_paid_msat, 200_000);
3832                         assert_eq!(route.get_total_fees(), 150_000);
3833                 }
3834
3835         }
3836
3837         #[test]
3838         fn drop_lowest_channel_mpp_route_test() {
3839                 // This test checks that low-capacity channel is dropped when after
3840                 // path finding we realize that we found more capacity than we need.
3841                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3842                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3843
3844                 // We need a route consisting of 3 paths:
3845                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3846
3847                 // The first and the second paths should be sufficient, but the third should be
3848                 // cheaper, so that we select it but drop later.
3849
3850                 // First, we set limits on these (previously unlimited) channels.
3851                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3852
3853                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3854                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3855                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3856                         short_channel_id: 1,
3857                         timestamp: 2,
3858                         flags: 0,
3859                         cltv_expiry_delta: 0,
3860                         htlc_minimum_msat: 0,
3861                         htlc_maximum_msat: OptionalField::Present(100_000),
3862                         fee_base_msat: 0,
3863                         fee_proportional_millionths: 0,
3864                         excess_data: Vec::new()
3865                 });
3866                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3867                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3868                         short_channel_id: 3,
3869                         timestamp: 2,
3870                         flags: 0,
3871                         cltv_expiry_delta: 0,
3872                         htlc_minimum_msat: 0,
3873                         htlc_maximum_msat: OptionalField::Present(50_000),
3874                         fee_base_msat: 100,
3875                         fee_proportional_millionths: 0,
3876                         excess_data: Vec::new()
3877                 });
3878
3879                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3880                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3881                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3882                         short_channel_id: 12,
3883                         timestamp: 2,
3884                         flags: 0,
3885                         cltv_expiry_delta: 0,
3886                         htlc_minimum_msat: 0,
3887                         htlc_maximum_msat: OptionalField::Present(60_000),
3888                         fee_base_msat: 100,
3889                         fee_proportional_millionths: 0,
3890                         excess_data: Vec::new()
3891                 });
3892                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3893                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3894                         short_channel_id: 13,
3895                         timestamp: 2,
3896                         flags: 0,
3897                         cltv_expiry_delta: 0,
3898                         htlc_minimum_msat: 0,
3899                         htlc_maximum_msat: OptionalField::Present(60_000),
3900                         fee_base_msat: 0,
3901                         fee_proportional_millionths: 0,
3902                         excess_data: Vec::new()
3903                 });
3904
3905                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3906                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3907                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3908                         short_channel_id: 2,
3909                         timestamp: 2,
3910                         flags: 0,
3911                         cltv_expiry_delta: 0,
3912                         htlc_minimum_msat: 0,
3913                         htlc_maximum_msat: OptionalField::Present(20_000),
3914                         fee_base_msat: 0,
3915                         fee_proportional_millionths: 0,
3916                         excess_data: Vec::new()
3917                 });
3918                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3919                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3920                         short_channel_id: 4,
3921                         timestamp: 2,
3922                         flags: 0,
3923                         cltv_expiry_delta: 0,
3924                         htlc_minimum_msat: 0,
3925                         htlc_maximum_msat: OptionalField::Present(20_000),
3926                         fee_base_msat: 0,
3927                         fee_proportional_millionths: 0,
3928                         excess_data: Vec::new()
3929                 });
3930
3931                 {
3932                         // Attempt to route more than available results in a failure.
3933                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3934                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3935                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3936                         } else { panic!(); }
3937                 }
3938
3939                 {
3940                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3941                         // Our algorithm should provide us with these 3 paths.
3942                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3943                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3944                         assert_eq!(route.paths.len(), 3);
3945                         let mut total_amount_paid_msat = 0;
3946                         for path in &route.paths {
3947                                 assert_eq!(path.len(), 2);
3948                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3949                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3950                         }
3951                         assert_eq!(total_amount_paid_msat, 125_000);
3952                 }
3953
3954                 {
3955                         // Attempt to route without the last small cheap channel
3956                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph, &nodes[2],
3957                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3958                         assert_eq!(route.paths.len(), 2);
3959                         let mut total_amount_paid_msat = 0;
3960                         for path in &route.paths {
3961                                 assert_eq!(path.len(), 2);
3962                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3963                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3964                         }
3965                         assert_eq!(total_amount_paid_msat, 90_000);
3966                 }
3967         }
3968
3969         #[test]
3970         fn min_criteria_consistency() {
3971                 // Test that we don't use an inconsistent metric between updating and walking nodes during
3972                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3973                 // was updated with a different criterion from the heap sorting, resulting in loops in
3974                 // calculated paths. We test for that specific case here.
3975
3976                 // We construct a network that looks like this:
3977                 //
3978                 //            node2 -1(3)2- node3
3979                 //              2          2
3980                 //               (2)     (4)
3981                 //                  1   1
3982                 //    node1 -1(5)2- node4 -1(1)2- node6
3983                 //    2
3984                 //   (6)
3985                 //        1
3986                 // our_node
3987                 //
3988                 // We create a loop on the side of our real path - our destination is node 6, with a
3989                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3990                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3991                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3992                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3993                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3994                 // "previous hop" being set to node 3, creating a loop in the path.
3995                 let secp_ctx = Secp256k1::new();
3996                 let logger = Arc::new(test_utils::TestLogger::new());
3997                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
3998                 let net_graph_msg_handler = NetGraphMsgHandler::new(network_graph, None, Arc::clone(&logger));
3999                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4000
4001                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4002                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4003                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4004                         short_channel_id: 6,
4005                         timestamp: 1,
4006                         flags: 0,
4007                         cltv_expiry_delta: (6 << 8) | 0,
4008                         htlc_minimum_msat: 0,
4009                         htlc_maximum_msat: OptionalField::Absent,
4010                         fee_base_msat: 0,
4011                         fee_proportional_millionths: 0,
4012                         excess_data: Vec::new()
4013                 });
4014                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4015
4016                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4017                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4018                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4019                         short_channel_id: 5,
4020                         timestamp: 1,
4021                         flags: 0,
4022                         cltv_expiry_delta: (5 << 8) | 0,
4023                         htlc_minimum_msat: 0,
4024                         htlc_maximum_msat: OptionalField::Absent,
4025                         fee_base_msat: 100,
4026                         fee_proportional_millionths: 0,
4027                         excess_data: Vec::new()
4028                 });
4029                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4030
4031                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4032                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4033                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4034                         short_channel_id: 4,
4035                         timestamp: 1,
4036                         flags: 0,
4037                         cltv_expiry_delta: (4 << 8) | 0,
4038                         htlc_minimum_msat: 0,
4039                         htlc_maximum_msat: OptionalField::Absent,
4040                         fee_base_msat: 0,
4041                         fee_proportional_millionths: 0,
4042                         excess_data: Vec::new()
4043                 });
4044                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4045
4046                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4047                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4048                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4049                         short_channel_id: 3,
4050                         timestamp: 1,
4051                         flags: 0,
4052                         cltv_expiry_delta: (3 << 8) | 0,
4053                         htlc_minimum_msat: 0,
4054                         htlc_maximum_msat: OptionalField::Absent,
4055                         fee_base_msat: 0,
4056                         fee_proportional_millionths: 0,
4057                         excess_data: Vec::new()
4058                 });
4059                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4060
4061                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4062                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4063                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4064                         short_channel_id: 2,
4065                         timestamp: 1,
4066                         flags: 0,
4067                         cltv_expiry_delta: (2 << 8) | 0,
4068                         htlc_minimum_msat: 0,
4069                         htlc_maximum_msat: OptionalField::Absent,
4070                         fee_base_msat: 0,
4071                         fee_proportional_millionths: 0,
4072                         excess_data: Vec::new()
4073                 });
4074
4075                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4076                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4077                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4078                         short_channel_id: 1,
4079                         timestamp: 1,
4080                         flags: 0,
4081                         cltv_expiry_delta: (1 << 8) | 0,
4082                         htlc_minimum_msat: 100,
4083                         htlc_maximum_msat: OptionalField::Absent,
4084                         fee_base_msat: 0,
4085                         fee_proportional_millionths: 0,
4086                         excess_data: Vec::new()
4087                 });
4088                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4089
4090                 {
4091                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
4092                         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();
4093                         assert_eq!(route.paths.len(), 1);
4094                         assert_eq!(route.paths[0].len(), 3);
4095
4096                         assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4097                         assert_eq!(route.paths[0][0].short_channel_id, 6);
4098                         assert_eq!(route.paths[0][0].fee_msat, 100);
4099                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4100                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4101                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4102
4103                         assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4104                         assert_eq!(route.paths[0][1].short_channel_id, 5);
4105                         assert_eq!(route.paths[0][1].fee_msat, 0);
4106                         assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4107                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4108                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4109
4110                         assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4111                         assert_eq!(route.paths[0][2].short_channel_id, 1);
4112                         assert_eq!(route.paths[0][2].fee_msat, 10_000);
4113                         assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4114                         assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4115                         assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4116                 }
4117         }
4118
4119
4120         #[test]
4121         fn exact_fee_liquidity_limit() {
4122                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4123                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4124                 // we calculated fees on a higher value, resulting in us ignoring such paths.
4125                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4126                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4127
4128                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4129                 // send.
4130                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4131                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4132                         short_channel_id: 2,
4133                         timestamp: 2,
4134                         flags: 0,
4135                         cltv_expiry_delta: 0,
4136                         htlc_minimum_msat: 0,
4137                         htlc_maximum_msat: OptionalField::Present(85_000),
4138                         fee_base_msat: 0,
4139                         fee_proportional_millionths: 0,
4140                         excess_data: Vec::new()
4141                 });
4142
4143                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4144                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4145                         short_channel_id: 12,
4146                         timestamp: 2,
4147                         flags: 0,
4148                         cltv_expiry_delta: (4 << 8) | 1,
4149                         htlc_minimum_msat: 0,
4150                         htlc_maximum_msat: OptionalField::Present(270_000),
4151                         fee_base_msat: 0,
4152                         fee_proportional_millionths: 1000000,
4153                         excess_data: Vec::new()
4154                 });
4155
4156                 {
4157                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4158                         // 200% fee charged channel 13 in the 1-to-2 direction.
4159                         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();
4160                         assert_eq!(route.paths.len(), 1);
4161                         assert_eq!(route.paths[0].len(), 2);
4162
4163                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4164                         assert_eq!(route.paths[0][0].short_channel_id, 12);
4165                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4166                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4167                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4168                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4169
4170                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4171                         assert_eq!(route.paths[0][1].short_channel_id, 13);
4172                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
4173                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4174                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4175                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4176                 }
4177         }
4178
4179         #[test]
4180         fn htlc_max_reduction_below_min() {
4181                 // Test that if, while walking the graph, we reduce the value being sent to meet an
4182                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4183                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4184                 // resulting in us thinking there is no possible path, even if other paths exist.
4185                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4186                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4187
4188                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4189                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4190                 // then try to send 90_000.
4191                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4192                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4193                         short_channel_id: 2,
4194                         timestamp: 2,
4195                         flags: 0,
4196                         cltv_expiry_delta: 0,
4197                         htlc_minimum_msat: 0,
4198                         htlc_maximum_msat: OptionalField::Present(80_000),
4199                         fee_base_msat: 0,
4200                         fee_proportional_millionths: 0,
4201                         excess_data: Vec::new()
4202                 });
4203                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4204                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4205                         short_channel_id: 4,
4206                         timestamp: 2,
4207                         flags: 0,
4208                         cltv_expiry_delta: (4 << 8) | 1,
4209                         htlc_minimum_msat: 90_000,
4210                         htlc_maximum_msat: OptionalField::Absent,
4211                         fee_base_msat: 0,
4212                         fee_proportional_millionths: 0,
4213                         excess_data: Vec::new()
4214                 });
4215
4216                 {
4217                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4218                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4219                         // expensive) channels 12-13 path.
4220                         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();
4221                         assert_eq!(route.paths.len(), 1);
4222                         assert_eq!(route.paths[0].len(), 2);
4223
4224                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4225                         assert_eq!(route.paths[0][0].short_channel_id, 12);
4226                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4227                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4228                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4229                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4230
4231                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4232                         assert_eq!(route.paths[0][1].short_channel_id, 13);
4233                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
4234                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4235                         assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4236                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4237                 }
4238         }
4239
4240         #[test]
4241         fn multiple_direct_first_hops() {
4242                 // Previously we'd only ever considered one first hop path per counterparty.
4243                 // However, as we don't restrict users to one channel per peer, we really need to support
4244                 // looking at all first hop paths.
4245                 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4246                 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4247                 // route over multiple channels with the same first hop.
4248                 let secp_ctx = Secp256k1::new();
4249                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4250                 let logger = Arc::new(test_utils::TestLogger::new());
4251                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4252
4253                 {
4254                         let route = get_route(&our_id, &network_graph, &nodes[0], Some(InvoiceFeatures::known()), Some(&[
4255                                 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4256                                 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4257                         ]), &[], 100_000, 42, Arc::clone(&logger)).unwrap();
4258                         assert_eq!(route.paths.len(), 1);
4259                         assert_eq!(route.paths[0].len(), 1);
4260
4261                         assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4262                         assert_eq!(route.paths[0][0].short_channel_id, 3);
4263                         assert_eq!(route.paths[0][0].fee_msat, 100_000);
4264                 }
4265                 {
4266                         let route = get_route(&our_id, &network_graph, &nodes[0], Some(InvoiceFeatures::known()), Some(&[
4267                                 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4268                                 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4269                         ]), &[], 100_000, 42, Arc::clone(&logger)).unwrap();
4270                         assert_eq!(route.paths.len(), 2);
4271                         assert_eq!(route.paths[0].len(), 1);
4272                         assert_eq!(route.paths[1].len(), 1);
4273
4274                         assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4275                         assert_eq!(route.paths[0][0].short_channel_id, 3);
4276                         assert_eq!(route.paths[0][0].fee_msat, 50_000);
4277
4278                         assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4279                         assert_eq!(route.paths[1][0].short_channel_id, 2);
4280                         assert_eq!(route.paths[1][0].fee_msat, 50_000);
4281                 }
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 }