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