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