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