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