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