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