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