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