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