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