Add an Option<>al InvoiceFeatures object for the payee in get_route
[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, InvoiceFeatures};
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, payee_features: Option<InvoiceFeatures>, 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::<Vec<RouteHop>>::new();
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         if let Some(features) = &payee_features {
970                 for path in selected_paths.iter_mut() {
971                         path.last_mut().unwrap().node_features = features.to_context();
972                 }
973         }
974
975         let route = Route { paths: selected_paths };
976         log_trace!(logger, "Got route: {}", log_route!(route));
977         Ok(route)
978 }
979
980 #[cfg(test)]
981 mod tests {
982         use routing::router::{get_route, RouteHint, RoutingFees};
983         use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
984         use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
985         use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
986            NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
987         use ln::channelmanager;
988         use util::test_utils;
989         use util::ser::Writeable;
990
991         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
992         use bitcoin::hashes::Hash;
993         use bitcoin::network::constants::Network;
994         use bitcoin::blockdata::constants::genesis_block;
995         use bitcoin::blockdata::script::Builder;
996         use bitcoin::blockdata::opcodes;
997         use bitcoin::blockdata::transaction::TxOut;
998
999         use hex;
1000
1001         use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1002         use bitcoin::secp256k1::{Secp256k1, All};
1003
1004         use std::sync::Arc;
1005
1006         // Using the same keys for LN and BTC ids
1007         fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1008            node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1009                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1010                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1011
1012                 let unsigned_announcement = UnsignedChannelAnnouncement {
1013                         features,
1014                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1015                         short_channel_id,
1016                         node_id_1,
1017                         node_id_2,
1018                         bitcoin_key_1: node_id_1,
1019                         bitcoin_key_2: node_id_2,
1020                         excess_data: Vec::new(),
1021                 };
1022
1023                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1024                 let valid_announcement = ChannelAnnouncement {
1025                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1026                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1027                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1028                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1029                         contents: unsigned_announcement.clone(),
1030                 };
1031                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1032                         Ok(res) => assert!(res),
1033                         _ => panic!()
1034                 };
1035         }
1036
1037         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) {
1038                 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1039                 let valid_channel_update = ChannelUpdate {
1040                         signature: secp_ctx.sign(&msghash, node_privkey),
1041                         contents: update.clone()
1042                 };
1043
1044                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1045                         Ok(res) => assert!(res),
1046                         Err(_) => panic!()
1047                 };
1048         }
1049
1050         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,
1051            features: NodeFeatures, timestamp: u32) {
1052                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1053                 let unsigned_announcement = UnsignedNodeAnnouncement {
1054                         features,
1055                         timestamp,
1056                         node_id,
1057                         rgb: [0; 3],
1058                         alias: [0; 32],
1059                         addresses: Vec::new(),
1060                         excess_address_data: Vec::new(),
1061                         excess_data: Vec::new(),
1062                 };
1063                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1064                 let valid_announcement = NodeAnnouncement {
1065                         signature: secp_ctx.sign(&msghash, node_privkey),
1066                         contents: unsigned_announcement.clone()
1067                 };
1068
1069                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1070                         Ok(_) => (),
1071                         Err(_) => panic!()
1072                 };
1073         }
1074
1075         fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1076                 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1077                         SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1078                 }).collect();
1079
1080                 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1081
1082                 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1083                 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1084
1085                 (our_privkey, our_id, privkeys, pubkeys)
1086         }
1087
1088         fn id_to_feature_flags(id: u8) -> Vec<u8> {
1089                 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1090                 // test for it later.
1091                 let idx = (id - 1) * 2 + 1;
1092                 if idx > 8*3 {
1093                         vec![1 << (idx - 8*3), 0, 0, 0]
1094                 } else if idx > 8*2 {
1095                         vec![1 << (idx - 8*2), 0, 0]
1096                 } else if idx > 8*1 {
1097                         vec![1 << (idx - 8*1), 0]
1098                 } else {
1099                         vec![1 << idx]
1100                 }
1101         }
1102
1103         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>) {
1104                 let secp_ctx = Secp256k1::new();
1105                 let logger = Arc::new(test_utils::TestLogger::new());
1106                 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1107                 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1108                 // Build network from our_id to node7:
1109                 //
1110                 //        -1(1)2-  node0  -1(3)2-
1111                 //       /                       \
1112                 // our_id -1(12)2- node7 -1(13)2--- node2
1113                 //       \                       /
1114                 //        -1(2)2-  node1  -1(4)2-
1115                 //
1116                 //
1117                 // chan1  1-to-2: disabled
1118                 // chan1  2-to-1: enabled, 0 fee
1119                 //
1120                 // chan2  1-to-2: enabled, ignored fee
1121                 // chan2  2-to-1: enabled, 0 fee
1122                 //
1123                 // chan3  1-to-2: enabled, 0 fee
1124                 // chan3  2-to-1: enabled, 100 msat fee
1125                 //
1126                 // chan4  1-to-2: enabled, 100% fee
1127                 // chan4  2-to-1: enabled, 0 fee
1128                 //
1129                 // chan12 1-to-2: enabled, ignored fee
1130                 // chan12 2-to-1: enabled, 0 fee
1131                 //
1132                 // chan13 1-to-2: enabled, 200% fee
1133                 // chan13 2-to-1: enabled, 0 fee
1134                 //
1135                 //
1136                 //       -1(5)2- node3 -1(8)2--
1137                 //       |         2          |
1138                 //       |       (11)         |
1139                 //      /          1           \
1140                 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1141                 //      \                      /
1142                 //       -1(7)2- node5 -1(10)2-
1143                 //
1144                 // chan5  1-to-2: enabled, 100 msat fee
1145                 // chan5  2-to-1: enabled, 0 fee
1146                 //
1147                 // chan6  1-to-2: enabled, 0 fee
1148                 // chan6  2-to-1: enabled, 0 fee
1149                 //
1150                 // chan7  1-to-2: enabled, 100% fee
1151                 // chan7  2-to-1: enabled, 0 fee
1152                 //
1153                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
1154                 // chan8  2-to-1: enabled, 0 fee
1155                 //
1156                 // chan9  1-to-2: enabled, 1001 msat fee
1157                 // chan9  2-to-1: enabled, 0 fee
1158                 //
1159                 // chan10 1-to-2: enabled, 0 fee
1160                 // chan10 2-to-1: enabled, 0 fee
1161                 //
1162                 // chan11 1-to-2: enabled, 0 fee
1163                 // chan11 2-to-1: enabled, 0 fee
1164
1165                 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1166
1167                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1168                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1169                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1170                         short_channel_id: 1,
1171                         timestamp: 1,
1172                         flags: 1,
1173                         cltv_expiry_delta: 0,
1174                         htlc_minimum_msat: 0,
1175                         htlc_maximum_msat: OptionalField::Absent,
1176                         fee_base_msat: 0,
1177                         fee_proportional_millionths: 0,
1178                         excess_data: Vec::new()
1179                 });
1180
1181                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1182
1183                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1184                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1185                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1186                         short_channel_id: 2,
1187                         timestamp: 1,
1188                         flags: 0,
1189                         cltv_expiry_delta: u16::max_value(),
1190                         htlc_minimum_msat: 0,
1191                         htlc_maximum_msat: OptionalField::Absent,
1192                         fee_base_msat: u32::max_value(),
1193                         fee_proportional_millionths: u32::max_value(),
1194                         excess_data: Vec::new()
1195                 });
1196                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1197                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1198                         short_channel_id: 2,
1199                         timestamp: 1,
1200                         flags: 1,
1201                         cltv_expiry_delta: 0,
1202                         htlc_minimum_msat: 0,
1203                         htlc_maximum_msat: OptionalField::Absent,
1204                         fee_base_msat: 0,
1205                         fee_proportional_millionths: 0,
1206                         excess_data: Vec::new()
1207                 });
1208
1209                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1210
1211                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1212                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1213                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1214                         short_channel_id: 12,
1215                         timestamp: 1,
1216                         flags: 0,
1217                         cltv_expiry_delta: u16::max_value(),
1218                         htlc_minimum_msat: 0,
1219                         htlc_maximum_msat: OptionalField::Absent,
1220                         fee_base_msat: u32::max_value(),
1221                         fee_proportional_millionths: u32::max_value(),
1222                         excess_data: Vec::new()
1223                 });
1224                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1225                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1226                         short_channel_id: 12,
1227                         timestamp: 1,
1228                         flags: 1,
1229                         cltv_expiry_delta: 0,
1230                         htlc_minimum_msat: 0,
1231                         htlc_maximum_msat: OptionalField::Absent,
1232                         fee_base_msat: 0,
1233                         fee_proportional_millionths: 0,
1234                         excess_data: Vec::new()
1235                 });
1236
1237                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1238
1239                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1240                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1241                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1242                         short_channel_id: 3,
1243                         timestamp: 1,
1244                         flags: 0,
1245                         cltv_expiry_delta: (3 << 8) | 1,
1246                         htlc_minimum_msat: 0,
1247                         htlc_maximum_msat: OptionalField::Absent,
1248                         fee_base_msat: 0,
1249                         fee_proportional_millionths: 0,
1250                         excess_data: Vec::new()
1251                 });
1252                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1253                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1254                         short_channel_id: 3,
1255                         timestamp: 1,
1256                         flags: 1,
1257                         cltv_expiry_delta: (3 << 8) | 2,
1258                         htlc_minimum_msat: 0,
1259                         htlc_maximum_msat: OptionalField::Absent,
1260                         fee_base_msat: 100,
1261                         fee_proportional_millionths: 0,
1262                         excess_data: Vec::new()
1263                 });
1264
1265                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1266                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1267                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1268                         short_channel_id: 4,
1269                         timestamp: 1,
1270                         flags: 0,
1271                         cltv_expiry_delta: (4 << 8) | 1,
1272                         htlc_minimum_msat: 0,
1273                         htlc_maximum_msat: OptionalField::Absent,
1274                         fee_base_msat: 0,
1275                         fee_proportional_millionths: 1000000,
1276                         excess_data: Vec::new()
1277                 });
1278                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1279                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1280                         short_channel_id: 4,
1281                         timestamp: 1,
1282                         flags: 1,
1283                         cltv_expiry_delta: (4 << 8) | 2,
1284                         htlc_minimum_msat: 0,
1285                         htlc_maximum_msat: OptionalField::Absent,
1286                         fee_base_msat: 0,
1287                         fee_proportional_millionths: 0,
1288                         excess_data: Vec::new()
1289                 });
1290
1291                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1292                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1293                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1294                         short_channel_id: 13,
1295                         timestamp: 1,
1296                         flags: 0,
1297                         cltv_expiry_delta: (13 << 8) | 1,
1298                         htlc_minimum_msat: 0,
1299                         htlc_maximum_msat: OptionalField::Absent,
1300                         fee_base_msat: 0,
1301                         fee_proportional_millionths: 2000000,
1302                         excess_data: Vec::new()
1303                 });
1304                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1305                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1306                         short_channel_id: 13,
1307                         timestamp: 1,
1308                         flags: 1,
1309                         cltv_expiry_delta: (13 << 8) | 2,
1310                         htlc_minimum_msat: 0,
1311                         htlc_maximum_msat: OptionalField::Absent,
1312                         fee_base_msat: 0,
1313                         fee_proportional_millionths: 0,
1314                         excess_data: Vec::new()
1315                 });
1316
1317                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1318
1319                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1320                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1321                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1322                         short_channel_id: 6,
1323                         timestamp: 1,
1324                         flags: 0,
1325                         cltv_expiry_delta: (6 << 8) | 1,
1326                         htlc_minimum_msat: 0,
1327                         htlc_maximum_msat: OptionalField::Absent,
1328                         fee_base_msat: 0,
1329                         fee_proportional_millionths: 0,
1330                         excess_data: Vec::new()
1331                 });
1332                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1333                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1334                         short_channel_id: 6,
1335                         timestamp: 1,
1336                         flags: 1,
1337                         cltv_expiry_delta: (6 << 8) | 2,
1338                         htlc_minimum_msat: 0,
1339                         htlc_maximum_msat: OptionalField::Absent,
1340                         fee_base_msat: 0,
1341                         fee_proportional_millionths: 0,
1342                         excess_data: Vec::new(),
1343                 });
1344
1345                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1346                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1347                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1348                         short_channel_id: 11,
1349                         timestamp: 1,
1350                         flags: 0,
1351                         cltv_expiry_delta: (11 << 8) | 1,
1352                         htlc_minimum_msat: 0,
1353                         htlc_maximum_msat: OptionalField::Absent,
1354                         fee_base_msat: 0,
1355                         fee_proportional_millionths: 0,
1356                         excess_data: Vec::new()
1357                 });
1358                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1359                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1360                         short_channel_id: 11,
1361                         timestamp: 1,
1362                         flags: 1,
1363                         cltv_expiry_delta: (11 << 8) | 2,
1364                         htlc_minimum_msat: 0,
1365                         htlc_maximum_msat: OptionalField::Absent,
1366                         fee_base_msat: 0,
1367                         fee_proportional_millionths: 0,
1368                         excess_data: Vec::new()
1369                 });
1370
1371                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1372
1373                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1374
1375                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1376                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1377                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1378                         short_channel_id: 7,
1379                         timestamp: 1,
1380                         flags: 0,
1381                         cltv_expiry_delta: (7 << 8) | 1,
1382                         htlc_minimum_msat: 0,
1383                         htlc_maximum_msat: OptionalField::Absent,
1384                         fee_base_msat: 0,
1385                         fee_proportional_millionths: 1000000,
1386                         excess_data: Vec::new()
1387                 });
1388                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1389                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1390                         short_channel_id: 7,
1391                         timestamp: 1,
1392                         flags: 1,
1393                         cltv_expiry_delta: (7 << 8) | 2,
1394                         htlc_minimum_msat: 0,
1395                         htlc_maximum_msat: OptionalField::Absent,
1396                         fee_base_msat: 0,
1397                         fee_proportional_millionths: 0,
1398                         excess_data: Vec::new()
1399                 });
1400
1401                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1402
1403                 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1404         }
1405
1406         #[test]
1407         fn simple_route_test() {
1408                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1409                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1410
1411                 // Simple route to 2 via 1
1412
1413                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 0, 42, Arc::clone(&logger)) {
1414                         assert_eq!(err, "Cannot send a payment of 0 msat");
1415                 } else { panic!(); }
1416
1417                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1418                 assert_eq!(route.paths[0].len(), 2);
1419
1420                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1421                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1422                 assert_eq!(route.paths[0][0].fee_msat, 100);
1423                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1424                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1425                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1426
1427                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1428                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1429                 assert_eq!(route.paths[0][1].fee_msat, 100);
1430                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1431                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1432                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1433         }
1434
1435         #[test]
1436         fn invalid_first_hop_test() {
1437                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1438                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1439
1440                 // Simple route to 2 via 1
1441
1442                 let our_chans = vec![channelmanager::ChannelDetails {
1443                         channel_id: [0; 32],
1444                         short_channel_id: Some(2),
1445                         remote_network_id: our_id,
1446                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1447                         channel_value_satoshis: 100000,
1448                         user_id: 0,
1449                         outbound_capacity_msat: 100000,
1450                         inbound_capacity_msat: 100000,
1451                         is_live: true,
1452                 }];
1453
1454                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)) {
1455                         assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1456                 } else { panic!(); }
1457
1458                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1459                 assert_eq!(route.paths[0].len(), 2);
1460         }
1461
1462         #[test]
1463         fn htlc_minimum_test() {
1464                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1465                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1466
1467                 // Simple route to 2 via 1
1468
1469                 // Disable other paths
1470                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1471                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1472                         short_channel_id: 12,
1473                         timestamp: 2,
1474                         flags: 2, // to disable
1475                         cltv_expiry_delta: 0,
1476                         htlc_minimum_msat: 0,
1477                         htlc_maximum_msat: OptionalField::Absent,
1478                         fee_base_msat: 0,
1479                         fee_proportional_millionths: 0,
1480                         excess_data: Vec::new()
1481                 });
1482                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1483                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1484                         short_channel_id: 3,
1485                         timestamp: 2,
1486                         flags: 2, // to disable
1487                         cltv_expiry_delta: 0,
1488                         htlc_minimum_msat: 0,
1489                         htlc_maximum_msat: OptionalField::Absent,
1490                         fee_base_msat: 0,
1491                         fee_proportional_millionths: 0,
1492                         excess_data: Vec::new()
1493                 });
1494                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1495                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1496                         short_channel_id: 13,
1497                         timestamp: 2,
1498                         flags: 2, // to disable
1499                         cltv_expiry_delta: 0,
1500                         htlc_minimum_msat: 0,
1501                         htlc_maximum_msat: OptionalField::Absent,
1502                         fee_base_msat: 0,
1503                         fee_proportional_millionths: 0,
1504                         excess_data: Vec::new()
1505                 });
1506                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1507                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1508                         short_channel_id: 6,
1509                         timestamp: 2,
1510                         flags: 2, // to disable
1511                         cltv_expiry_delta: 0,
1512                         htlc_minimum_msat: 0,
1513                         htlc_maximum_msat: OptionalField::Absent,
1514                         fee_base_msat: 0,
1515                         fee_proportional_millionths: 0,
1516                         excess_data: Vec::new()
1517                 });
1518                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1519                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1520                         short_channel_id: 7,
1521                         timestamp: 2,
1522                         flags: 2, // to disable
1523                         cltv_expiry_delta: 0,
1524                         htlc_minimum_msat: 0,
1525                         htlc_maximum_msat: OptionalField::Absent,
1526                         fee_base_msat: 0,
1527                         fee_proportional_millionths: 0,
1528                         excess_data: Vec::new()
1529                 });
1530
1531                 // Check against amount_to_transfer_over_msat.
1532                 // Set minimal HTLC of 200_000_000 msat.
1533                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1534                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1535                         short_channel_id: 2,
1536                         timestamp: 3,
1537                         flags: 0,
1538                         cltv_expiry_delta: 0,
1539                         htlc_minimum_msat: 200_000_000,
1540                         htlc_maximum_msat: OptionalField::Absent,
1541                         fee_base_msat: 0,
1542                         fee_proportional_millionths: 0,
1543                         excess_data: Vec::new()
1544                 });
1545
1546                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1547                 // be used.
1548                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1549                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1550                         short_channel_id: 4,
1551                         timestamp: 3,
1552                         flags: 0,
1553                         cltv_expiry_delta: 0,
1554                         htlc_minimum_msat: 0,
1555                         htlc_maximum_msat: OptionalField::Present(199_999_999),
1556                         fee_base_msat: 0,
1557                         fee_proportional_millionths: 0,
1558                         excess_data: Vec::new()
1559                 });
1560
1561                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1562                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)) {
1563                         assert_eq!(err, "Failed to find a path to the given destination");
1564                 } else { panic!(); }
1565
1566                 // Lift the restriction on the first hop.
1567                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1568                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1569                         short_channel_id: 2,
1570                         timestamp: 4,
1571                         flags: 0,
1572                         cltv_expiry_delta: 0,
1573                         htlc_minimum_msat: 0,
1574                         htlc_maximum_msat: OptionalField::Absent,
1575                         fee_base_msat: 0,
1576                         fee_proportional_millionths: 0,
1577                         excess_data: Vec::new()
1578                 });
1579
1580                 // A payment above the minimum should pass
1581                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)).unwrap();
1582                 assert_eq!(route.paths[0].len(), 2);
1583         }
1584
1585         #[test]
1586         fn htlc_minimum_overpay_test() {
1587                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1588                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1589
1590                 // A route to node#2 via two paths.
1591                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1592                 // Thus, they can't send 60 without overpaying.
1593                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1594                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1595                         short_channel_id: 2,
1596                         timestamp: 2,
1597                         flags: 0,
1598                         cltv_expiry_delta: 0,
1599                         htlc_minimum_msat: 35_000,
1600                         htlc_maximum_msat: OptionalField::Present(40_000),
1601                         fee_base_msat: 0,
1602                         fee_proportional_millionths: 0,
1603                         excess_data: Vec::new()
1604                 });
1605                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1606                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1607                         short_channel_id: 12,
1608                         timestamp: 3,
1609                         flags: 0,
1610                         cltv_expiry_delta: 0,
1611                         htlc_minimum_msat: 35_000,
1612                         htlc_maximum_msat: OptionalField::Present(40_000),
1613                         fee_base_msat: 0,
1614                         fee_proportional_millionths: 0,
1615                         excess_data: Vec::new()
1616                 });
1617
1618                 // Make 0 fee.
1619                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1620                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1621                         short_channel_id: 13,
1622                         timestamp: 2,
1623                         flags: 0,
1624                         cltv_expiry_delta: 0,
1625                         htlc_minimum_msat: 0,
1626                         htlc_maximum_msat: OptionalField::Absent,
1627                         fee_base_msat: 0,
1628                         fee_proportional_millionths: 0,
1629                         excess_data: Vec::new()
1630                 });
1631                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1632                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1633                         short_channel_id: 4,
1634                         timestamp: 2,
1635                         flags: 0,
1636                         cltv_expiry_delta: 0,
1637                         htlc_minimum_msat: 0,
1638                         htlc_maximum_msat: OptionalField::Absent,
1639                         fee_base_msat: 0,
1640                         fee_proportional_millionths: 0,
1641                         excess_data: Vec::new()
1642                 });
1643
1644                 // Disable other paths
1645                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1646                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1647                         short_channel_id: 1,
1648                         timestamp: 3,
1649                         flags: 2, // to disable
1650                         cltv_expiry_delta: 0,
1651                         htlc_minimum_msat: 0,
1652                         htlc_maximum_msat: OptionalField::Absent,
1653                         fee_base_msat: 0,
1654                         fee_proportional_millionths: 0,
1655                         excess_data: Vec::new()
1656                 });
1657
1658                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1659                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1660                 // Overpay fees to hit htlc_minimum_msat.
1661                 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1662                 // TODO: this could be better balanced to overpay 10k and not 15k.
1663                 assert_eq!(overpaid_fees, 15_000);
1664
1665                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1666                 // while taking even more fee to match htlc_minimum_msat.
1667                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1668                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1669                         short_channel_id: 12,
1670                         timestamp: 4,
1671                         flags: 0,
1672                         cltv_expiry_delta: 0,
1673                         htlc_minimum_msat: 65_000,
1674                         htlc_maximum_msat: OptionalField::Present(80_000),
1675                         fee_base_msat: 0,
1676                         fee_proportional_millionths: 0,
1677                         excess_data: Vec::new()
1678                 });
1679                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1680                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1681                         short_channel_id: 2,
1682                         timestamp: 3,
1683                         flags: 0,
1684                         cltv_expiry_delta: 0,
1685                         htlc_minimum_msat: 0,
1686                         htlc_maximum_msat: OptionalField::Absent,
1687                         fee_base_msat: 0,
1688                         fee_proportional_millionths: 0,
1689                         excess_data: Vec::new()
1690                 });
1691                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1692                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1693                         short_channel_id: 4,
1694                         timestamp: 4,
1695                         flags: 0,
1696                         cltv_expiry_delta: 0,
1697                         htlc_minimum_msat: 0,
1698                         htlc_maximum_msat: OptionalField::Absent,
1699                         fee_base_msat: 0,
1700                         fee_proportional_millionths: 100_000,
1701                         excess_data: Vec::new()
1702                 });
1703
1704                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1705                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1706                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1707                 assert_eq!(route.paths.len(), 1);
1708                 assert_eq!(route.paths[0][0].short_channel_id, 12);
1709                 let fees = route.paths[0][0].fee_msat;
1710                 assert_eq!(fees, 5_000);
1711
1712                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1713                         Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1714                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1715                 // the other channel.
1716                 assert_eq!(route.paths.len(), 1);
1717                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1718                 let fees = route.paths[0][0].fee_msat;
1719                 assert_eq!(fees, 5_000);
1720         }
1721
1722         #[test]
1723         fn disable_channels_test() {
1724                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1725                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1726
1727                 // // Disable channels 4 and 12 by flags=2
1728                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1729                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1730                         short_channel_id: 4,
1731                         timestamp: 2,
1732                         flags: 2, // to disable
1733                         cltv_expiry_delta: 0,
1734                         htlc_minimum_msat: 0,
1735                         htlc_maximum_msat: OptionalField::Absent,
1736                         fee_base_msat: 0,
1737                         fee_proportional_millionths: 0,
1738                         excess_data: Vec::new()
1739                 });
1740                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1741                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1742                         short_channel_id: 12,
1743                         timestamp: 2,
1744                         flags: 2, // to disable
1745                         cltv_expiry_delta: 0,
1746                         htlc_minimum_msat: 0,
1747                         htlc_maximum_msat: OptionalField::Absent,
1748                         fee_base_msat: 0,
1749                         fee_proportional_millionths: 0,
1750                         excess_data: Vec::new()
1751                 });
1752
1753                 // If all the channels require some features we don't understand, route should fail
1754                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1755                         assert_eq!(err, "Failed to find a path to the given destination");
1756                 } else { panic!(); }
1757
1758                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1759                 let our_chans = vec![channelmanager::ChannelDetails {
1760                         channel_id: [0; 32],
1761                         short_channel_id: Some(42),
1762                         remote_network_id: nodes[7].clone(),
1763                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1764                         channel_value_satoshis: 0,
1765                         user_id: 0,
1766                         outbound_capacity_msat: 250_000_000,
1767                         inbound_capacity_msat: 0,
1768                         is_live: true,
1769                 }];
1770                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()),  &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1771                 assert_eq!(route.paths[0].len(), 2);
1772
1773                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1774                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1775                 assert_eq!(route.paths[0][0].fee_msat, 200);
1776                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1777                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1778                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1779
1780                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1781                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1782                 assert_eq!(route.paths[0][1].fee_msat, 100);
1783                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1784                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1785                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1786         }
1787
1788         #[test]
1789         fn disable_node_test() {
1790                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1791                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1792
1793                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1794                 let mut unknown_features = NodeFeatures::known();
1795                 unknown_features.set_required_unknown_bits();
1796                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1797                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1798                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1799
1800                 // If all nodes require some features we don't understand, route should fail
1801                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1802                         assert_eq!(err, "Failed to find a path to the given destination");
1803                 } else { panic!(); }
1804
1805                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1806                 let our_chans = vec![channelmanager::ChannelDetails {
1807                         channel_id: [0; 32],
1808                         short_channel_id: Some(42),
1809                         remote_network_id: nodes[7].clone(),
1810                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1811                         channel_value_satoshis: 0,
1812                         user_id: 0,
1813                         outbound_capacity_msat: 250_000_000,
1814                         inbound_capacity_msat: 0,
1815                         is_live: true,
1816                 }];
1817                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1818                 assert_eq!(route.paths[0].len(), 2);
1819
1820                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1821                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1822                 assert_eq!(route.paths[0][0].fee_msat, 200);
1823                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1824                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1825                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1826
1827                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1828                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1829                 assert_eq!(route.paths[0][1].fee_msat, 100);
1830                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1831                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1832                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1833
1834                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1835                 // naively) assume that the user checked the feature bits on the invoice, which override
1836                 // the node_announcement.
1837         }
1838
1839         #[test]
1840         fn our_chans_test() {
1841                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1842                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1843
1844                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1845                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1846                 assert_eq!(route.paths[0].len(), 3);
1847
1848                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1849                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1850                 assert_eq!(route.paths[0][0].fee_msat, 200);
1851                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1852                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1853                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1854
1855                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1856                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1857                 assert_eq!(route.paths[0][1].fee_msat, 100);
1858                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1859                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1860                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1861
1862                 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1863                 assert_eq!(route.paths[0][2].short_channel_id, 3);
1864                 assert_eq!(route.paths[0][2].fee_msat, 100);
1865                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1866                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1867                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1868
1869                 // If we specify a channel to node7, that overrides our local channel view and that gets used
1870                 let our_chans = vec![channelmanager::ChannelDetails {
1871                         channel_id: [0; 32],
1872                         short_channel_id: Some(42),
1873                         remote_network_id: nodes[7].clone(),
1874                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1875                         channel_value_satoshis: 0,
1876                         user_id: 0,
1877                         outbound_capacity_msat: 250_000_000,
1878                         inbound_capacity_msat: 0,
1879                         is_live: true,
1880                 }];
1881                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1882                 assert_eq!(route.paths[0].len(), 2);
1883
1884                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1885                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1886                 assert_eq!(route.paths[0][0].fee_msat, 200);
1887                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1888                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1889                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1890
1891                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1892                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1893                 assert_eq!(route.paths[0][1].fee_msat, 100);
1894                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1895                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1896                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1897         }
1898
1899         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1900                 let zero_fees = RoutingFees {
1901                         base_msat: 0,
1902                         proportional_millionths: 0,
1903                 };
1904                 vec!(RouteHint {
1905                         src_node_id: nodes[3].clone(),
1906                         short_channel_id: 8,
1907                         fees: zero_fees,
1908                         cltv_expiry_delta: (8 << 8) | 1,
1909                         htlc_minimum_msat: None,
1910                         htlc_maximum_msat: None,
1911                 }, RouteHint {
1912                         src_node_id: nodes[4].clone(),
1913                         short_channel_id: 9,
1914                         fees: RoutingFees {
1915                                 base_msat: 1001,
1916                                 proportional_millionths: 0,
1917                         },
1918                         cltv_expiry_delta: (9 << 8) | 1,
1919                         htlc_minimum_msat: None,
1920                         htlc_maximum_msat: None,
1921                 }, RouteHint {
1922                         src_node_id: nodes[5].clone(),
1923                         short_channel_id: 10,
1924                         fees: zero_fees,
1925                         cltv_expiry_delta: (10 << 8) | 1,
1926                         htlc_minimum_msat: None,
1927                         htlc_maximum_msat: None,
1928                 })
1929         }
1930
1931         #[test]
1932         fn last_hops_test() {
1933                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1934                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1935
1936                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
1937
1938                 // First check that lst hop can't have its source as the payee.
1939                 let invalid_last_hop = RouteHint {
1940                         src_node_id: nodes[6],
1941                         short_channel_id: 8,
1942                         fees: RoutingFees {
1943                                 base_msat: 1000,
1944                                 proportional_millionths: 0,
1945                         },
1946                         cltv_expiry_delta: (8 << 8) | 1,
1947                         htlc_minimum_msat: None,
1948                         htlc_maximum_msat: None,
1949                 };
1950
1951                 let mut invalid_last_hops = last_hops(&nodes);
1952                 invalid_last_hops.push(invalid_last_hop);
1953                 {
1954                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)) {
1955                                 assert_eq!(err, "Last hop cannot have a payee as a source.");
1956                         } else { panic!(); }
1957                 }
1958
1959                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
1960                 assert_eq!(route.paths[0].len(), 5);
1961
1962                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1963                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1964                 assert_eq!(route.paths[0][0].fee_msat, 100);
1965                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1966                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1967                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1968
1969                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1970                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1971                 assert_eq!(route.paths[0][1].fee_msat, 0);
1972                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1973                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1974                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1975
1976                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
1977                 assert_eq!(route.paths[0][2].short_channel_id, 6);
1978                 assert_eq!(route.paths[0][2].fee_msat, 0);
1979                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1980                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
1981                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
1982
1983                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
1984                 assert_eq!(route.paths[0][3].short_channel_id, 11);
1985                 assert_eq!(route.paths[0][3].fee_msat, 0);
1986                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1987                 // If we have a peer in the node map, we'll use their features here since we don't have
1988                 // a way of figuring out their features from the invoice:
1989                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
1990                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
1991
1992                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
1993                 assert_eq!(route.paths[0][4].short_channel_id, 8);
1994                 assert_eq!(route.paths[0][4].fee_msat, 100);
1995                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1996                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1997                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1998         }
1999
2000         #[test]
2001         fn our_chans_last_hop_connect_test() {
2002                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2003                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2004
2005                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2006                 let our_chans = vec![channelmanager::ChannelDetails {
2007                         channel_id: [0; 32],
2008                         short_channel_id: Some(42),
2009                         remote_network_id: nodes[3].clone(),
2010                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2011                         channel_value_satoshis: 0,
2012                         user_id: 0,
2013                         outbound_capacity_msat: 250_000_000,
2014                         inbound_capacity_msat: 0,
2015                         is_live: true,
2016                 }];
2017                 let mut last_hops = last_hops(&nodes);
2018                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2019                 assert_eq!(route.paths[0].len(), 2);
2020
2021                 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2022                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2023                 assert_eq!(route.paths[0][0].fee_msat, 0);
2024                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2025                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2026                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2027
2028                 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2029                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2030                 assert_eq!(route.paths[0][1].fee_msat, 100);
2031                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2032                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2033                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2034
2035                 last_hops[0].fees.base_msat = 1000;
2036
2037                 // Revert to via 6 as the fee on 8 goes up
2038                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2039                 assert_eq!(route.paths[0].len(), 4);
2040
2041                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2042                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2043                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2044                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2045                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2046                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2047
2048                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2049                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2050                 assert_eq!(route.paths[0][1].fee_msat, 100);
2051                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2052                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2053                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2054
2055                 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2056                 assert_eq!(route.paths[0][2].short_channel_id, 7);
2057                 assert_eq!(route.paths[0][2].fee_msat, 0);
2058                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2059                 // If we have a peer in the node map, we'll use their features here since we don't have
2060                 // a way of figuring out their features from the invoice:
2061                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2062                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2063
2064                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2065                 assert_eq!(route.paths[0][3].short_channel_id, 10);
2066                 assert_eq!(route.paths[0][3].fee_msat, 100);
2067                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2068                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2069                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2070
2071                 // ...but still use 8 for larger payments as 6 has a variable feerate
2072                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger)).unwrap();
2073                 assert_eq!(route.paths[0].len(), 5);
2074
2075                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2076                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2077                 assert_eq!(route.paths[0][0].fee_msat, 3000);
2078                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2079                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2080                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2081
2082                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2083                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2084                 assert_eq!(route.paths[0][1].fee_msat, 0);
2085                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2086                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2087                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2088
2089                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2090                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2091                 assert_eq!(route.paths[0][2].fee_msat, 0);
2092                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2093                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2094                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2095
2096                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2097                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2098                 assert_eq!(route.paths[0][3].fee_msat, 1000);
2099                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2100                 // If we have a peer in the node map, we'll use their features here since we don't have
2101                 // a way of figuring out their features from the invoice:
2102                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2103                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2104
2105                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2106                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2107                 assert_eq!(route.paths[0][4].fee_msat, 2000);
2108                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2109                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2110                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2111         }
2112
2113         #[test]
2114         fn unannounced_path_test() {
2115                 // We should be able to send a payment to a destination without any help of a routing graph
2116                 // if we have a channel with a common counterparty that appears in the first and last hop
2117                 // hints.
2118                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2119                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2120                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2121
2122                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2123                 let last_hops = vec![RouteHint {
2124                         src_node_id: middle_node_id,
2125                         short_channel_id: 8,
2126                         fees: RoutingFees {
2127                                 base_msat: 1000,
2128                                 proportional_millionths: 0,
2129                         },
2130                         cltv_expiry_delta: (8 << 8) | 1,
2131                         htlc_minimum_msat: None,
2132                         htlc_maximum_msat: None,
2133                 }];
2134                 let our_chans = vec![channelmanager::ChannelDetails {
2135                         channel_id: [0; 32],
2136                         short_channel_id: Some(42),
2137                         remote_network_id: middle_node_id,
2138                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2139                         channel_value_satoshis: 100000,
2140                         user_id: 0,
2141                         outbound_capacity_msat: 100000,
2142                         inbound_capacity_msat: 100000,
2143                         is_live: true,
2144                 }];
2145                 let route = get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
2146
2147                 assert_eq!(route.paths[0].len(), 2);
2148
2149                 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2150                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2151                 assert_eq!(route.paths[0][0].fee_msat, 1000);
2152                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2153                 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2154                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2155
2156                 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2157                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2158                 assert_eq!(route.paths[0][1].fee_msat, 100);
2159                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2160                 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2161                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2162         }
2163
2164         #[test]
2165         fn available_amount_while_routing_test() {
2166                 // Tests whether we choose the correct available channel amount while routing.
2167
2168                 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2169                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2170
2171                 // We will use a simple single-path route from
2172                 // our node to node2 via node0: channels {1, 3}.
2173
2174                 // First disable all other paths.
2175                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2176                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2177                         short_channel_id: 2,
2178                         timestamp: 2,
2179                         flags: 2,
2180                         cltv_expiry_delta: 0,
2181                         htlc_minimum_msat: 0,
2182                         htlc_maximum_msat: OptionalField::Present(100_000),
2183                         fee_base_msat: 0,
2184                         fee_proportional_millionths: 0,
2185                         excess_data: Vec::new()
2186                 });
2187                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2188                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2189                         short_channel_id: 12,
2190                         timestamp: 2,
2191                         flags: 2,
2192                         cltv_expiry_delta: 0,
2193                         htlc_minimum_msat: 0,
2194                         htlc_maximum_msat: OptionalField::Present(100_000),
2195                         fee_base_msat: 0,
2196                         fee_proportional_millionths: 0,
2197                         excess_data: Vec::new()
2198                 });
2199
2200                 // Make the first channel (#1) very permissive,
2201                 // and we will be testing all limits on the second channel.
2202                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2203                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2204                         short_channel_id: 1,
2205                         timestamp: 2,
2206                         flags: 0,
2207                         cltv_expiry_delta: 0,
2208                         htlc_minimum_msat: 0,
2209                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2210                         fee_base_msat: 0,
2211                         fee_proportional_millionths: 0,
2212                         excess_data: Vec::new()
2213                 });
2214
2215                 // First, let's see if routing works if we have absolutely no idea about the available amount.
2216                 // In this case, it should be set to 250_000 sats.
2217                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2218                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2219                         short_channel_id: 3,
2220                         timestamp: 2,
2221                         flags: 0,
2222                         cltv_expiry_delta: 0,
2223                         htlc_minimum_msat: 0,
2224                         htlc_maximum_msat: OptionalField::Absent,
2225                         fee_base_msat: 0,
2226                         fee_proportional_millionths: 0,
2227                         excess_data: Vec::new()
2228                 });
2229
2230                 {
2231                         // Attempt to route more than available results in a failure.
2232                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2233                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2234                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2235                         } else { panic!(); }
2236                 }
2237
2238                 {
2239                         // Now, attempt to route an exact amount we have should be fine.
2240                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2241                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2242                         assert_eq!(route.paths.len(), 1);
2243                         let path = route.paths.last().unwrap();
2244                         assert_eq!(path.len(), 2);
2245                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2246                         assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2247                 }
2248
2249                 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2250                 // Disable channel #1 and use another first hop.
2251                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2252                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2253                         short_channel_id: 1,
2254                         timestamp: 3,
2255                         flags: 2,
2256                         cltv_expiry_delta: 0,
2257                         htlc_minimum_msat: 0,
2258                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2259                         fee_base_msat: 0,
2260                         fee_proportional_millionths: 0,
2261                         excess_data: Vec::new()
2262                 });
2263
2264                 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2265                 let our_chans = vec![channelmanager::ChannelDetails {
2266                         channel_id: [0; 32],
2267                         short_channel_id: Some(42),
2268                         remote_network_id: nodes[0].clone(),
2269                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2270                         channel_value_satoshis: 0,
2271                         user_id: 0,
2272                         outbound_capacity_msat: 200_000_000,
2273                         inbound_capacity_msat: 0,
2274                         is_live: true,
2275                 }];
2276
2277                 {
2278                         // Attempt to route more than available results in a failure.
2279                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2280                                         Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2281                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2282                         } else { panic!(); }
2283                 }
2284
2285                 {
2286                         // Now, attempt to route an exact amount we have should be fine.
2287                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2288                                 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2289                         assert_eq!(route.paths.len(), 1);
2290                         let path = route.paths.last().unwrap();
2291                         assert_eq!(path.len(), 2);
2292                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2293                         assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2294                 }
2295
2296                 // Enable channel #1 back.
2297                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2298                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2299                         short_channel_id: 1,
2300                         timestamp: 4,
2301                         flags: 0,
2302                         cltv_expiry_delta: 0,
2303                         htlc_minimum_msat: 0,
2304                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2305                         fee_base_msat: 0,
2306                         fee_proportional_millionths: 0,
2307                         excess_data: Vec::new()
2308                 });
2309
2310
2311                 // Now let's see if routing works if we know only htlc_maximum_msat.
2312                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2313                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2314                         short_channel_id: 3,
2315                         timestamp: 3,
2316                         flags: 0,
2317                         cltv_expiry_delta: 0,
2318                         htlc_minimum_msat: 0,
2319                         htlc_maximum_msat: OptionalField::Present(15_000),
2320                         fee_base_msat: 0,
2321                         fee_proportional_millionths: 0,
2322                         excess_data: Vec::new()
2323                 });
2324
2325                 {
2326                         // Attempt to route more than available results in a failure.
2327                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2328                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2329                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2330                         } else { panic!(); }
2331                 }
2332
2333                 {
2334                         // Now, attempt to route an exact amount we have should be fine.
2335                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2336                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2337                         assert_eq!(route.paths.len(), 1);
2338                         let path = route.paths.last().unwrap();
2339                         assert_eq!(path.len(), 2);
2340                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2341                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2342                 }
2343
2344                 // Now let's see if routing works if we know only capacity from the UTXO.
2345
2346                 // We can't change UTXO capacity on the fly, so we'll disable
2347                 // the existing channel and add another one with the capacity we need.
2348                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2349                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2350                         short_channel_id: 3,
2351                         timestamp: 4,
2352                         flags: 2,
2353                         cltv_expiry_delta: 0,
2354                         htlc_minimum_msat: 0,
2355                         htlc_maximum_msat: OptionalField::Absent,
2356                         fee_base_msat: 0,
2357                         fee_proportional_millionths: 0,
2358                         excess_data: Vec::new()
2359                 });
2360
2361                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2362                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2363                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2364                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2365                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2366
2367                 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2368                 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2369
2370                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2371                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2372                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2373                         short_channel_id: 333,
2374                         timestamp: 1,
2375                         flags: 0,
2376                         cltv_expiry_delta: (3 << 8) | 1,
2377                         htlc_minimum_msat: 0,
2378                         htlc_maximum_msat: OptionalField::Absent,
2379                         fee_base_msat: 0,
2380                         fee_proportional_millionths: 0,
2381                         excess_data: Vec::new()
2382                 });
2383                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2384                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2385                         short_channel_id: 333,
2386                         timestamp: 1,
2387                         flags: 1,
2388                         cltv_expiry_delta: (3 << 8) | 2,
2389                         htlc_minimum_msat: 0,
2390                         htlc_maximum_msat: OptionalField::Absent,
2391                         fee_base_msat: 100,
2392                         fee_proportional_millionths: 0,
2393                         excess_data: Vec::new()
2394                 });
2395
2396                 {
2397                         // Attempt to route more than available results in a failure.
2398                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2399                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2400                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2401                         } else { panic!(); }
2402                 }
2403
2404                 {
2405                         // Now, attempt to route an exact amount we have should be fine.
2406                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2407                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2408                         assert_eq!(route.paths.len(), 1);
2409                         let path = route.paths.last().unwrap();
2410                         assert_eq!(path.len(), 2);
2411                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2412                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2413                 }
2414
2415                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2416                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2417                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2418                         short_channel_id: 333,
2419                         timestamp: 6,
2420                         flags: 0,
2421                         cltv_expiry_delta: 0,
2422                         htlc_minimum_msat: 0,
2423                         htlc_maximum_msat: OptionalField::Present(10_000),
2424                         fee_base_msat: 0,
2425                         fee_proportional_millionths: 0,
2426                         excess_data: Vec::new()
2427                 });
2428
2429                 {
2430                         // Attempt to route more than available results in a failure.
2431                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2432                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2433                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2434                         } else { panic!(); }
2435                 }
2436
2437                 {
2438                         // Now, attempt to route an exact amount we have should be fine.
2439                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2440                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2441                         assert_eq!(route.paths.len(), 1);
2442                         let path = route.paths.last().unwrap();
2443                         assert_eq!(path.len(), 2);
2444                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2445                         assert_eq!(path.last().unwrap().fee_msat, 10_000);
2446                 }
2447         }
2448
2449         #[test]
2450         fn available_liquidity_last_hop_test() {
2451                 // Check that available liquidity properly limits the path even when only
2452                 // one of the latter hops is limited.
2453                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2454                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2455
2456                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2457                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2458                 // Total capacity: 50 sats.
2459
2460                 // Disable other potential paths.
2461                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2462                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2463                         short_channel_id: 2,
2464                         timestamp: 2,
2465                         flags: 2,
2466                         cltv_expiry_delta: 0,
2467                         htlc_minimum_msat: 0,
2468                         htlc_maximum_msat: OptionalField::Present(100_000),
2469                         fee_base_msat: 0,
2470                         fee_proportional_millionths: 0,
2471                         excess_data: Vec::new()
2472                 });
2473                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2474                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2475                         short_channel_id: 7,
2476                         timestamp: 2,
2477                         flags: 2,
2478                         cltv_expiry_delta: 0,
2479                         htlc_minimum_msat: 0,
2480                         htlc_maximum_msat: OptionalField::Present(100_000),
2481                         fee_base_msat: 0,
2482                         fee_proportional_millionths: 0,
2483                         excess_data: Vec::new()
2484                 });
2485
2486                 // Limit capacities
2487
2488                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2489                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2490                         short_channel_id: 12,
2491                         timestamp: 2,
2492                         flags: 0,
2493                         cltv_expiry_delta: 0,
2494                         htlc_minimum_msat: 0,
2495                         htlc_maximum_msat: OptionalField::Present(100_000),
2496                         fee_base_msat: 0,
2497                         fee_proportional_millionths: 0,
2498                         excess_data: Vec::new()
2499                 });
2500                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2501                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2502                         short_channel_id: 13,
2503                         timestamp: 2,
2504                         flags: 0,
2505                         cltv_expiry_delta: 0,
2506                         htlc_minimum_msat: 0,
2507                         htlc_maximum_msat: OptionalField::Present(100_000),
2508                         fee_base_msat: 0,
2509                         fee_proportional_millionths: 0,
2510                         excess_data: Vec::new()
2511                 });
2512
2513                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2514                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2515                         short_channel_id: 6,
2516                         timestamp: 2,
2517                         flags: 0,
2518                         cltv_expiry_delta: 0,
2519                         htlc_minimum_msat: 0,
2520                         htlc_maximum_msat: OptionalField::Present(50_000),
2521                         fee_base_msat: 0,
2522                         fee_proportional_millionths: 0,
2523                         excess_data: Vec::new()
2524                 });
2525                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2526                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2527                         short_channel_id: 11,
2528                         timestamp: 2,
2529                         flags: 0,
2530                         cltv_expiry_delta: 0,
2531                         htlc_minimum_msat: 0,
2532                         htlc_maximum_msat: OptionalField::Present(100_000),
2533                         fee_base_msat: 0,
2534                         fee_proportional_millionths: 0,
2535                         excess_data: Vec::new()
2536                 });
2537                 {
2538                         // Attempt to route more than available results in a failure.
2539                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2540                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2541                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2542                         } else { panic!(); }
2543                 }
2544
2545                 {
2546                         // Now, attempt to route 49 sats (just a bit below the capacity).
2547                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2548                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2549                         assert_eq!(route.paths.len(), 1);
2550                         let mut total_amount_paid_msat = 0;
2551                         for path in &route.paths {
2552                                 assert_eq!(path.len(), 4);
2553                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2554                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2555                         }
2556                         assert_eq!(total_amount_paid_msat, 49_000);
2557                 }
2558
2559                 {
2560                         // Attempt to route an exact amount is also fine
2561                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2562                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2563                         assert_eq!(route.paths.len(), 1);
2564                         let mut total_amount_paid_msat = 0;
2565                         for path in &route.paths {
2566                                 assert_eq!(path.len(), 4);
2567                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2568                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2569                         }
2570                         assert_eq!(total_amount_paid_msat, 50_000);
2571                 }
2572         }
2573
2574         #[test]
2575         fn ignore_fee_first_hop_test() {
2576                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2577                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2578
2579                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2580                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2581                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2582                         short_channel_id: 1,
2583                         timestamp: 2,
2584                         flags: 0,
2585                         cltv_expiry_delta: 0,
2586                         htlc_minimum_msat: 0,
2587                         htlc_maximum_msat: OptionalField::Present(100_000),
2588                         fee_base_msat: 1_000_000,
2589                         fee_proportional_millionths: 0,
2590                         excess_data: Vec::new()
2591                 });
2592                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2593                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2594                         short_channel_id: 3,
2595                         timestamp: 2,
2596                         flags: 0,
2597                         cltv_expiry_delta: 0,
2598                         htlc_minimum_msat: 0,
2599                         htlc_maximum_msat: OptionalField::Present(50_000),
2600                         fee_base_msat: 0,
2601                         fee_proportional_millionths: 0,
2602                         excess_data: Vec::new()
2603                 });
2604
2605                 {
2606                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2607                         assert_eq!(route.paths.len(), 1);
2608                         let mut total_amount_paid_msat = 0;
2609                         for path in &route.paths {
2610                                 assert_eq!(path.len(), 2);
2611                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2612                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2613                         }
2614                         assert_eq!(total_amount_paid_msat, 50_000);
2615                 }
2616         }
2617
2618         #[test]
2619         fn simple_mpp_route_test() {
2620                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2621                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2622
2623                 // We need a route consisting of 3 paths:
2624                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2625                 // To achieve this, the amount being transferred should be around
2626                 // the total capacity of these 3 paths.
2627
2628                 // First, we set limits on these (previously unlimited) channels.
2629                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2630
2631                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2632                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2633                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2634                         short_channel_id: 1,
2635                         timestamp: 2,
2636                         flags: 0,
2637                         cltv_expiry_delta: 0,
2638                         htlc_minimum_msat: 0,
2639                         htlc_maximum_msat: OptionalField::Present(100_000),
2640                         fee_base_msat: 0,
2641                         fee_proportional_millionths: 0,
2642                         excess_data: Vec::new()
2643                 });
2644                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2645                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2646                         short_channel_id: 3,
2647                         timestamp: 2,
2648                         flags: 0,
2649                         cltv_expiry_delta: 0,
2650                         htlc_minimum_msat: 0,
2651                         htlc_maximum_msat: OptionalField::Present(50_000),
2652                         fee_base_msat: 0,
2653                         fee_proportional_millionths: 0,
2654                         excess_data: Vec::new()
2655                 });
2656
2657                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2658                 // (total limit 60).
2659                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2660                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2661                         short_channel_id: 12,
2662                         timestamp: 2,
2663                         flags: 0,
2664                         cltv_expiry_delta: 0,
2665                         htlc_minimum_msat: 0,
2666                         htlc_maximum_msat: OptionalField::Present(60_000),
2667                         fee_base_msat: 0,
2668                         fee_proportional_millionths: 0,
2669                         excess_data: Vec::new()
2670                 });
2671                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2672                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2673                         short_channel_id: 13,
2674                         timestamp: 2,
2675                         flags: 0,
2676                         cltv_expiry_delta: 0,
2677                         htlc_minimum_msat: 0,
2678                         htlc_maximum_msat: OptionalField::Present(60_000),
2679                         fee_base_msat: 0,
2680                         fee_proportional_millionths: 0,
2681                         excess_data: Vec::new()
2682                 });
2683
2684                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2685                 // (total capacity 180 sats).
2686                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2687                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2688                         short_channel_id: 2,
2689                         timestamp: 2,
2690                         flags: 0,
2691                         cltv_expiry_delta: 0,
2692                         htlc_minimum_msat: 0,
2693                         htlc_maximum_msat: OptionalField::Present(200_000),
2694                         fee_base_msat: 0,
2695                         fee_proportional_millionths: 0,
2696                         excess_data: Vec::new()
2697                 });
2698                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2699                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2700                         short_channel_id: 4,
2701                         timestamp: 2,
2702                         flags: 0,
2703                         cltv_expiry_delta: 0,
2704                         htlc_minimum_msat: 0,
2705                         htlc_maximum_msat: OptionalField::Present(180_000),
2706                         fee_base_msat: 0,
2707                         fee_proportional_millionths: 0,
2708                         excess_data: Vec::new()
2709                 });
2710
2711                 {
2712                         // Attempt to route more than available results in a failure.
2713                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2714                                         &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2715                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2716                         } else { panic!(); }
2717                 }
2718
2719                 {
2720                         // Now, attempt to route 250 sats (just a bit below the capacity).
2721                         // Our algorithm should provide us with these 3 paths.
2722                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2723                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2724                         assert_eq!(route.paths.len(), 3);
2725                         let mut total_amount_paid_msat = 0;
2726                         for path in &route.paths {
2727                                 assert_eq!(path.len(), 2);
2728                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2729                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2730                         }
2731                         assert_eq!(total_amount_paid_msat, 250_000);
2732                 }
2733
2734                 {
2735                         // Attempt to route an exact amount is also fine
2736                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2737                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2738                         assert_eq!(route.paths.len(), 3);
2739                         let mut total_amount_paid_msat = 0;
2740                         for path in &route.paths {
2741                                 assert_eq!(path.len(), 2);
2742                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2743                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2744                         }
2745                         assert_eq!(total_amount_paid_msat, 290_000);
2746                 }
2747         }
2748
2749         #[test]
2750         fn long_mpp_route_test() {
2751                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2752                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2753
2754                 // We need a route consisting of 3 paths:
2755                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2756                 // Note that these paths overlap (channels 5, 12, 13).
2757                 // We will route 300 sats.
2758                 // Each path will have 100 sats capacity, those channels which
2759                 // are used twice will have 200 sats capacity.
2760
2761                 // Disable other potential paths.
2762                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2763                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2764                         short_channel_id: 2,
2765                         timestamp: 2,
2766                         flags: 2,
2767                         cltv_expiry_delta: 0,
2768                         htlc_minimum_msat: 0,
2769                         htlc_maximum_msat: OptionalField::Present(100_000),
2770                         fee_base_msat: 0,
2771                         fee_proportional_millionths: 0,
2772                         excess_data: Vec::new()
2773                 });
2774                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2775                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2776                         short_channel_id: 7,
2777                         timestamp: 2,
2778                         flags: 2,
2779                         cltv_expiry_delta: 0,
2780                         htlc_minimum_msat: 0,
2781                         htlc_maximum_msat: OptionalField::Present(100_000),
2782                         fee_base_msat: 0,
2783                         fee_proportional_millionths: 0,
2784                         excess_data: Vec::new()
2785                 });
2786
2787                 // Path via {node0, node2} is channels {1, 3, 5}.
2788                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2789                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2790                         short_channel_id: 1,
2791                         timestamp: 2,
2792                         flags: 0,
2793                         cltv_expiry_delta: 0,
2794                         htlc_minimum_msat: 0,
2795                         htlc_maximum_msat: OptionalField::Present(100_000),
2796                         fee_base_msat: 0,
2797                         fee_proportional_millionths: 0,
2798                         excess_data: Vec::new()
2799                 });
2800                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2801                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2802                         short_channel_id: 3,
2803                         timestamp: 2,
2804                         flags: 0,
2805                         cltv_expiry_delta: 0,
2806                         htlc_minimum_msat: 0,
2807                         htlc_maximum_msat: OptionalField::Present(100_000),
2808                         fee_base_msat: 0,
2809                         fee_proportional_millionths: 0,
2810                         excess_data: Vec::new()
2811                 });
2812
2813                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2814                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2815                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2816                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2817                         short_channel_id: 5,
2818                         timestamp: 2,
2819                         flags: 0,
2820                         cltv_expiry_delta: 0,
2821                         htlc_minimum_msat: 0,
2822                         htlc_maximum_msat: OptionalField::Present(200_000),
2823                         fee_base_msat: 0,
2824                         fee_proportional_millionths: 0,
2825                         excess_data: Vec::new()
2826                 });
2827
2828                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2829                 // Add 100 sats to the capacities of {12, 13}, because these channels
2830                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2831                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2832                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2833                         short_channel_id: 12,
2834                         timestamp: 2,
2835                         flags: 0,
2836                         cltv_expiry_delta: 0,
2837                         htlc_minimum_msat: 0,
2838                         htlc_maximum_msat: OptionalField::Present(200_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[7], UnsignedChannelUpdate {
2844                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2845                         short_channel_id: 13,
2846                         timestamp: 2,
2847                         flags: 0,
2848                         cltv_expiry_delta: 0,
2849                         htlc_minimum_msat: 0,
2850                         htlc_maximum_msat: OptionalField::Present(200_000),
2851                         fee_base_msat: 0,
2852                         fee_proportional_millionths: 0,
2853                         excess_data: Vec::new()
2854                 });
2855
2856                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2857                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2858                         short_channel_id: 6,
2859                         timestamp: 2,
2860                         flags: 0,
2861                         cltv_expiry_delta: 0,
2862                         htlc_minimum_msat: 0,
2863                         htlc_maximum_msat: OptionalField::Present(100_000),
2864                         fee_base_msat: 0,
2865                         fee_proportional_millionths: 0,
2866                         excess_data: Vec::new()
2867                 });
2868                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2869                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2870                         short_channel_id: 11,
2871                         timestamp: 2,
2872                         flags: 0,
2873                         cltv_expiry_delta: 0,
2874                         htlc_minimum_msat: 0,
2875                         htlc_maximum_msat: OptionalField::Present(100_000),
2876                         fee_base_msat: 0,
2877                         fee_proportional_millionths: 0,
2878                         excess_data: Vec::new()
2879                 });
2880
2881                 // Path via {node7, node2} is channels {12, 13, 5}.
2882                 // We already limited them to 200 sats (they are used twice for 100 sats).
2883                 // Nothing to do here.
2884
2885                 {
2886                         // Attempt to route more than available results in a failure.
2887                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2888                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
2889                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2890                         } else { panic!(); }
2891                 }
2892
2893                 {
2894                         // Now, attempt to route 300 sats (exact amount we can route).
2895                         // Our algorithm should provide us with these 3 paths, 100 sats each.
2896                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2897                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
2898                         assert_eq!(route.paths.len(), 3);
2899
2900                         let mut total_amount_paid_msat = 0;
2901                         for path in &route.paths {
2902                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2903                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
2904                         }
2905                         assert_eq!(total_amount_paid_msat, 300_000);
2906                 }
2907
2908         }
2909
2910         #[test]
2911         fn mpp_cheaper_route_test() {
2912                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2913                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2914
2915                 // This test checks that if we have two cheaper paths and one more expensive path,
2916                 // so that liquidity-wise any 2 of 3 combination is sufficient,
2917                 // two cheaper paths will be taken.
2918                 // These paths have equal available liquidity.
2919
2920                 // We need a combination of 3 paths:
2921                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2922                 // Note that these paths overlap (channels 5, 12, 13).
2923                 // Each path will have 100 sats capacity, those channels which
2924                 // are used twice will have 200 sats capacity.
2925
2926                 // Disable other potential paths.
2927                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2928                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2929                         short_channel_id: 2,
2930                         timestamp: 2,
2931                         flags: 2,
2932                         cltv_expiry_delta: 0,
2933                         htlc_minimum_msat: 0,
2934                         htlc_maximum_msat: OptionalField::Present(100_000),
2935                         fee_base_msat: 0,
2936                         fee_proportional_millionths: 0,
2937                         excess_data: Vec::new()
2938                 });
2939                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2940                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2941                         short_channel_id: 7,
2942                         timestamp: 2,
2943                         flags: 2,
2944                         cltv_expiry_delta: 0,
2945                         htlc_minimum_msat: 0,
2946                         htlc_maximum_msat: OptionalField::Present(100_000),
2947                         fee_base_msat: 0,
2948                         fee_proportional_millionths: 0,
2949                         excess_data: Vec::new()
2950                 });
2951
2952                 // Path via {node0, node2} is channels {1, 3, 5}.
2953                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2954                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2955                         short_channel_id: 1,
2956                         timestamp: 2,
2957                         flags: 0,
2958                         cltv_expiry_delta: 0,
2959                         htlc_minimum_msat: 0,
2960                         htlc_maximum_msat: OptionalField::Present(100_000),
2961                         fee_base_msat: 0,
2962                         fee_proportional_millionths: 0,
2963                         excess_data: Vec::new()
2964                 });
2965                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2966                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2967                         short_channel_id: 3,
2968                         timestamp: 2,
2969                         flags: 0,
2970                         cltv_expiry_delta: 0,
2971                         htlc_minimum_msat: 0,
2972                         htlc_maximum_msat: OptionalField::Present(100_000),
2973                         fee_base_msat: 0,
2974                         fee_proportional_millionths: 0,
2975                         excess_data: Vec::new()
2976                 });
2977
2978                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2979                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2980                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2981                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2982                         short_channel_id: 5,
2983                         timestamp: 2,
2984                         flags: 0,
2985                         cltv_expiry_delta: 0,
2986                         htlc_minimum_msat: 0,
2987                         htlc_maximum_msat: OptionalField::Present(200_000),
2988                         fee_base_msat: 0,
2989                         fee_proportional_millionths: 0,
2990                         excess_data: Vec::new()
2991                 });
2992
2993                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2994                 // Add 100 sats to the capacities of {12, 13}, because these channels
2995                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2996                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2997                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2998                         short_channel_id: 12,
2999                         timestamp: 2,
3000                         flags: 0,
3001                         cltv_expiry_delta: 0,
3002                         htlc_minimum_msat: 0,
3003                         htlc_maximum_msat: OptionalField::Present(200_000),
3004                         fee_base_msat: 0,
3005                         fee_proportional_millionths: 0,
3006                         excess_data: Vec::new()
3007                 });
3008                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3009                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3010                         short_channel_id: 13,
3011                         timestamp: 2,
3012                         flags: 0,
3013                         cltv_expiry_delta: 0,
3014                         htlc_minimum_msat: 0,
3015                         htlc_maximum_msat: OptionalField::Present(200_000),
3016                         fee_base_msat: 0,
3017                         fee_proportional_millionths: 0,
3018                         excess_data: Vec::new()
3019                 });
3020
3021                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3022                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3023                         short_channel_id: 6,
3024                         timestamp: 2,
3025                         flags: 0,
3026                         cltv_expiry_delta: 0,
3027                         htlc_minimum_msat: 0,
3028                         htlc_maximum_msat: OptionalField::Present(100_000),
3029                         fee_base_msat: 1_000,
3030                         fee_proportional_millionths: 0,
3031                         excess_data: Vec::new()
3032                 });
3033                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3034                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3035                         short_channel_id: 11,
3036                         timestamp: 2,
3037                         flags: 0,
3038                         cltv_expiry_delta: 0,
3039                         htlc_minimum_msat: 0,
3040                         htlc_maximum_msat: OptionalField::Present(100_000),
3041                         fee_base_msat: 0,
3042                         fee_proportional_millionths: 0,
3043                         excess_data: Vec::new()
3044                 });
3045
3046                 // Path via {node7, node2} is channels {12, 13, 5}.
3047                 // We already limited them to 200 sats (they are used twice for 100 sats).
3048                 // Nothing to do here.
3049
3050                 {
3051                         // Now, attempt to route 180 sats.
3052                         // Our algorithm should provide us with these 2 paths.
3053                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3054                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3055                         assert_eq!(route.paths.len(), 2);
3056
3057                         let mut total_value_transferred_msat = 0;
3058                         let mut total_paid_msat = 0;
3059                         for path in &route.paths {
3060                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3061                                 total_value_transferred_msat += path.last().unwrap().fee_msat;
3062                                 for hop in path {
3063                                         total_paid_msat += hop.fee_msat;
3064                                 }
3065                         }
3066                         // If we paid fee, this would be higher.
3067                         assert_eq!(total_value_transferred_msat, 180_000);
3068                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3069                         assert_eq!(total_fees_paid, 0);
3070                 }
3071         }
3072
3073         #[test]
3074         fn fees_on_mpp_route_test() {
3075                 // This test makes sure that MPP algorithm properly takes into account
3076                 // fees charged on the channels, by making the fees impactful:
3077                 // if the fee is not properly accounted for, the behavior is different.
3078                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3079                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3080
3081                 // We need a route consisting of 2 paths:
3082                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3083                 // We will route 200 sats, Each path will have 100 sats capacity.
3084
3085                 // This test is not particularly stable: e.g.,
3086                 // there's a way to route via {node0, node2, node4}.
3087                 // It works while pathfinding is deterministic, but can be broken otherwise.
3088                 // It's fine to ignore this concern for now.
3089
3090                 // Disable other potential paths.
3091                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3092                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3093                         short_channel_id: 2,
3094                         timestamp: 2,
3095                         flags: 2,
3096                         cltv_expiry_delta: 0,
3097                         htlc_minimum_msat: 0,
3098                         htlc_maximum_msat: OptionalField::Present(100_000),
3099                         fee_base_msat: 0,
3100                         fee_proportional_millionths: 0,
3101                         excess_data: Vec::new()
3102                 });
3103
3104                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3105                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3106                         short_channel_id: 7,
3107                         timestamp: 2,
3108                         flags: 2,
3109                         cltv_expiry_delta: 0,
3110                         htlc_minimum_msat: 0,
3111                         htlc_maximum_msat: OptionalField::Present(100_000),
3112                         fee_base_msat: 0,
3113                         fee_proportional_millionths: 0,
3114                         excess_data: Vec::new()
3115                 });
3116
3117                 // Path via {node0, node2} is channels {1, 3, 5}.
3118                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3119                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3120                         short_channel_id: 1,
3121                         timestamp: 2,
3122                         flags: 0,
3123                         cltv_expiry_delta: 0,
3124                         htlc_minimum_msat: 0,
3125                         htlc_maximum_msat: OptionalField::Present(100_000),
3126                         fee_base_msat: 0,
3127                         fee_proportional_millionths: 0,
3128                         excess_data: Vec::new()
3129                 });
3130                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3131                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3132                         short_channel_id: 3,
3133                         timestamp: 2,
3134                         flags: 0,
3135                         cltv_expiry_delta: 0,
3136                         htlc_minimum_msat: 0,
3137                         htlc_maximum_msat: OptionalField::Present(100_000),
3138                         fee_base_msat: 0,
3139                         fee_proportional_millionths: 0,
3140                         excess_data: Vec::new()
3141                 });
3142
3143                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3144                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3145                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3146                         short_channel_id: 5,
3147                         timestamp: 2,
3148                         flags: 0,
3149                         cltv_expiry_delta: 0,
3150                         htlc_minimum_msat: 0,
3151                         htlc_maximum_msat: OptionalField::Present(100_000),
3152                         fee_base_msat: 0,
3153                         fee_proportional_millionths: 0,
3154                         excess_data: Vec::new()
3155                 });
3156
3157                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3158                 // All channels should be 100 sats capacity. But for the fee experiment,
3159                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3160                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3161                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3162                 // so no matter how large are other channels,
3163                 // the whole path will be limited by 100 sats with just these 2 conditions:
3164                 // - channel 12 capacity is 250 sats
3165                 // - fee for channel 6 is 150 sats
3166                 // Let's test this by enforcing these 2 conditions and removing other limits.
3167                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3168                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3169                         short_channel_id: 12,
3170                         timestamp: 2,
3171                         flags: 0,
3172                         cltv_expiry_delta: 0,
3173                         htlc_minimum_msat: 0,
3174                         htlc_maximum_msat: OptionalField::Present(250_000),
3175                         fee_base_msat: 0,
3176                         fee_proportional_millionths: 0,
3177                         excess_data: Vec::new()
3178                 });
3179                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3180                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3181                         short_channel_id: 13,
3182                         timestamp: 2,
3183                         flags: 0,
3184                         cltv_expiry_delta: 0,
3185                         htlc_minimum_msat: 0,
3186                         htlc_maximum_msat: OptionalField::Absent,
3187                         fee_base_msat: 0,
3188                         fee_proportional_millionths: 0,
3189                         excess_data: Vec::new()
3190                 });
3191
3192                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3193                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3194                         short_channel_id: 6,
3195                         timestamp: 2,
3196                         flags: 0,
3197                         cltv_expiry_delta: 0,
3198                         htlc_minimum_msat: 0,
3199                         htlc_maximum_msat: OptionalField::Absent,
3200                         fee_base_msat: 150_000,
3201                         fee_proportional_millionths: 0,
3202                         excess_data: Vec::new()
3203                 });
3204                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3205                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3206                         short_channel_id: 11,
3207                         timestamp: 2,
3208                         flags: 0,
3209                         cltv_expiry_delta: 0,
3210                         htlc_minimum_msat: 0,
3211                         htlc_maximum_msat: OptionalField::Absent,
3212                         fee_base_msat: 0,
3213                         fee_proportional_millionths: 0,
3214                         excess_data: Vec::new()
3215                 });
3216
3217                 {
3218                         // Attempt to route more than available results in a failure.
3219                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3220                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3221                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3222                         } else { panic!(); }
3223                 }
3224
3225                 {
3226                         // Now, attempt to route 200 sats (exact amount we can route).
3227                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3228                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3229                         assert_eq!(route.paths.len(), 2);
3230
3231                         let mut total_amount_paid_msat = 0;
3232                         for path in &route.paths {
3233                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3234                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3235                         }
3236                         assert_eq!(total_amount_paid_msat, 200_000);
3237                 }
3238
3239         }
3240
3241         #[test]
3242         fn drop_lowest_channel_mpp_route_test() {
3243                 // This test checks that low-capacity channel is dropped when after
3244                 // path finding we realize that we found more capacity than we need.
3245                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3246                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3247
3248                 // We need a route consisting of 3 paths:
3249                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3250
3251                 // The first and the second paths should be sufficient, but the third should be
3252                 // cheaper, so that we select it but drop later.
3253
3254                 // First, we set limits on these (previously unlimited) channels.
3255                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3256
3257                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3258                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3259                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3260                         short_channel_id: 1,
3261                         timestamp: 2,
3262                         flags: 0,
3263                         cltv_expiry_delta: 0,
3264                         htlc_minimum_msat: 0,
3265                         htlc_maximum_msat: OptionalField::Present(100_000),
3266                         fee_base_msat: 0,
3267                         fee_proportional_millionths: 0,
3268                         excess_data: Vec::new()
3269                 });
3270                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3271                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3272                         short_channel_id: 3,
3273                         timestamp: 2,
3274                         flags: 0,
3275                         cltv_expiry_delta: 0,
3276                         htlc_minimum_msat: 0,
3277                         htlc_maximum_msat: OptionalField::Present(50_000),
3278                         fee_base_msat: 100,
3279                         fee_proportional_millionths: 0,
3280                         excess_data: Vec::new()
3281                 });
3282
3283                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3284                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3285                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3286                         short_channel_id: 12,
3287                         timestamp: 2,
3288                         flags: 0,
3289                         cltv_expiry_delta: 0,
3290                         htlc_minimum_msat: 0,
3291                         htlc_maximum_msat: OptionalField::Present(60_000),
3292                         fee_base_msat: 100,
3293                         fee_proportional_millionths: 0,
3294                         excess_data: Vec::new()
3295                 });
3296                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3297                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3298                         short_channel_id: 13,
3299                         timestamp: 2,
3300                         flags: 0,
3301                         cltv_expiry_delta: 0,
3302                         htlc_minimum_msat: 0,
3303                         htlc_maximum_msat: OptionalField::Present(60_000),
3304                         fee_base_msat: 0,
3305                         fee_proportional_millionths: 0,
3306                         excess_data: Vec::new()
3307                 });
3308
3309                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3310                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3311                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3312                         short_channel_id: 2,
3313                         timestamp: 2,
3314                         flags: 0,
3315                         cltv_expiry_delta: 0,
3316                         htlc_minimum_msat: 0,
3317                         htlc_maximum_msat: OptionalField::Present(20_000),
3318                         fee_base_msat: 0,
3319                         fee_proportional_millionths: 0,
3320                         excess_data: Vec::new()
3321                 });
3322                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3323                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3324                         short_channel_id: 4,
3325                         timestamp: 2,
3326                         flags: 0,
3327                         cltv_expiry_delta: 0,
3328                         htlc_minimum_msat: 0,
3329                         htlc_maximum_msat: OptionalField::Present(20_000),
3330                         fee_base_msat: 0,
3331                         fee_proportional_millionths: 0,
3332                         excess_data: Vec::new()
3333                 });
3334
3335                 {
3336                         // Attempt to route more than available results in a failure.
3337                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3338                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3339                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3340                         } else { panic!(); }
3341                 }
3342
3343                 {
3344                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3345                         // Our algorithm should provide us with these 3 paths.
3346                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3347                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3348                         assert_eq!(route.paths.len(), 3);
3349                         let mut total_amount_paid_msat = 0;
3350                         for path in &route.paths {
3351                                 assert_eq!(path.len(), 2);
3352                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3353                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3354                         }
3355                         assert_eq!(total_amount_paid_msat, 125_000);
3356                 }
3357
3358                 {
3359                         // Attempt to route without the last small cheap channel
3360                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3361                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3362                         assert_eq!(route.paths.len(), 2);
3363                         let mut total_amount_paid_msat = 0;
3364                         for path in &route.paths {
3365                                 assert_eq!(path.len(), 2);
3366                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3367                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3368                         }
3369                         assert_eq!(total_amount_paid_msat, 90_000);
3370                 }
3371         }
3372 }
3373
3374 #[cfg(all(test, feature = "unstable"))]
3375 mod benches {
3376         use super::*;
3377         use util::logger::{Logger, Record};
3378
3379         use std::fs::File;
3380         use test::Bencher;
3381
3382         struct DummyLogger {}
3383         impl Logger for DummyLogger {
3384                 fn log(&self, _record: &Record) {}
3385         }
3386
3387         #[bench]
3388         fn generate_routes(bench: &mut Bencher) {
3389                 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");
3390                 let graph = NetworkGraph::read(&mut d).unwrap();
3391
3392                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3393                 let mut path_endpoints = Vec::new();
3394                 let mut seed: usize = 0xdeadbeef;
3395                 'load_endpoints: for _ in 0..100 {
3396                         loop {
3397                                 seed *= 0xdeadbeef;
3398                                 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3399                                 seed *= 0xdeadbeef;
3400                                 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3401                                 let amt = seed as u64 % 1_000_000;
3402                                 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3403                                         path_endpoints.push((src, dst, amt));
3404                                         continue 'load_endpoints;
3405                                 }
3406                         }
3407                 }
3408
3409                 // ...then benchmark finding paths between the nodes we learned.
3410                 let mut idx = 0;
3411                 bench.iter(|| {
3412                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3413                         assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3414                         idx += 1;
3415                 });
3416         }
3417 }