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