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