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