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