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