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