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