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