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