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