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