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