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