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