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