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