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