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