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