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