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