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