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