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