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