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