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