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