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