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