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