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