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