Expose counterparty forwarding info in ChannelDetails.
[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                         counterparty_forwarding_info: None,
1477                 }];
1478
1479                 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)) {
1480                         assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1481                 } else { panic!(); }
1482
1483                 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();
1484                 assert_eq!(route.paths[0].len(), 2);
1485         }
1486
1487         #[test]
1488         fn htlc_minimum_test() {
1489                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1490                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1491
1492                 // Simple route to 2 via 1
1493
1494                 // Disable other paths
1495                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1496                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1497                         short_channel_id: 12,
1498                         timestamp: 2,
1499                         flags: 2, // to disable
1500                         cltv_expiry_delta: 0,
1501                         htlc_minimum_msat: 0,
1502                         htlc_maximum_msat: OptionalField::Absent,
1503                         fee_base_msat: 0,
1504                         fee_proportional_millionths: 0,
1505                         excess_data: Vec::new()
1506                 });
1507                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1508                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1509                         short_channel_id: 3,
1510                         timestamp: 2,
1511                         flags: 2, // to disable
1512                         cltv_expiry_delta: 0,
1513                         htlc_minimum_msat: 0,
1514                         htlc_maximum_msat: OptionalField::Absent,
1515                         fee_base_msat: 0,
1516                         fee_proportional_millionths: 0,
1517                         excess_data: Vec::new()
1518                 });
1519                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1520                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1521                         short_channel_id: 13,
1522                         timestamp: 2,
1523                         flags: 2, // to disable
1524                         cltv_expiry_delta: 0,
1525                         htlc_minimum_msat: 0,
1526                         htlc_maximum_msat: OptionalField::Absent,
1527                         fee_base_msat: 0,
1528                         fee_proportional_millionths: 0,
1529                         excess_data: Vec::new()
1530                 });
1531                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1532                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1533                         short_channel_id: 6,
1534                         timestamp: 2,
1535                         flags: 2, // to disable
1536                         cltv_expiry_delta: 0,
1537                         htlc_minimum_msat: 0,
1538                         htlc_maximum_msat: OptionalField::Absent,
1539                         fee_base_msat: 0,
1540                         fee_proportional_millionths: 0,
1541                         excess_data: Vec::new()
1542                 });
1543                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1544                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1545                         short_channel_id: 7,
1546                         timestamp: 2,
1547                         flags: 2, // to disable
1548                         cltv_expiry_delta: 0,
1549                         htlc_minimum_msat: 0,
1550                         htlc_maximum_msat: OptionalField::Absent,
1551                         fee_base_msat: 0,
1552                         fee_proportional_millionths: 0,
1553                         excess_data: Vec::new()
1554                 });
1555
1556                 // Check against amount_to_transfer_over_msat.
1557                 // Set minimal HTLC of 200_000_000 msat.
1558                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1559                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1560                         short_channel_id: 2,
1561                         timestamp: 3,
1562                         flags: 0,
1563                         cltv_expiry_delta: 0,
1564                         htlc_minimum_msat: 200_000_000,
1565                         htlc_maximum_msat: OptionalField::Absent,
1566                         fee_base_msat: 0,
1567                         fee_proportional_millionths: 0,
1568                         excess_data: Vec::new()
1569                 });
1570
1571                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1572                 // be used.
1573                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1574                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1575                         short_channel_id: 4,
1576                         timestamp: 3,
1577                         flags: 0,
1578                         cltv_expiry_delta: 0,
1579                         htlc_minimum_msat: 0,
1580                         htlc_maximum_msat: OptionalField::Present(199_999_999),
1581                         fee_base_msat: 0,
1582                         fee_proportional_millionths: 0,
1583                         excess_data: Vec::new()
1584                 });
1585
1586                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1587                 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)) {
1588                         assert_eq!(err, "Failed to find a path to the given destination");
1589                 } else { panic!(); }
1590
1591                 // Lift the restriction on the first hop.
1592                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1593                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1594                         short_channel_id: 2,
1595                         timestamp: 4,
1596                         flags: 0,
1597                         cltv_expiry_delta: 0,
1598                         htlc_minimum_msat: 0,
1599                         htlc_maximum_msat: OptionalField::Absent,
1600                         fee_base_msat: 0,
1601                         fee_proportional_millionths: 0,
1602                         excess_data: Vec::new()
1603                 });
1604
1605                 // A payment above the minimum should pass
1606                 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();
1607                 assert_eq!(route.paths[0].len(), 2);
1608         }
1609
1610         #[test]
1611         fn htlc_minimum_overpay_test() {
1612                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1613                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1614
1615                 // A route to node#2 via two paths.
1616                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1617                 // Thus, they can't send 60 without overpaying.
1618                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1619                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1620                         short_channel_id: 2,
1621                         timestamp: 2,
1622                         flags: 0,
1623                         cltv_expiry_delta: 0,
1624                         htlc_minimum_msat: 35_000,
1625                         htlc_maximum_msat: OptionalField::Present(40_000),
1626                         fee_base_msat: 0,
1627                         fee_proportional_millionths: 0,
1628                         excess_data: Vec::new()
1629                 });
1630                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1631                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1632                         short_channel_id: 12,
1633                         timestamp: 3,
1634                         flags: 0,
1635                         cltv_expiry_delta: 0,
1636                         htlc_minimum_msat: 35_000,
1637                         htlc_maximum_msat: OptionalField::Present(40_000),
1638                         fee_base_msat: 0,
1639                         fee_proportional_millionths: 0,
1640                         excess_data: Vec::new()
1641                 });
1642
1643                 // Make 0 fee.
1644                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1645                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1646                         short_channel_id: 13,
1647                         timestamp: 2,
1648                         flags: 0,
1649                         cltv_expiry_delta: 0,
1650                         htlc_minimum_msat: 0,
1651                         htlc_maximum_msat: OptionalField::Absent,
1652                         fee_base_msat: 0,
1653                         fee_proportional_millionths: 0,
1654                         excess_data: Vec::new()
1655                 });
1656                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1657                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1658                         short_channel_id: 4,
1659                         timestamp: 2,
1660                         flags: 0,
1661                         cltv_expiry_delta: 0,
1662                         htlc_minimum_msat: 0,
1663                         htlc_maximum_msat: OptionalField::Absent,
1664                         fee_base_msat: 0,
1665                         fee_proportional_millionths: 0,
1666                         excess_data: Vec::new()
1667                 });
1668
1669                 // Disable other paths
1670                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1671                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1672                         short_channel_id: 1,
1673                         timestamp: 3,
1674                         flags: 2, // to disable
1675                         cltv_expiry_delta: 0,
1676                         htlc_minimum_msat: 0,
1677                         htlc_maximum_msat: OptionalField::Absent,
1678                         fee_base_msat: 0,
1679                         fee_proportional_millionths: 0,
1680                         excess_data: Vec::new()
1681                 });
1682
1683                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1684                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1685                 // Overpay fees to hit htlc_minimum_msat.
1686                 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1687                 // TODO: this could be better balanced to overpay 10k and not 15k.
1688                 assert_eq!(overpaid_fees, 15_000);
1689
1690                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1691                 // while taking even more fee to match htlc_minimum_msat.
1692                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1693                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1694                         short_channel_id: 12,
1695                         timestamp: 4,
1696                         flags: 0,
1697                         cltv_expiry_delta: 0,
1698                         htlc_minimum_msat: 65_000,
1699                         htlc_maximum_msat: OptionalField::Present(80_000),
1700                         fee_base_msat: 0,
1701                         fee_proportional_millionths: 0,
1702                         excess_data: Vec::new()
1703                 });
1704                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1705                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1706                         short_channel_id: 2,
1707                         timestamp: 3,
1708                         flags: 0,
1709                         cltv_expiry_delta: 0,
1710                         htlc_minimum_msat: 0,
1711                         htlc_maximum_msat: OptionalField::Absent,
1712                         fee_base_msat: 0,
1713                         fee_proportional_millionths: 0,
1714                         excess_data: Vec::new()
1715                 });
1716                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1717                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1718                         short_channel_id: 4,
1719                         timestamp: 4,
1720                         flags: 0,
1721                         cltv_expiry_delta: 0,
1722                         htlc_minimum_msat: 0,
1723                         htlc_maximum_msat: OptionalField::Absent,
1724                         fee_base_msat: 0,
1725                         fee_proportional_millionths: 100_000,
1726                         excess_data: Vec::new()
1727                 });
1728
1729                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1730                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1731                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1732                 assert_eq!(route.paths.len(), 1);
1733                 assert_eq!(route.paths[0][0].short_channel_id, 12);
1734                 let fees = route.paths[0][0].fee_msat;
1735                 assert_eq!(fees, 5_000);
1736
1737                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1738                         Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1739                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1740                 // the other channel.
1741                 assert_eq!(route.paths.len(), 1);
1742                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1743                 let fees = route.paths[0][0].fee_msat;
1744                 assert_eq!(fees, 5_000);
1745         }
1746
1747         #[test]
1748         fn disable_channels_test() {
1749                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1750                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1751
1752                 // // Disable channels 4 and 12 by flags=2
1753                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1754                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1755                         short_channel_id: 4,
1756                         timestamp: 2,
1757                         flags: 2, // to disable
1758                         cltv_expiry_delta: 0,
1759                         htlc_minimum_msat: 0,
1760                         htlc_maximum_msat: OptionalField::Absent,
1761                         fee_base_msat: 0,
1762                         fee_proportional_millionths: 0,
1763                         excess_data: Vec::new()
1764                 });
1765                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1766                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1767                         short_channel_id: 12,
1768                         timestamp: 2,
1769                         flags: 2, // to disable
1770                         cltv_expiry_delta: 0,
1771                         htlc_minimum_msat: 0,
1772                         htlc_maximum_msat: OptionalField::Absent,
1773                         fee_base_msat: 0,
1774                         fee_proportional_millionths: 0,
1775                         excess_data: Vec::new()
1776                 });
1777
1778                 // If all the channels require some features we don't understand, route should fail
1779                 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)) {
1780                         assert_eq!(err, "Failed to find a path to the given destination");
1781                 } else { panic!(); }
1782
1783                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1784                 let our_chans = vec![channelmanager::ChannelDetails {
1785                         channel_id: [0; 32],
1786                         short_channel_id: Some(42),
1787                         remote_network_id: nodes[7].clone(),
1788                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1789                         channel_value_satoshis: 0,
1790                         user_id: 0,
1791                         outbound_capacity_msat: 250_000_000,
1792                         inbound_capacity_msat: 0,
1793                         is_live: true,
1794                         counterparty_forwarding_info: None,
1795                 }];
1796                 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();
1797                 assert_eq!(route.paths[0].len(), 2);
1798
1799                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1800                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1801                 assert_eq!(route.paths[0][0].fee_msat, 200);
1802                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1803                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1804                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1805
1806                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1807                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1808                 assert_eq!(route.paths[0][1].fee_msat, 100);
1809                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1810                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1811                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1812         }
1813
1814         #[test]
1815         fn disable_node_test() {
1816                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1817                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1818
1819                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1820                 let mut unknown_features = NodeFeatures::known();
1821                 unknown_features.set_required_unknown_bits();
1822                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1823                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1824                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1825
1826                 // If all nodes require some features we don't understand, route should fail
1827                 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)) {
1828                         assert_eq!(err, "Failed to find a path to the given destination");
1829                 } else { panic!(); }
1830
1831                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1832                 let our_chans = vec![channelmanager::ChannelDetails {
1833                         channel_id: [0; 32],
1834                         short_channel_id: Some(42),
1835                         remote_network_id: nodes[7].clone(),
1836                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1837                         channel_value_satoshis: 0,
1838                         user_id: 0,
1839                         outbound_capacity_msat: 250_000_000,
1840                         inbound_capacity_msat: 0,
1841                         is_live: true,
1842                         counterparty_forwarding_info: None,
1843                 }];
1844                 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();
1845                 assert_eq!(route.paths[0].len(), 2);
1846
1847                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1848                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1849                 assert_eq!(route.paths[0][0].fee_msat, 200);
1850                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1851                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1852                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1853
1854                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1855                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1856                 assert_eq!(route.paths[0][1].fee_msat, 100);
1857                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1858                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1859                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1860
1861                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1862                 // naively) assume that the user checked the feature bits on the invoice, which override
1863                 // the node_announcement.
1864         }
1865
1866         #[test]
1867         fn our_chans_test() {
1868                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1869                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1870
1871                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1872                 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();
1873                 assert_eq!(route.paths[0].len(), 3);
1874
1875                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1876                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1877                 assert_eq!(route.paths[0][0].fee_msat, 200);
1878                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1879                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1880                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1881
1882                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1883                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1884                 assert_eq!(route.paths[0][1].fee_msat, 100);
1885                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1886                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1887                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1888
1889                 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1890                 assert_eq!(route.paths[0][2].short_channel_id, 3);
1891                 assert_eq!(route.paths[0][2].fee_msat, 100);
1892                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1893                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1894                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1895
1896                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1897                 let our_chans = vec![channelmanager::ChannelDetails {
1898                         channel_id: [0; 32],
1899                         short_channel_id: Some(42),
1900                         remote_network_id: nodes[7].clone(),
1901                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1902                         channel_value_satoshis: 0,
1903                         user_id: 0,
1904                         outbound_capacity_msat: 250_000_000,
1905                         inbound_capacity_msat: 0,
1906                         is_live: true,
1907                         counterparty_forwarding_info: None,
1908                 }];
1909                 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();
1910                 assert_eq!(route.paths[0].len(), 2);
1911
1912                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1913                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1914                 assert_eq!(route.paths[0][0].fee_msat, 200);
1915                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1916                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1917                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1918
1919                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1920                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1921                 assert_eq!(route.paths[0][1].fee_msat, 100);
1922                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1923                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1924                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1925         }
1926
1927         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1928                 let zero_fees = RoutingFees {
1929                         base_msat: 0,
1930                         proportional_millionths: 0,
1931                 };
1932                 vec!(RouteHint {
1933                         src_node_id: nodes[3].clone(),
1934                         short_channel_id: 8,
1935                         fees: zero_fees,
1936                         cltv_expiry_delta: (8 << 8) | 1,
1937                         htlc_minimum_msat: None,
1938                         htlc_maximum_msat: None,
1939                 }, RouteHint {
1940                         src_node_id: nodes[4].clone(),
1941                         short_channel_id: 9,
1942                         fees: RoutingFees {
1943                                 base_msat: 1001,
1944                                 proportional_millionths: 0,
1945                         },
1946                         cltv_expiry_delta: (9 << 8) | 1,
1947                         htlc_minimum_msat: None,
1948                         htlc_maximum_msat: None,
1949                 }, RouteHint {
1950                         src_node_id: nodes[5].clone(),
1951                         short_channel_id: 10,
1952                         fees: zero_fees,
1953                         cltv_expiry_delta: (10 << 8) | 1,
1954                         htlc_minimum_msat: None,
1955                         htlc_maximum_msat: None,
1956                 })
1957         }
1958
1959         #[test]
1960         fn last_hops_test() {
1961                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1962                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1963
1964                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
1965
1966                 // First check that lst hop can't have its source as the payee.
1967                 let invalid_last_hop = RouteHint {
1968                         src_node_id: nodes[6],
1969                         short_channel_id: 8,
1970                         fees: RoutingFees {
1971                                 base_msat: 1000,
1972                                 proportional_millionths: 0,
1973                         },
1974                         cltv_expiry_delta: (8 << 8) | 1,
1975                         htlc_minimum_msat: None,
1976                         htlc_maximum_msat: None,
1977                 };
1978
1979                 let mut invalid_last_hops = last_hops(&nodes);
1980                 invalid_last_hops.push(invalid_last_hop);
1981                 {
1982                         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)) {
1983                                 assert_eq!(err, "Last hop cannot have a payee as a source.");
1984                         } else { panic!(); }
1985                 }
1986
1987                 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();
1988                 assert_eq!(route.paths[0].len(), 5);
1989
1990                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1991                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1992                 assert_eq!(route.paths[0][0].fee_msat, 100);
1993                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1994                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1995                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1996
1997                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1998                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1999                 assert_eq!(route.paths[0][1].fee_msat, 0);
2000                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2001                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2002                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2003
2004                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2005                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2006                 assert_eq!(route.paths[0][2].fee_msat, 0);
2007                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2008                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2009                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2010
2011                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2012                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2013                 assert_eq!(route.paths[0][3].fee_msat, 0);
2014                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2015                 // If we have a peer in the node map, we'll use their features here since we don't have
2016                 // a way of figuring out their features from the invoice:
2017                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2018                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2019
2020                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2021                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2022                 assert_eq!(route.paths[0][4].fee_msat, 100);
2023                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2024                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2025                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2026         }
2027
2028         #[test]
2029         fn our_chans_last_hop_connect_test() {
2030                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2031                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2032
2033                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2034                 let our_chans = vec![channelmanager::ChannelDetails {
2035                         channel_id: [0; 32],
2036                         short_channel_id: Some(42),
2037                         remote_network_id: nodes[3].clone(),
2038                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2039                         channel_value_satoshis: 0,
2040                         user_id: 0,
2041                         outbound_capacity_msat: 250_000_000,
2042                         inbound_capacity_msat: 0,
2043                         is_live: true,
2044                         counterparty_forwarding_info: None,
2045                 }];
2046                 let mut last_hops = last_hops(&nodes);
2047                 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();
2048                 assert_eq!(route.paths[0].len(), 2);
2049
2050                 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2051                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2052                 assert_eq!(route.paths[0][0].fee_msat, 0);
2053                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2054                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2055                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2056
2057                 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2058                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2059                 assert_eq!(route.paths[0][1].fee_msat, 100);
2060                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2061                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2062                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2063
2064                 last_hops[0].fees.base_msat = 1000;
2065
2066                 // Revert to via 6 as the fee on 8 goes up
2067                 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();
2068                 assert_eq!(route.paths[0].len(), 4);
2069
2070                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2071                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2072                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2073                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2074                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2075                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2076
2077                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2078                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2079                 assert_eq!(route.paths[0][1].fee_msat, 100);
2080                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2081                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2082                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2083
2084                 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2085                 assert_eq!(route.paths[0][2].short_channel_id, 7);
2086                 assert_eq!(route.paths[0][2].fee_msat, 0);
2087                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2088                 // If we have a peer in the node map, we'll use their features here since we don't have
2089                 // a way of figuring out their features from the invoice:
2090                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2091                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2092
2093                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2094                 assert_eq!(route.paths[0][3].short_channel_id, 10);
2095                 assert_eq!(route.paths[0][3].fee_msat, 100);
2096                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2097                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2098                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2099
2100                 // ...but still use 8 for larger payments as 6 has a variable feerate
2101                 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();
2102                 assert_eq!(route.paths[0].len(), 5);
2103
2104                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2105                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2106                 assert_eq!(route.paths[0][0].fee_msat, 3000);
2107                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2108                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2109                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2110
2111                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2112                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2113                 assert_eq!(route.paths[0][1].fee_msat, 0);
2114                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2115                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2116                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2117
2118                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2119                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2120                 assert_eq!(route.paths[0][2].fee_msat, 0);
2121                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2122                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2123                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2124
2125                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2126                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2127                 assert_eq!(route.paths[0][3].fee_msat, 1000);
2128                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2129                 // If we have a peer in the node map, we'll use their features here since we don't have
2130                 // a way of figuring out their features from the invoice:
2131                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2132                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2133
2134                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2135                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2136                 assert_eq!(route.paths[0][4].fee_msat, 2000);
2137                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2138                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2139                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2140         }
2141
2142         #[test]
2143         fn unannounced_path_test() {
2144                 // We should be able to send a payment to a destination without any help of a routing graph
2145                 // if we have a channel with a common counterparty that appears in the first and last hop
2146                 // hints.
2147                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2148                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2149                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2150
2151                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2152                 let last_hops = vec![RouteHint {
2153                         src_node_id: middle_node_id,
2154                         short_channel_id: 8,
2155                         fees: RoutingFees {
2156                                 base_msat: 1000,
2157                                 proportional_millionths: 0,
2158                         },
2159                         cltv_expiry_delta: (8 << 8) | 1,
2160                         htlc_minimum_msat: None,
2161                         htlc_maximum_msat: None,
2162                 }];
2163                 let our_chans = vec![channelmanager::ChannelDetails {
2164                         channel_id: [0; 32],
2165                         short_channel_id: Some(42),
2166                         remote_network_id: middle_node_id,
2167                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2168                         channel_value_satoshis: 100000,
2169                         user_id: 0,
2170                         outbound_capacity_msat: 100000,
2171                         inbound_capacity_msat: 100000,
2172                         is_live: true,
2173                         counterparty_forwarding_info: None,
2174                 }];
2175                 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();
2176
2177                 assert_eq!(route.paths[0].len(), 2);
2178
2179                 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2180                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2181                 assert_eq!(route.paths[0][0].fee_msat, 1000);
2182                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2183                 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2184                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2185
2186                 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2187                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2188                 assert_eq!(route.paths[0][1].fee_msat, 100);
2189                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2190                 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2191                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2192         }
2193
2194         #[test]
2195         fn available_amount_while_routing_test() {
2196                 // Tests whether we choose the correct available channel amount while routing.
2197
2198                 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2199                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2200
2201                 // We will use a simple single-path route from
2202                 // our node to node2 via node0: channels {1, 3}.
2203
2204                 // First disable all other paths.
2205                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2206                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2207                         short_channel_id: 2,
2208                         timestamp: 2,
2209                         flags: 2,
2210                         cltv_expiry_delta: 0,
2211                         htlc_minimum_msat: 0,
2212                         htlc_maximum_msat: OptionalField::Present(100_000),
2213                         fee_base_msat: 0,
2214                         fee_proportional_millionths: 0,
2215                         excess_data: Vec::new()
2216                 });
2217                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2218                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2219                         short_channel_id: 12,
2220                         timestamp: 2,
2221                         flags: 2,
2222                         cltv_expiry_delta: 0,
2223                         htlc_minimum_msat: 0,
2224                         htlc_maximum_msat: OptionalField::Present(100_000),
2225                         fee_base_msat: 0,
2226                         fee_proportional_millionths: 0,
2227                         excess_data: Vec::new()
2228                 });
2229
2230                 // Make the first channel (#1) very permissive,
2231                 // and we will be testing all limits on the second channel.
2232                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2233                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2234                         short_channel_id: 1,
2235                         timestamp: 2,
2236                         flags: 0,
2237                         cltv_expiry_delta: 0,
2238                         htlc_minimum_msat: 0,
2239                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2240                         fee_base_msat: 0,
2241                         fee_proportional_millionths: 0,
2242                         excess_data: Vec::new()
2243                 });
2244
2245                 // First, let's see if routing works if we have absolutely no idea about the available amount.
2246                 // In this case, it should be set to 250_000 sats.
2247                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2248                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2249                         short_channel_id: 3,
2250                         timestamp: 2,
2251                         flags: 0,
2252                         cltv_expiry_delta: 0,
2253                         htlc_minimum_msat: 0,
2254                         htlc_maximum_msat: OptionalField::Absent,
2255                         fee_base_msat: 0,
2256                         fee_proportional_millionths: 0,
2257                         excess_data: Vec::new()
2258                 });
2259
2260                 {
2261                         // Attempt to route more than available results in a failure.
2262                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2263                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2264                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2265                         } else { panic!(); }
2266                 }
2267
2268                 {
2269                         // Now, attempt to route an exact amount we have should be fine.
2270                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2271                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2272                         assert_eq!(route.paths.len(), 1);
2273                         let path = route.paths.last().unwrap();
2274                         assert_eq!(path.len(), 2);
2275                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2276                         assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2277                 }
2278
2279                 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2280                 // Disable channel #1 and use another first hop.
2281                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2282                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2283                         short_channel_id: 1,
2284                         timestamp: 3,
2285                         flags: 2,
2286                         cltv_expiry_delta: 0,
2287                         htlc_minimum_msat: 0,
2288                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2289                         fee_base_msat: 0,
2290                         fee_proportional_millionths: 0,
2291                         excess_data: Vec::new()
2292                 });
2293
2294                 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2295                 let our_chans = vec![channelmanager::ChannelDetails {
2296                         channel_id: [0; 32],
2297                         short_channel_id: Some(42),
2298                         remote_network_id: nodes[0].clone(),
2299                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2300                         channel_value_satoshis: 0,
2301                         user_id: 0,
2302                         outbound_capacity_msat: 200_000_000,
2303                         inbound_capacity_msat: 0,
2304                         is_live: true,
2305                         counterparty_forwarding_info: None,
2306                 }];
2307
2308                 {
2309                         // Attempt to route more than available results in a failure.
2310                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2311                                         Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2312                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2313                         } else { panic!(); }
2314                 }
2315
2316                 {
2317                         // Now, attempt to route an exact amount we have should be fine.
2318                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2319                                 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2320                         assert_eq!(route.paths.len(), 1);
2321                         let path = route.paths.last().unwrap();
2322                         assert_eq!(path.len(), 2);
2323                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2324                         assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2325                 }
2326
2327                 // Enable channel #1 back.
2328                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2329                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2330                         short_channel_id: 1,
2331                         timestamp: 4,
2332                         flags: 0,
2333                         cltv_expiry_delta: 0,
2334                         htlc_minimum_msat: 0,
2335                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2336                         fee_base_msat: 0,
2337                         fee_proportional_millionths: 0,
2338                         excess_data: Vec::new()
2339                 });
2340
2341
2342                 // Now let's see if routing works if we know only htlc_maximum_msat.
2343                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2344                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2345                         short_channel_id: 3,
2346                         timestamp: 3,
2347                         flags: 0,
2348                         cltv_expiry_delta: 0,
2349                         htlc_minimum_msat: 0,
2350                         htlc_maximum_msat: OptionalField::Present(15_000),
2351                         fee_base_msat: 0,
2352                         fee_proportional_millionths: 0,
2353                         excess_data: Vec::new()
2354                 });
2355
2356                 {
2357                         // Attempt to route more than available results in a failure.
2358                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2359                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2360                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2361                         } else { panic!(); }
2362                 }
2363
2364                 {
2365                         // Now, attempt to route an exact amount we have should be fine.
2366                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2367                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2368                         assert_eq!(route.paths.len(), 1);
2369                         let path = route.paths.last().unwrap();
2370                         assert_eq!(path.len(), 2);
2371                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2372                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2373                 }
2374
2375                 // Now let's see if routing works if we know only capacity from the UTXO.
2376
2377                 // We can't change UTXO capacity on the fly, so we'll disable
2378                 // the existing channel and add another one with the capacity we need.
2379                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2380                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2381                         short_channel_id: 3,
2382                         timestamp: 4,
2383                         flags: 2,
2384                         cltv_expiry_delta: 0,
2385                         htlc_minimum_msat: 0,
2386                         htlc_maximum_msat: OptionalField::Absent,
2387                         fee_base_msat: 0,
2388                         fee_proportional_millionths: 0,
2389                         excess_data: Vec::new()
2390                 });
2391
2392                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2393                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2394                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2395                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2396                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2397
2398                 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2399                 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2400
2401                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2402                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2403                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2404                         short_channel_id: 333,
2405                         timestamp: 1,
2406                         flags: 0,
2407                         cltv_expiry_delta: (3 << 8) | 1,
2408                         htlc_minimum_msat: 0,
2409                         htlc_maximum_msat: OptionalField::Absent,
2410                         fee_base_msat: 0,
2411                         fee_proportional_millionths: 0,
2412                         excess_data: Vec::new()
2413                 });
2414                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2415                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2416                         short_channel_id: 333,
2417                         timestamp: 1,
2418                         flags: 1,
2419                         cltv_expiry_delta: (3 << 8) | 2,
2420                         htlc_minimum_msat: 0,
2421                         htlc_maximum_msat: OptionalField::Absent,
2422                         fee_base_msat: 100,
2423                         fee_proportional_millionths: 0,
2424                         excess_data: Vec::new()
2425                 });
2426
2427                 {
2428                         // Attempt to route more than available results in a failure.
2429                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2430                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2431                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2432                         } else { panic!(); }
2433                 }
2434
2435                 {
2436                         // Now, attempt to route an exact amount we have should be fine.
2437                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2438                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2439                         assert_eq!(route.paths.len(), 1);
2440                         let path = route.paths.last().unwrap();
2441                         assert_eq!(path.len(), 2);
2442                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2443                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2444                 }
2445
2446                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2447                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2448                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2449                         short_channel_id: 333,
2450                         timestamp: 6,
2451                         flags: 0,
2452                         cltv_expiry_delta: 0,
2453                         htlc_minimum_msat: 0,
2454                         htlc_maximum_msat: OptionalField::Present(10_000),
2455                         fee_base_msat: 0,
2456                         fee_proportional_millionths: 0,
2457                         excess_data: Vec::new()
2458                 });
2459
2460                 {
2461                         // Attempt to route more than available results in a failure.
2462                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2463                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2464                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2465                         } else { panic!(); }
2466                 }
2467
2468                 {
2469                         // Now, attempt to route an exact amount we have should be fine.
2470                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2471                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2472                         assert_eq!(route.paths.len(), 1);
2473                         let path = route.paths.last().unwrap();
2474                         assert_eq!(path.len(), 2);
2475                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2476                         assert_eq!(path.last().unwrap().fee_msat, 10_000);
2477                 }
2478         }
2479
2480         #[test]
2481         fn available_liquidity_last_hop_test() {
2482                 // Check that available liquidity properly limits the path even when only
2483                 // one of the latter hops is limited.
2484                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2485                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2486
2487                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2488                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2489                 // Total capacity: 50 sats.
2490
2491                 // Disable other potential paths.
2492                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2493                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2494                         short_channel_id: 2,
2495                         timestamp: 2,
2496                         flags: 2,
2497                         cltv_expiry_delta: 0,
2498                         htlc_minimum_msat: 0,
2499                         htlc_maximum_msat: OptionalField::Present(100_000),
2500                         fee_base_msat: 0,
2501                         fee_proportional_millionths: 0,
2502                         excess_data: Vec::new()
2503                 });
2504                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2505                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2506                         short_channel_id: 7,
2507                         timestamp: 2,
2508                         flags: 2,
2509                         cltv_expiry_delta: 0,
2510                         htlc_minimum_msat: 0,
2511                         htlc_maximum_msat: OptionalField::Present(100_000),
2512                         fee_base_msat: 0,
2513                         fee_proportional_millionths: 0,
2514                         excess_data: Vec::new()
2515                 });
2516
2517                 // Limit capacities
2518
2519                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2520                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2521                         short_channel_id: 12,
2522                         timestamp: 2,
2523                         flags: 0,
2524                         cltv_expiry_delta: 0,
2525                         htlc_minimum_msat: 0,
2526                         htlc_maximum_msat: OptionalField::Present(100_000),
2527                         fee_base_msat: 0,
2528                         fee_proportional_millionths: 0,
2529                         excess_data: Vec::new()
2530                 });
2531                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2532                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2533                         short_channel_id: 13,
2534                         timestamp: 2,
2535                         flags: 0,
2536                         cltv_expiry_delta: 0,
2537                         htlc_minimum_msat: 0,
2538                         htlc_maximum_msat: OptionalField::Present(100_000),
2539                         fee_base_msat: 0,
2540                         fee_proportional_millionths: 0,
2541                         excess_data: Vec::new()
2542                 });
2543
2544                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2545                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2546                         short_channel_id: 6,
2547                         timestamp: 2,
2548                         flags: 0,
2549                         cltv_expiry_delta: 0,
2550                         htlc_minimum_msat: 0,
2551                         htlc_maximum_msat: OptionalField::Present(50_000),
2552                         fee_base_msat: 0,
2553                         fee_proportional_millionths: 0,
2554                         excess_data: Vec::new()
2555                 });
2556                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2557                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2558                         short_channel_id: 11,
2559                         timestamp: 2,
2560                         flags: 0,
2561                         cltv_expiry_delta: 0,
2562                         htlc_minimum_msat: 0,
2563                         htlc_maximum_msat: OptionalField::Present(100_000),
2564                         fee_base_msat: 0,
2565                         fee_proportional_millionths: 0,
2566                         excess_data: Vec::new()
2567                 });
2568                 {
2569                         // Attempt to route more than available results in a failure.
2570                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2571                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2572                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2573                         } else { panic!(); }
2574                 }
2575
2576                 {
2577                         // Now, attempt to route 49 sats (just a bit below the capacity).
2578                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2579                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2580                         assert_eq!(route.paths.len(), 1);
2581                         let mut total_amount_paid_msat = 0;
2582                         for path in &route.paths {
2583                                 assert_eq!(path.len(), 4);
2584                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2585                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2586                         }
2587                         assert_eq!(total_amount_paid_msat, 49_000);
2588                 }
2589
2590                 {
2591                         // Attempt to route an exact amount is also fine
2592                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2593                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2594                         assert_eq!(route.paths.len(), 1);
2595                         let mut total_amount_paid_msat = 0;
2596                         for path in &route.paths {
2597                                 assert_eq!(path.len(), 4);
2598                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2599                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2600                         }
2601                         assert_eq!(total_amount_paid_msat, 50_000);
2602                 }
2603         }
2604
2605         #[test]
2606         fn ignore_fee_first_hop_test() {
2607                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2608                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2609
2610                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2611                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2612                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2613                         short_channel_id: 1,
2614                         timestamp: 2,
2615                         flags: 0,
2616                         cltv_expiry_delta: 0,
2617                         htlc_minimum_msat: 0,
2618                         htlc_maximum_msat: OptionalField::Present(100_000),
2619                         fee_base_msat: 1_000_000,
2620                         fee_proportional_millionths: 0,
2621                         excess_data: Vec::new()
2622                 });
2623                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2624                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2625                         short_channel_id: 3,
2626                         timestamp: 2,
2627                         flags: 0,
2628                         cltv_expiry_delta: 0,
2629                         htlc_minimum_msat: 0,
2630                         htlc_maximum_msat: OptionalField::Present(50_000),
2631                         fee_base_msat: 0,
2632                         fee_proportional_millionths: 0,
2633                         excess_data: Vec::new()
2634                 });
2635
2636                 {
2637                         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();
2638                         assert_eq!(route.paths.len(), 1);
2639                         let mut total_amount_paid_msat = 0;
2640                         for path in &route.paths {
2641                                 assert_eq!(path.len(), 2);
2642                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2643                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2644                         }
2645                         assert_eq!(total_amount_paid_msat, 50_000);
2646                 }
2647         }
2648
2649         #[test]
2650         fn simple_mpp_route_test() {
2651                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2652                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2653
2654                 // We need a route consisting of 3 paths:
2655                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2656                 // To achieve this, the amount being transferred should be around
2657                 // the total capacity of these 3 paths.
2658
2659                 // First, we set limits on these (previously unlimited) channels.
2660                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2661
2662                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2663                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2664                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2665                         short_channel_id: 1,
2666                         timestamp: 2,
2667                         flags: 0,
2668                         cltv_expiry_delta: 0,
2669                         htlc_minimum_msat: 0,
2670                         htlc_maximum_msat: OptionalField::Present(100_000),
2671                         fee_base_msat: 0,
2672                         fee_proportional_millionths: 0,
2673                         excess_data: Vec::new()
2674                 });
2675                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2676                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2677                         short_channel_id: 3,
2678                         timestamp: 2,
2679                         flags: 0,
2680                         cltv_expiry_delta: 0,
2681                         htlc_minimum_msat: 0,
2682                         htlc_maximum_msat: OptionalField::Present(50_000),
2683                         fee_base_msat: 0,
2684                         fee_proportional_millionths: 0,
2685                         excess_data: Vec::new()
2686                 });
2687
2688                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2689                 // (total limit 60).
2690                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2691                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2692                         short_channel_id: 12,
2693                         timestamp: 2,
2694                         flags: 0,
2695                         cltv_expiry_delta: 0,
2696                         htlc_minimum_msat: 0,
2697                         htlc_maximum_msat: OptionalField::Present(60_000),
2698                         fee_base_msat: 0,
2699                         fee_proportional_millionths: 0,
2700                         excess_data: Vec::new()
2701                 });
2702                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2703                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2704                         short_channel_id: 13,
2705                         timestamp: 2,
2706                         flags: 0,
2707                         cltv_expiry_delta: 0,
2708                         htlc_minimum_msat: 0,
2709                         htlc_maximum_msat: OptionalField::Present(60_000),
2710                         fee_base_msat: 0,
2711                         fee_proportional_millionths: 0,
2712                         excess_data: Vec::new()
2713                 });
2714
2715                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2716                 // (total capacity 180 sats).
2717                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2718                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2719                         short_channel_id: 2,
2720                         timestamp: 2,
2721                         flags: 0,
2722                         cltv_expiry_delta: 0,
2723                         htlc_minimum_msat: 0,
2724                         htlc_maximum_msat: OptionalField::Present(200_000),
2725                         fee_base_msat: 0,
2726                         fee_proportional_millionths: 0,
2727                         excess_data: Vec::new()
2728                 });
2729                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2730                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2731                         short_channel_id: 4,
2732                         timestamp: 2,
2733                         flags: 0,
2734                         cltv_expiry_delta: 0,
2735                         htlc_minimum_msat: 0,
2736                         htlc_maximum_msat: OptionalField::Present(180_000),
2737                         fee_base_msat: 0,
2738                         fee_proportional_millionths: 0,
2739                         excess_data: Vec::new()
2740                 });
2741
2742                 {
2743                         // Attempt to route more than available results in a failure.
2744                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2745                                         &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2746                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2747                         } else { panic!(); }
2748                 }
2749
2750                 {
2751                         // Now, attempt to route 250 sats (just a bit below the capacity).
2752                         // Our algorithm should provide us with these 3 paths.
2753                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2754                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2755                         assert_eq!(route.paths.len(), 3);
2756                         let mut total_amount_paid_msat = 0;
2757                         for path in &route.paths {
2758                                 assert_eq!(path.len(), 2);
2759                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2760                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2761                         }
2762                         assert_eq!(total_amount_paid_msat, 250_000);
2763                 }
2764
2765                 {
2766                         // Attempt to route an exact amount is also fine
2767                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2768                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2769                         assert_eq!(route.paths.len(), 3);
2770                         let mut total_amount_paid_msat = 0;
2771                         for path in &route.paths {
2772                                 assert_eq!(path.len(), 2);
2773                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2774                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2775                         }
2776                         assert_eq!(total_amount_paid_msat, 290_000);
2777                 }
2778         }
2779
2780         #[test]
2781         fn long_mpp_route_test() {
2782                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2783                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2784
2785                 // We need a route consisting of 3 paths:
2786                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2787                 // Note that these paths overlap (channels 5, 12, 13).
2788                 // We will route 300 sats.
2789                 // Each path will have 100 sats capacity, those channels which
2790                 // are used twice will have 200 sats capacity.
2791
2792                 // Disable other potential paths.
2793                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2794                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2795                         short_channel_id: 2,
2796                         timestamp: 2,
2797                         flags: 2,
2798                         cltv_expiry_delta: 0,
2799                         htlc_minimum_msat: 0,
2800                         htlc_maximum_msat: OptionalField::Present(100_000),
2801                         fee_base_msat: 0,
2802                         fee_proportional_millionths: 0,
2803                         excess_data: Vec::new()
2804                 });
2805                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2806                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2807                         short_channel_id: 7,
2808                         timestamp: 2,
2809                         flags: 2,
2810                         cltv_expiry_delta: 0,
2811                         htlc_minimum_msat: 0,
2812                         htlc_maximum_msat: OptionalField::Present(100_000),
2813                         fee_base_msat: 0,
2814                         fee_proportional_millionths: 0,
2815                         excess_data: Vec::new()
2816                 });
2817
2818                 // Path via {node0, node2} is channels {1, 3, 5}.
2819                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2820                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2821                         short_channel_id: 1,
2822                         timestamp: 2,
2823                         flags: 0,
2824                         cltv_expiry_delta: 0,
2825                         htlc_minimum_msat: 0,
2826                         htlc_maximum_msat: OptionalField::Present(100_000),
2827                         fee_base_msat: 0,
2828                         fee_proportional_millionths: 0,
2829                         excess_data: Vec::new()
2830                 });
2831                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2832                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2833                         short_channel_id: 3,
2834                         timestamp: 2,
2835                         flags: 0,
2836                         cltv_expiry_delta: 0,
2837                         htlc_minimum_msat: 0,
2838                         htlc_maximum_msat: OptionalField::Present(100_000),
2839                         fee_base_msat: 0,
2840                         fee_proportional_millionths: 0,
2841                         excess_data: Vec::new()
2842                 });
2843
2844                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2845                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2846                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2847                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2848                         short_channel_id: 5,
2849                         timestamp: 2,
2850                         flags: 0,
2851                         cltv_expiry_delta: 0,
2852                         htlc_minimum_msat: 0,
2853                         htlc_maximum_msat: OptionalField::Present(200_000),
2854                         fee_base_msat: 0,
2855                         fee_proportional_millionths: 0,
2856                         excess_data: Vec::new()
2857                 });
2858
2859                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2860                 // Add 100 sats to the capacities of {12, 13}, because these channels
2861                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2862                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2863                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2864                         short_channel_id: 12,
2865                         timestamp: 2,
2866                         flags: 0,
2867                         cltv_expiry_delta: 0,
2868                         htlc_minimum_msat: 0,
2869                         htlc_maximum_msat: OptionalField::Present(200_000),
2870                         fee_base_msat: 0,
2871                         fee_proportional_millionths: 0,
2872                         excess_data: Vec::new()
2873                 });
2874                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2875                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2876                         short_channel_id: 13,
2877                         timestamp: 2,
2878                         flags: 0,
2879                         cltv_expiry_delta: 0,
2880                         htlc_minimum_msat: 0,
2881                         htlc_maximum_msat: OptionalField::Present(200_000),
2882                         fee_base_msat: 0,
2883                         fee_proportional_millionths: 0,
2884                         excess_data: Vec::new()
2885                 });
2886
2887                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2888                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2889                         short_channel_id: 6,
2890                         timestamp: 2,
2891                         flags: 0,
2892                         cltv_expiry_delta: 0,
2893                         htlc_minimum_msat: 0,
2894                         htlc_maximum_msat: OptionalField::Present(100_000),
2895                         fee_base_msat: 0,
2896                         fee_proportional_millionths: 0,
2897                         excess_data: Vec::new()
2898                 });
2899                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2900                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2901                         short_channel_id: 11,
2902                         timestamp: 2,
2903                         flags: 0,
2904                         cltv_expiry_delta: 0,
2905                         htlc_minimum_msat: 0,
2906                         htlc_maximum_msat: OptionalField::Present(100_000),
2907                         fee_base_msat: 0,
2908                         fee_proportional_millionths: 0,
2909                         excess_data: Vec::new()
2910                 });
2911
2912                 // Path via {node7, node2} is channels {12, 13, 5}.
2913                 // We already limited them to 200 sats (they are used twice for 100 sats).
2914                 // Nothing to do here.
2915
2916                 {
2917                         // Attempt to route more than available results in a failure.
2918                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2919                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
2920                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2921                         } else { panic!(); }
2922                 }
2923
2924                 {
2925                         // Now, attempt to route 300 sats (exact amount we can route).
2926                         // Our algorithm should provide us with these 3 paths, 100 sats each.
2927                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2928                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
2929                         assert_eq!(route.paths.len(), 3);
2930
2931                         let mut total_amount_paid_msat = 0;
2932                         for path in &route.paths {
2933                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2934                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2935                         }
2936                         assert_eq!(total_amount_paid_msat, 300_000);
2937                 }
2938
2939         }
2940
2941         #[test]
2942         fn mpp_cheaper_route_test() {
2943                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2944                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2945
2946                 // This test checks that if we have two cheaper paths and one more expensive path,
2947                 // so that liquidity-wise any 2 of 3 combination is sufficient,
2948                 // two cheaper paths will be taken.
2949                 // These paths have equal available liquidity.
2950
2951                 // We need a combination of 3 paths:
2952                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2953                 // Note that these paths overlap (channels 5, 12, 13).
2954                 // Each path will have 100 sats capacity, those channels which
2955                 // are used twice will have 200 sats capacity.
2956
2957                 // Disable other potential paths.
2958                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2959                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2960                         short_channel_id: 2,
2961                         timestamp: 2,
2962                         flags: 2,
2963                         cltv_expiry_delta: 0,
2964                         htlc_minimum_msat: 0,
2965                         htlc_maximum_msat: OptionalField::Present(100_000),
2966                         fee_base_msat: 0,
2967                         fee_proportional_millionths: 0,
2968                         excess_data: Vec::new()
2969                 });
2970                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2971                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2972                         short_channel_id: 7,
2973                         timestamp: 2,
2974                         flags: 2,
2975                         cltv_expiry_delta: 0,
2976                         htlc_minimum_msat: 0,
2977                         htlc_maximum_msat: OptionalField::Present(100_000),
2978                         fee_base_msat: 0,
2979                         fee_proportional_millionths: 0,
2980                         excess_data: Vec::new()
2981                 });
2982
2983                 // Path via {node0, node2} is channels {1, 3, 5}.
2984                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2985                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2986                         short_channel_id: 1,
2987                         timestamp: 2,
2988                         flags: 0,
2989                         cltv_expiry_delta: 0,
2990                         htlc_minimum_msat: 0,
2991                         htlc_maximum_msat: OptionalField::Present(100_000),
2992                         fee_base_msat: 0,
2993                         fee_proportional_millionths: 0,
2994                         excess_data: Vec::new()
2995                 });
2996                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2997                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2998                         short_channel_id: 3,
2999                         timestamp: 2,
3000                         flags: 0,
3001                         cltv_expiry_delta: 0,
3002                         htlc_minimum_msat: 0,
3003                         htlc_maximum_msat: OptionalField::Present(100_000),
3004                         fee_base_msat: 0,
3005                         fee_proportional_millionths: 0,
3006                         excess_data: Vec::new()
3007                 });
3008
3009                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3010                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3011                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3012                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3013                         short_channel_id: 5,
3014                         timestamp: 2,
3015                         flags: 0,
3016                         cltv_expiry_delta: 0,
3017                         htlc_minimum_msat: 0,
3018                         htlc_maximum_msat: OptionalField::Present(200_000),
3019                         fee_base_msat: 0,
3020                         fee_proportional_millionths: 0,
3021                         excess_data: Vec::new()
3022                 });
3023
3024                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3025                 // Add 100 sats to the capacities of {12, 13}, because these channels
3026                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3027                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3028                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3029                         short_channel_id: 12,
3030                         timestamp: 2,
3031                         flags: 0,
3032                         cltv_expiry_delta: 0,
3033                         htlc_minimum_msat: 0,
3034                         htlc_maximum_msat: OptionalField::Present(200_000),
3035                         fee_base_msat: 0,
3036                         fee_proportional_millionths: 0,
3037                         excess_data: Vec::new()
3038                 });
3039                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3040                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3041                         short_channel_id: 13,
3042                         timestamp: 2,
3043                         flags: 0,
3044                         cltv_expiry_delta: 0,
3045                         htlc_minimum_msat: 0,
3046                         htlc_maximum_msat: OptionalField::Present(200_000),
3047                         fee_base_msat: 0,
3048                         fee_proportional_millionths: 0,
3049                         excess_data: Vec::new()
3050                 });
3051
3052                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3053                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3054                         short_channel_id: 6,
3055                         timestamp: 2,
3056                         flags: 0,
3057                         cltv_expiry_delta: 0,
3058                         htlc_minimum_msat: 0,
3059                         htlc_maximum_msat: OptionalField::Present(100_000),
3060                         fee_base_msat: 1_000,
3061                         fee_proportional_millionths: 0,
3062                         excess_data: Vec::new()
3063                 });
3064                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3065                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3066                         short_channel_id: 11,
3067                         timestamp: 2,
3068                         flags: 0,
3069                         cltv_expiry_delta: 0,
3070                         htlc_minimum_msat: 0,
3071                         htlc_maximum_msat: OptionalField::Present(100_000),
3072                         fee_base_msat: 0,
3073                         fee_proportional_millionths: 0,
3074                         excess_data: Vec::new()
3075                 });
3076
3077                 // Path via {node7, node2} is channels {12, 13, 5}.
3078                 // We already limited them to 200 sats (they are used twice for 100 sats).
3079                 // Nothing to do here.
3080
3081                 {
3082                         // Now, attempt to route 180 sats.
3083                         // Our algorithm should provide us with these 2 paths.
3084                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3085                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3086                         assert_eq!(route.paths.len(), 2);
3087
3088                         let mut total_value_transferred_msat = 0;
3089                         let mut total_paid_msat = 0;
3090                         for path in &route.paths {
3091                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3092                                 total_value_transferred_msat += path.last().unwrap().fee_msat;
3093                                 for hop in path {
3094                                         total_paid_msat += hop.fee_msat;
3095                                 }
3096                         }
3097                         // If we paid fee, this would be higher.
3098                         assert_eq!(total_value_transferred_msat, 180_000);
3099                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3100                         assert_eq!(total_fees_paid, 0);
3101                 }
3102         }
3103
3104         #[test]
3105         fn fees_on_mpp_route_test() {
3106                 // This test makes sure that MPP algorithm properly takes into account
3107                 // fees charged on the channels, by making the fees impactful:
3108                 // if the fee is not properly accounted for, the behavior is different.
3109                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3110                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3111
3112                 // We need a route consisting of 2 paths:
3113                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3114                 // We will route 200 sats, Each path will have 100 sats capacity.
3115
3116                 // This test is not particularly stable: e.g.,
3117                 // there's a way to route via {node0, node2, node4}.
3118                 // It works while pathfinding is deterministic, but can be broken otherwise.
3119                 // It's fine to ignore this concern for now.
3120
3121                 // Disable other potential paths.
3122                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3123                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3124                         short_channel_id: 2,
3125                         timestamp: 2,
3126                         flags: 2,
3127                         cltv_expiry_delta: 0,
3128                         htlc_minimum_msat: 0,
3129                         htlc_maximum_msat: OptionalField::Present(100_000),
3130                         fee_base_msat: 0,
3131                         fee_proportional_millionths: 0,
3132                         excess_data: Vec::new()
3133                 });
3134
3135                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3136                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3137                         short_channel_id: 7,
3138                         timestamp: 2,
3139                         flags: 2,
3140                         cltv_expiry_delta: 0,
3141                         htlc_minimum_msat: 0,
3142                         htlc_maximum_msat: OptionalField::Present(100_000),
3143                         fee_base_msat: 0,
3144                         fee_proportional_millionths: 0,
3145                         excess_data: Vec::new()
3146                 });
3147
3148                 // Path via {node0, node2} is channels {1, 3, 5}.
3149                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3150                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3151                         short_channel_id: 1,
3152                         timestamp: 2,
3153                         flags: 0,
3154                         cltv_expiry_delta: 0,
3155                         htlc_minimum_msat: 0,
3156                         htlc_maximum_msat: OptionalField::Present(100_000),
3157                         fee_base_msat: 0,
3158                         fee_proportional_millionths: 0,
3159                         excess_data: Vec::new()
3160                 });
3161                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3162                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3163                         short_channel_id: 3,
3164                         timestamp: 2,
3165                         flags: 0,
3166                         cltv_expiry_delta: 0,
3167                         htlc_minimum_msat: 0,
3168                         htlc_maximum_msat: OptionalField::Present(100_000),
3169                         fee_base_msat: 0,
3170                         fee_proportional_millionths: 0,
3171                         excess_data: Vec::new()
3172                 });
3173
3174                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3175                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3176                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3177                         short_channel_id: 5,
3178                         timestamp: 2,
3179                         flags: 0,
3180                         cltv_expiry_delta: 0,
3181                         htlc_minimum_msat: 0,
3182                         htlc_maximum_msat: OptionalField::Present(100_000),
3183                         fee_base_msat: 0,
3184                         fee_proportional_millionths: 0,
3185                         excess_data: Vec::new()
3186                 });
3187
3188                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3189                 // All channels should be 100 sats capacity. But for the fee experiment,
3190                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3191                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3192                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3193                 // so no matter how large are other channels,
3194                 // the whole path will be limited by 100 sats with just these 2 conditions:
3195                 // - channel 12 capacity is 250 sats
3196                 // - fee for channel 6 is 150 sats
3197                 // Let's test this by enforcing these 2 conditions and removing other limits.
3198                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3199                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3200                         short_channel_id: 12,
3201                         timestamp: 2,
3202                         flags: 0,
3203                         cltv_expiry_delta: 0,
3204                         htlc_minimum_msat: 0,
3205                         htlc_maximum_msat: OptionalField::Present(250_000),
3206                         fee_base_msat: 0,
3207                         fee_proportional_millionths: 0,
3208                         excess_data: Vec::new()
3209                 });
3210                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3211                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3212                         short_channel_id: 13,
3213                         timestamp: 2,
3214                         flags: 0,
3215                         cltv_expiry_delta: 0,
3216                         htlc_minimum_msat: 0,
3217                         htlc_maximum_msat: OptionalField::Absent,
3218                         fee_base_msat: 0,
3219                         fee_proportional_millionths: 0,
3220                         excess_data: Vec::new()
3221                 });
3222
3223                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3224                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3225                         short_channel_id: 6,
3226                         timestamp: 2,
3227                         flags: 0,
3228                         cltv_expiry_delta: 0,
3229                         htlc_minimum_msat: 0,
3230                         htlc_maximum_msat: OptionalField::Absent,
3231                         fee_base_msat: 150_000,
3232                         fee_proportional_millionths: 0,
3233                         excess_data: Vec::new()
3234                 });
3235                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3236                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3237                         short_channel_id: 11,
3238                         timestamp: 2,
3239                         flags: 0,
3240                         cltv_expiry_delta: 0,
3241                         htlc_minimum_msat: 0,
3242                         htlc_maximum_msat: OptionalField::Absent,
3243                         fee_base_msat: 0,
3244                         fee_proportional_millionths: 0,
3245                         excess_data: Vec::new()
3246                 });
3247
3248                 {
3249                         // Attempt to route more than available results in a failure.
3250                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3251                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3252                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3253                         } else { panic!(); }
3254                 }
3255
3256                 {
3257                         // Now, attempt to route 200 sats (exact amount we can route).
3258                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3259                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3260                         assert_eq!(route.paths.len(), 2);
3261
3262                         let mut total_amount_paid_msat = 0;
3263                         for path in &route.paths {
3264                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3265                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3266                         }
3267                         assert_eq!(total_amount_paid_msat, 200_000);
3268                 }
3269
3270         }
3271
3272         #[test]
3273         fn drop_lowest_channel_mpp_route_test() {
3274                 // This test checks that low-capacity channel is dropped when after
3275                 // path finding we realize that we found more capacity than we need.
3276                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3277                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3278
3279                 // We need a route consisting of 3 paths:
3280                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3281
3282                 // The first and the second paths should be sufficient, but the third should be
3283                 // cheaper, so that we select it but drop later.
3284
3285                 // First, we set limits on these (previously unlimited) channels.
3286                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3287
3288                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3289                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3290                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3291                         short_channel_id: 1,
3292                         timestamp: 2,
3293                         flags: 0,
3294                         cltv_expiry_delta: 0,
3295                         htlc_minimum_msat: 0,
3296                         htlc_maximum_msat: OptionalField::Present(100_000),
3297                         fee_base_msat: 0,
3298                         fee_proportional_millionths: 0,
3299                         excess_data: Vec::new()
3300                 });
3301                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3302                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3303                         short_channel_id: 3,
3304                         timestamp: 2,
3305                         flags: 0,
3306                         cltv_expiry_delta: 0,
3307                         htlc_minimum_msat: 0,
3308                         htlc_maximum_msat: OptionalField::Present(50_000),
3309                         fee_base_msat: 100,
3310                         fee_proportional_millionths: 0,
3311                         excess_data: Vec::new()
3312                 });
3313
3314                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3315                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3316                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3317                         short_channel_id: 12,
3318                         timestamp: 2,
3319                         flags: 0,
3320                         cltv_expiry_delta: 0,
3321                         htlc_minimum_msat: 0,
3322                         htlc_maximum_msat: OptionalField::Present(60_000),
3323                         fee_base_msat: 100,
3324                         fee_proportional_millionths: 0,
3325                         excess_data: Vec::new()
3326                 });
3327                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3328                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3329                         short_channel_id: 13,
3330                         timestamp: 2,
3331                         flags: 0,
3332                         cltv_expiry_delta: 0,
3333                         htlc_minimum_msat: 0,
3334                         htlc_maximum_msat: OptionalField::Present(60_000),
3335                         fee_base_msat: 0,
3336                         fee_proportional_millionths: 0,
3337                         excess_data: Vec::new()
3338                 });
3339
3340                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3341                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3342                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3343                         short_channel_id: 2,
3344                         timestamp: 2,
3345                         flags: 0,
3346                         cltv_expiry_delta: 0,
3347                         htlc_minimum_msat: 0,
3348                         htlc_maximum_msat: OptionalField::Present(20_000),
3349                         fee_base_msat: 0,
3350                         fee_proportional_millionths: 0,
3351                         excess_data: Vec::new()
3352                 });
3353                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3354                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3355                         short_channel_id: 4,
3356                         timestamp: 2,
3357                         flags: 0,
3358                         cltv_expiry_delta: 0,
3359                         htlc_minimum_msat: 0,
3360                         htlc_maximum_msat: OptionalField::Present(20_000),
3361                         fee_base_msat: 0,
3362                         fee_proportional_millionths: 0,
3363                         excess_data: Vec::new()
3364                 });
3365
3366                 {
3367                         // Attempt to route more than available results in a failure.
3368                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3369                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3370                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3371                         } else { panic!(); }
3372                 }
3373
3374                 {
3375                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3376                         // Our algorithm should provide us with these 3 paths.
3377                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3378                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3379                         assert_eq!(route.paths.len(), 3);
3380                         let mut total_amount_paid_msat = 0;
3381                         for path in &route.paths {
3382                                 assert_eq!(path.len(), 2);
3383                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3384                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3385                         }
3386                         assert_eq!(total_amount_paid_msat, 125_000);
3387                 }
3388
3389                 {
3390                         // Attempt to route without the last small cheap channel
3391                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3392                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3393                         assert_eq!(route.paths.len(), 2);
3394                         let mut total_amount_paid_msat = 0;
3395                         for path in &route.paths {
3396                                 assert_eq!(path.len(), 2);
3397                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3398                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3399                         }
3400                         assert_eq!(total_amount_paid_msat, 90_000);
3401                 }
3402         }
3403 }
3404
3405 #[cfg(all(test, feature = "unstable"))]
3406 mod benches {
3407         use super::*;
3408         use util::logger::{Logger, Record};
3409
3410         use std::fs::File;
3411         use test::Bencher;
3412
3413         struct DummyLogger {}
3414         impl Logger for DummyLogger {
3415                 fn log(&self, _record: &Record) {}
3416         }
3417
3418         #[bench]
3419         fn generate_routes(bench: &mut Bencher) {
3420                 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");
3421                 let graph = NetworkGraph::read(&mut d).unwrap();
3422
3423                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3424                 let mut path_endpoints = Vec::new();
3425                 let mut seed: usize = 0xdeadbeef;
3426                 'load_endpoints: for _ in 0..100 {
3427                         loop {
3428                                 seed *= 0xdeadbeef;
3429                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3430                                 seed *= 0xdeadbeef;
3431                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3432                                 let amt = seed as u64 % 1_000_000;
3433                                 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3434                                         path_endpoints.push((src, dst, amt));
3435                                         continue 'load_endpoints;
3436                                 }
3437                         }
3438                 }
3439
3440                 // ...then benchmark finding paths between the nodes we learned.
3441                 let mut idx = 0;
3442                 bench.iter(|| {
3443                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3444                         assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3445                         idx += 1;
3446                 });
3447         }
3448
3449         #[bench]
3450         fn generate_mpp_routes(bench: &mut Bencher) {
3451                 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");
3452                 let graph = NetworkGraph::read(&mut d).unwrap();
3453
3454                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3455                 let mut path_endpoints = Vec::new();
3456                 let mut seed: usize = 0xdeadbeef;
3457                 'load_endpoints: for _ in 0..100 {
3458                         loop {
3459                                 seed *= 0xdeadbeef;
3460                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3461                                 seed *= 0xdeadbeef;
3462                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3463                                 let amt = seed as u64 % 1_000_000;
3464                                 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
3465                                         path_endpoints.push((src, dst, amt));
3466                                         continue 'load_endpoints;
3467                                 }
3468                         }
3469                 }
3470
3471                 // ...then benchmark finding paths between the nodes we learned.
3472                 let mut idx = 0;
3473                 bench.iter(|| {
3474                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3475                         assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());
3476                         idx += 1;
3477                 });
3478         }
3479 }