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