Track SCID aliases from our counterparty and use them in invoices
[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::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters, Score};
1541         use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1542         use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
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                         inbound_scid_alias: None,
1582                         channel_value_satoshis: 0,
1583                         user_channel_id: 0,
1584                         balance_msat: 0,
1585                         outbound_capacity_msat,
1586                         inbound_capacity_msat: 42,
1587                         unspendable_punishment_reserve: None,
1588                         confirmations_required: None,
1589                         force_close_spend_delay: None,
1590                         is_outbound: true, is_funding_locked: true,
1591                         is_usable: true, is_public: true,
1592                 }
1593         }
1594
1595         // Using the same keys for LN and BTC ids
1596         fn add_channel(
1597                 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1598                 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1599         ) {
1600                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1601                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1602
1603                 let unsigned_announcement = UnsignedChannelAnnouncement {
1604                         features,
1605                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1606                         short_channel_id,
1607                         node_id_1,
1608                         node_id_2,
1609                         bitcoin_key_1: node_id_1,
1610                         bitcoin_key_2: node_id_2,
1611                         excess_data: Vec::new(),
1612                 };
1613
1614                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1615                 let valid_announcement = ChannelAnnouncement {
1616                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1617                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1618                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1619                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1620                         contents: unsigned_announcement.clone(),
1621                 };
1622                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1623                         Ok(res) => assert!(res),
1624                         _ => panic!()
1625                 };
1626         }
1627
1628         fn update_channel(
1629                 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1630                 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1631         ) {
1632                 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1633                 let valid_channel_update = ChannelUpdate {
1634                         signature: secp_ctx.sign(&msghash, node_privkey),
1635                         contents: update.clone()
1636                 };
1637
1638                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1639                         Ok(res) => assert!(res),
1640                         Err(_) => panic!()
1641                 };
1642         }
1643
1644         fn add_or_update_node(
1645                 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1646                 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1647         ) {
1648                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1649                 let unsigned_announcement = UnsignedNodeAnnouncement {
1650                         features,
1651                         timestamp,
1652                         node_id,
1653                         rgb: [0; 3],
1654                         alias: [0; 32],
1655                         addresses: Vec::new(),
1656                         excess_address_data: Vec::new(),
1657                         excess_data: Vec::new(),
1658                 };
1659                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1660                 let valid_announcement = NodeAnnouncement {
1661                         signature: secp_ctx.sign(&msghash, node_privkey),
1662                         contents: unsigned_announcement.clone()
1663                 };
1664
1665                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1666                         Ok(_) => (),
1667                         Err(_) => panic!()
1668                 };
1669         }
1670
1671         fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1672                 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1673                         SecretKey::from_slice(&hex::decode(format!("{:02x}", i).repeat(32)).unwrap()[..]).unwrap()
1674                 }).collect();
1675
1676                 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1677
1678                 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1679                 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1680
1681                 (our_privkey, our_id, privkeys, pubkeys)
1682         }
1683
1684         fn id_to_feature_flags(id: u8) -> Vec<u8> {
1685                 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1686                 // test for it later.
1687                 let idx = (id - 1) * 2 + 1;
1688                 if idx > 8*3 {
1689                         vec![1 << (idx - 8*3), 0, 0, 0]
1690                 } else if idx > 8*2 {
1691                         vec![1 << (idx - 8*2), 0, 0]
1692                 } else if idx > 8*1 {
1693                         vec![1 << (idx - 8*1), 0]
1694                 } else {
1695                         vec![1 << idx]
1696                 }
1697         }
1698
1699         fn build_graph() -> (
1700                 Secp256k1<All>,
1701                 sync::Arc<NetworkGraph>,
1702                 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1703                 sync::Arc<test_utils::TestChainSource>,
1704                 sync::Arc<test_utils::TestLogger>,
1705         ) {
1706                 let secp_ctx = Secp256k1::new();
1707                 let logger = Arc::new(test_utils::TestLogger::new());
1708                 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1709                 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1710                 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1711                 // Build network from our_id to node6:
1712                 //
1713                 //        -1(1)2-  node0  -1(3)2-
1714                 //       /                       \
1715                 // our_id -1(12)2- node7 -1(13)2--- node2
1716                 //       \                       /
1717                 //        -1(2)2-  node1  -1(4)2-
1718                 //
1719                 //
1720                 // chan1  1-to-2: disabled
1721                 // chan1  2-to-1: enabled, 0 fee
1722                 //
1723                 // chan2  1-to-2: enabled, ignored fee
1724                 // chan2  2-to-1: enabled, 0 fee
1725                 //
1726                 // chan3  1-to-2: enabled, 0 fee
1727                 // chan3  2-to-1: enabled, 100 msat fee
1728                 //
1729                 // chan4  1-to-2: enabled, 100% fee
1730                 // chan4  2-to-1: enabled, 0 fee
1731                 //
1732                 // chan12 1-to-2: enabled, ignored fee
1733                 // chan12 2-to-1: enabled, 0 fee
1734                 //
1735                 // chan13 1-to-2: enabled, 200% fee
1736                 // chan13 2-to-1: enabled, 0 fee
1737                 //
1738                 //
1739                 //       -1(5)2- node3 -1(8)2--
1740                 //       |         2          |
1741                 //       |       (11)         |
1742                 //      /          1           \
1743                 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1744                 //      \                      /
1745                 //       -1(7)2- node5 -1(10)2-
1746                 //
1747                 // Channels 5, 8, 9 and 10 are private channels.
1748                 //
1749                 // chan5  1-to-2: enabled, 100 msat fee
1750                 // chan5  2-to-1: enabled, 0 fee
1751                 //
1752                 // chan6  1-to-2: enabled, 0 fee
1753                 // chan6  2-to-1: enabled, 0 fee
1754                 //
1755                 // chan7  1-to-2: enabled, 100% fee
1756                 // chan7  2-to-1: enabled, 0 fee
1757                 //
1758                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
1759                 // chan8  2-to-1: enabled, 0 fee
1760                 //
1761                 // chan9  1-to-2: enabled, 1001 msat fee
1762                 // chan9  2-to-1: enabled, 0 fee
1763                 //
1764                 // chan10 1-to-2: enabled, 0 fee
1765                 // chan10 2-to-1: enabled, 0 fee
1766                 //
1767                 // chan11 1-to-2: enabled, 0 fee
1768                 // chan11 2-to-1: enabled, 0 fee
1769
1770                 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1771
1772                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1773                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1774                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1775                         short_channel_id: 1,
1776                         timestamp: 1,
1777                         flags: 1,
1778                         cltv_expiry_delta: 0,
1779                         htlc_minimum_msat: 0,
1780                         htlc_maximum_msat: OptionalField::Absent,
1781                         fee_base_msat: 0,
1782                         fee_proportional_millionths: 0,
1783                         excess_data: Vec::new()
1784                 });
1785
1786                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1787
1788                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1789                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1790                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1791                         short_channel_id: 2,
1792                         timestamp: 1,
1793                         flags: 0,
1794                         cltv_expiry_delta: (5 << 4) | 3,
1795                         htlc_minimum_msat: 0,
1796                         htlc_maximum_msat: OptionalField::Absent,
1797                         fee_base_msat: u32::max_value(),
1798                         fee_proportional_millionths: u32::max_value(),
1799                         excess_data: Vec::new()
1800                 });
1801                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1802                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1803                         short_channel_id: 2,
1804                         timestamp: 1,
1805                         flags: 1,
1806                         cltv_expiry_delta: 0,
1807                         htlc_minimum_msat: 0,
1808                         htlc_maximum_msat: OptionalField::Absent,
1809                         fee_base_msat: 0,
1810                         fee_proportional_millionths: 0,
1811                         excess_data: Vec::new()
1812                 });
1813
1814                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1815
1816                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1817                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1818                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1819                         short_channel_id: 12,
1820                         timestamp: 1,
1821                         flags: 0,
1822                         cltv_expiry_delta: (5 << 4) | 3,
1823                         htlc_minimum_msat: 0,
1824                         htlc_maximum_msat: OptionalField::Absent,
1825                         fee_base_msat: u32::max_value(),
1826                         fee_proportional_millionths: u32::max_value(),
1827                         excess_data: Vec::new()
1828                 });
1829                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1830                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1831                         short_channel_id: 12,
1832                         timestamp: 1,
1833                         flags: 1,
1834                         cltv_expiry_delta: 0,
1835                         htlc_minimum_msat: 0,
1836                         htlc_maximum_msat: OptionalField::Absent,
1837                         fee_base_msat: 0,
1838                         fee_proportional_millionths: 0,
1839                         excess_data: Vec::new()
1840                 });
1841
1842                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1843
1844                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1845                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1846                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1847                         short_channel_id: 3,
1848                         timestamp: 1,
1849                         flags: 0,
1850                         cltv_expiry_delta: (3 << 4) | 1,
1851                         htlc_minimum_msat: 0,
1852                         htlc_maximum_msat: OptionalField::Absent,
1853                         fee_base_msat: 0,
1854                         fee_proportional_millionths: 0,
1855                         excess_data: Vec::new()
1856                 });
1857                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1858                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1859                         short_channel_id: 3,
1860                         timestamp: 1,
1861                         flags: 1,
1862                         cltv_expiry_delta: (3 << 4) | 2,
1863                         htlc_minimum_msat: 0,
1864                         htlc_maximum_msat: OptionalField::Absent,
1865                         fee_base_msat: 100,
1866                         fee_proportional_millionths: 0,
1867                         excess_data: Vec::new()
1868                 });
1869
1870                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1871                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1872                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1873                         short_channel_id: 4,
1874                         timestamp: 1,
1875                         flags: 0,
1876                         cltv_expiry_delta: (4 << 4) | 1,
1877                         htlc_minimum_msat: 0,
1878                         htlc_maximum_msat: OptionalField::Absent,
1879                         fee_base_msat: 0,
1880                         fee_proportional_millionths: 1000000,
1881                         excess_data: Vec::new()
1882                 });
1883                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1884                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1885                         short_channel_id: 4,
1886                         timestamp: 1,
1887                         flags: 1,
1888                         cltv_expiry_delta: (4 << 4) | 2,
1889                         htlc_minimum_msat: 0,
1890                         htlc_maximum_msat: OptionalField::Absent,
1891                         fee_base_msat: 0,
1892                         fee_proportional_millionths: 0,
1893                         excess_data: Vec::new()
1894                 });
1895
1896                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1897                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1898                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1899                         short_channel_id: 13,
1900                         timestamp: 1,
1901                         flags: 0,
1902                         cltv_expiry_delta: (13 << 4) | 1,
1903                         htlc_minimum_msat: 0,
1904                         htlc_maximum_msat: OptionalField::Absent,
1905                         fee_base_msat: 0,
1906                         fee_proportional_millionths: 2000000,
1907                         excess_data: Vec::new()
1908                 });
1909                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1910                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1911                         short_channel_id: 13,
1912                         timestamp: 1,
1913                         flags: 1,
1914                         cltv_expiry_delta: (13 << 4) | 2,
1915                         htlc_minimum_msat: 0,
1916                         htlc_maximum_msat: OptionalField::Absent,
1917                         fee_base_msat: 0,
1918                         fee_proportional_millionths: 0,
1919                         excess_data: Vec::new()
1920                 });
1921
1922                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1923
1924                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1925                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1926                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1927                         short_channel_id: 6,
1928                         timestamp: 1,
1929                         flags: 0,
1930                         cltv_expiry_delta: (6 << 4) | 1,
1931                         htlc_minimum_msat: 0,
1932                         htlc_maximum_msat: OptionalField::Absent,
1933                         fee_base_msat: 0,
1934                         fee_proportional_millionths: 0,
1935                         excess_data: Vec::new()
1936                 });
1937                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1938                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1939                         short_channel_id: 6,
1940                         timestamp: 1,
1941                         flags: 1,
1942                         cltv_expiry_delta: (6 << 4) | 2,
1943                         htlc_minimum_msat: 0,
1944                         htlc_maximum_msat: OptionalField::Absent,
1945                         fee_base_msat: 0,
1946                         fee_proportional_millionths: 0,
1947                         excess_data: Vec::new(),
1948                 });
1949
1950                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1951                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1952                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1953                         short_channel_id: 11,
1954                         timestamp: 1,
1955                         flags: 0,
1956                         cltv_expiry_delta: (11 << 4) | 1,
1957                         htlc_minimum_msat: 0,
1958                         htlc_maximum_msat: OptionalField::Absent,
1959                         fee_base_msat: 0,
1960                         fee_proportional_millionths: 0,
1961                         excess_data: Vec::new()
1962                 });
1963                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1964                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1965                         short_channel_id: 11,
1966                         timestamp: 1,
1967                         flags: 1,
1968                         cltv_expiry_delta: (11 << 4) | 2,
1969                         htlc_minimum_msat: 0,
1970                         htlc_maximum_msat: OptionalField::Absent,
1971                         fee_base_msat: 0,
1972                         fee_proportional_millionths: 0,
1973                         excess_data: Vec::new()
1974                 });
1975
1976                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1977
1978                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1979
1980                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1981                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1982                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1983                         short_channel_id: 7,
1984                         timestamp: 1,
1985                         flags: 0,
1986                         cltv_expiry_delta: (7 << 4) | 1,
1987                         htlc_minimum_msat: 0,
1988                         htlc_maximum_msat: OptionalField::Absent,
1989                         fee_base_msat: 0,
1990                         fee_proportional_millionths: 1000000,
1991                         excess_data: Vec::new()
1992                 });
1993                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1994                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1995                         short_channel_id: 7,
1996                         timestamp: 1,
1997                         flags: 1,
1998                         cltv_expiry_delta: (7 << 4) | 2,
1999                         htlc_minimum_msat: 0,
2000                         htlc_maximum_msat: OptionalField::Absent,
2001                         fee_base_msat: 0,
2002                         fee_proportional_millionths: 0,
2003                         excess_data: Vec::new()
2004                 });
2005
2006                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
2007
2008                 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
2009         }
2010
2011         #[test]
2012         fn simple_route_test() {
2013                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2014                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2015                 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2016                 let scorer = test_utils::TestScorer::with_penalty(0);
2017
2018                 // Simple route to 2 via 1
2019
2020                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
2021                         assert_eq!(err, "Cannot send a payment of 0 msat");
2022                 } else { panic!(); }
2023
2024                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2025                 assert_eq!(route.paths[0].len(), 2);
2026
2027                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2028                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2029                 assert_eq!(route.paths[0][0].fee_msat, 100);
2030                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2031                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2032                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2033
2034                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2035                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2036                 assert_eq!(route.paths[0][1].fee_msat, 100);
2037                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2038                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2039                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2040         }
2041
2042         #[test]
2043         fn invalid_first_hop_test() {
2044                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2045                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2046                 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2047                 let scorer = test_utils::TestScorer::with_penalty(0);
2048
2049                 // Simple route to 2 via 1
2050
2051                 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2052
2053                 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) {
2054                         assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2055                 } else { panic!(); }
2056
2057                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2058                 assert_eq!(route.paths[0].len(), 2);
2059         }
2060
2061         #[test]
2062         fn htlc_minimum_test() {
2063                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2064                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2065                 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2066                 let scorer = test_utils::TestScorer::with_penalty(0);
2067
2068                 // Simple route to 2 via 1
2069
2070                 // Disable other paths
2071                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2072                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2073                         short_channel_id: 12,
2074                         timestamp: 2,
2075                         flags: 2, // to disable
2076                         cltv_expiry_delta: 0,
2077                         htlc_minimum_msat: 0,
2078                         htlc_maximum_msat: OptionalField::Absent,
2079                         fee_base_msat: 0,
2080                         fee_proportional_millionths: 0,
2081                         excess_data: Vec::new()
2082                 });
2083                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2084                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2085                         short_channel_id: 3,
2086                         timestamp: 2,
2087                         flags: 2, // to disable
2088                         cltv_expiry_delta: 0,
2089                         htlc_minimum_msat: 0,
2090                         htlc_maximum_msat: OptionalField::Absent,
2091                         fee_base_msat: 0,
2092                         fee_proportional_millionths: 0,
2093                         excess_data: Vec::new()
2094                 });
2095                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2096                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2097                         short_channel_id: 13,
2098                         timestamp: 2,
2099                         flags: 2, // to disable
2100                         cltv_expiry_delta: 0,
2101                         htlc_minimum_msat: 0,
2102                         htlc_maximum_msat: OptionalField::Absent,
2103                         fee_base_msat: 0,
2104                         fee_proportional_millionths: 0,
2105                         excess_data: Vec::new()
2106                 });
2107                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2108                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2109                         short_channel_id: 6,
2110                         timestamp: 2,
2111                         flags: 2, // to disable
2112                         cltv_expiry_delta: 0,
2113                         htlc_minimum_msat: 0,
2114                         htlc_maximum_msat: OptionalField::Absent,
2115                         fee_base_msat: 0,
2116                         fee_proportional_millionths: 0,
2117                         excess_data: Vec::new()
2118                 });
2119                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2120                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2121                         short_channel_id: 7,
2122                         timestamp: 2,
2123                         flags: 2, // to disable
2124                         cltv_expiry_delta: 0,
2125                         htlc_minimum_msat: 0,
2126                         htlc_maximum_msat: OptionalField::Absent,
2127                         fee_base_msat: 0,
2128                         fee_proportional_millionths: 0,
2129                         excess_data: Vec::new()
2130                 });
2131
2132                 // Check against amount_to_transfer_over_msat.
2133                 // Set minimal HTLC of 200_000_000 msat.
2134                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2135                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2136                         short_channel_id: 2,
2137                         timestamp: 3,
2138                         flags: 0,
2139                         cltv_expiry_delta: 0,
2140                         htlc_minimum_msat: 200_000_000,
2141                         htlc_maximum_msat: OptionalField::Absent,
2142                         fee_base_msat: 0,
2143                         fee_proportional_millionths: 0,
2144                         excess_data: Vec::new()
2145                 });
2146
2147                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2148                 // be used.
2149                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2150                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2151                         short_channel_id: 4,
2152                         timestamp: 3,
2153                         flags: 0,
2154                         cltv_expiry_delta: 0,
2155                         htlc_minimum_msat: 0,
2156                         htlc_maximum_msat: OptionalField::Present(199_999_999),
2157                         fee_base_msat: 0,
2158                         fee_proportional_millionths: 0,
2159                         excess_data: Vec::new()
2160                 });
2161
2162                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2163                 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) {
2164                         assert_eq!(err, "Failed to find a path to the given destination");
2165                 } else { panic!(); }
2166
2167                 // Lift the restriction on the first hop.
2168                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2169                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2170                         short_channel_id: 2,
2171                         timestamp: 4,
2172                         flags: 0,
2173                         cltv_expiry_delta: 0,
2174                         htlc_minimum_msat: 0,
2175                         htlc_maximum_msat: OptionalField::Absent,
2176                         fee_base_msat: 0,
2177                         fee_proportional_millionths: 0,
2178                         excess_data: Vec::new()
2179                 });
2180
2181                 // A payment above the minimum should pass
2182                 let route = get_route(&our_id, &payment_params, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2183                 assert_eq!(route.paths[0].len(), 2);
2184         }
2185
2186         #[test]
2187         fn htlc_minimum_overpay_test() {
2188                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2189                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2190                 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2191                 let scorer = test_utils::TestScorer::with_penalty(0);
2192
2193                 // A route to node#2 via two paths.
2194                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2195                 // Thus, they can't send 60 without overpaying.
2196                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2197                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2198                         short_channel_id: 2,
2199                         timestamp: 2,
2200                         flags: 0,
2201                         cltv_expiry_delta: 0,
2202                         htlc_minimum_msat: 35_000,
2203                         htlc_maximum_msat: OptionalField::Present(40_000),
2204                         fee_base_msat: 0,
2205                         fee_proportional_millionths: 0,
2206                         excess_data: Vec::new()
2207                 });
2208                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2209                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210                         short_channel_id: 12,
2211                         timestamp: 3,
2212                         flags: 0,
2213                         cltv_expiry_delta: 0,
2214                         htlc_minimum_msat: 35_000,
2215                         htlc_maximum_msat: OptionalField::Present(40_000),
2216                         fee_base_msat: 0,
2217                         fee_proportional_millionths: 0,
2218                         excess_data: Vec::new()
2219                 });
2220
2221                 // Make 0 fee.
2222                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2223                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2224                         short_channel_id: 13,
2225                         timestamp: 2,
2226                         flags: 0,
2227                         cltv_expiry_delta: 0,
2228                         htlc_minimum_msat: 0,
2229                         htlc_maximum_msat: OptionalField::Absent,
2230                         fee_base_msat: 0,
2231                         fee_proportional_millionths: 0,
2232                         excess_data: Vec::new()
2233                 });
2234                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2235                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2236                         short_channel_id: 4,
2237                         timestamp: 2,
2238                         flags: 0,
2239                         cltv_expiry_delta: 0,
2240                         htlc_minimum_msat: 0,
2241                         htlc_maximum_msat: OptionalField::Absent,
2242                         fee_base_msat: 0,
2243                         fee_proportional_millionths: 0,
2244                         excess_data: Vec::new()
2245                 });
2246
2247                 // Disable other paths
2248                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2249                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2250                         short_channel_id: 1,
2251                         timestamp: 3,
2252                         flags: 2, // to disable
2253                         cltv_expiry_delta: 0,
2254                         htlc_minimum_msat: 0,
2255                         htlc_maximum_msat: OptionalField::Absent,
2256                         fee_base_msat: 0,
2257                         fee_proportional_millionths: 0,
2258                         excess_data: Vec::new()
2259                 });
2260
2261                 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2262                 // Overpay fees to hit htlc_minimum_msat.
2263                 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2264                 // TODO: this could be better balanced to overpay 10k and not 15k.
2265                 assert_eq!(overpaid_fees, 15_000);
2266
2267                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2268                 // while taking even more fee to match htlc_minimum_msat.
2269                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2270                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2271                         short_channel_id: 12,
2272                         timestamp: 4,
2273                         flags: 0,
2274                         cltv_expiry_delta: 0,
2275                         htlc_minimum_msat: 65_000,
2276                         htlc_maximum_msat: OptionalField::Present(80_000),
2277                         fee_base_msat: 0,
2278                         fee_proportional_millionths: 0,
2279                         excess_data: Vec::new()
2280                 });
2281                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2282                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2283                         short_channel_id: 2,
2284                         timestamp: 3,
2285                         flags: 0,
2286                         cltv_expiry_delta: 0,
2287                         htlc_minimum_msat: 0,
2288                         htlc_maximum_msat: OptionalField::Absent,
2289                         fee_base_msat: 0,
2290                         fee_proportional_millionths: 0,
2291                         excess_data: Vec::new()
2292                 });
2293                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2294                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2295                         short_channel_id: 4,
2296                         timestamp: 4,
2297                         flags: 0,
2298                         cltv_expiry_delta: 0,
2299                         htlc_minimum_msat: 0,
2300                         htlc_maximum_msat: OptionalField::Absent,
2301                         fee_base_msat: 0,
2302                         fee_proportional_millionths: 100_000,
2303                         excess_data: Vec::new()
2304                 });
2305
2306                 let route = get_route(&our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2307                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2308                 assert_eq!(route.paths.len(), 1);
2309                 assert_eq!(route.paths[0][0].short_channel_id, 12);
2310                 let fees = route.paths[0][0].fee_msat;
2311                 assert_eq!(fees, 5_000);
2312
2313                 let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2314                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2315                 // the other channel.
2316                 assert_eq!(route.paths.len(), 1);
2317                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2318                 let fees = route.paths[0][0].fee_msat;
2319                 assert_eq!(fees, 5_000);
2320         }
2321
2322         #[test]
2323         fn disable_channels_test() {
2324                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2325                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2326                 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2327                 let scorer = test_utils::TestScorer::with_penalty(0);
2328
2329                 // // Disable channels 4 and 12 by flags=2
2330                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2331                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2332                         short_channel_id: 4,
2333                         timestamp: 2,
2334                         flags: 2, // to disable
2335                         cltv_expiry_delta: 0,
2336                         htlc_minimum_msat: 0,
2337                         htlc_maximum_msat: OptionalField::Absent,
2338                         fee_base_msat: 0,
2339                         fee_proportional_millionths: 0,
2340                         excess_data: Vec::new()
2341                 });
2342                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2343                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2344                         short_channel_id: 12,
2345                         timestamp: 2,
2346                         flags: 2, // to disable
2347                         cltv_expiry_delta: 0,
2348                         htlc_minimum_msat: 0,
2349                         htlc_maximum_msat: OptionalField::Absent,
2350                         fee_base_msat: 0,
2351                         fee_proportional_millionths: 0,
2352                         excess_data: Vec::new()
2353                 });
2354
2355                 // If all the channels require some features we don't understand, route should fail
2356                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2357                         assert_eq!(err, "Failed to find a path to the given destination");
2358                 } else { panic!(); }
2359
2360                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2361                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2362                 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2363                 assert_eq!(route.paths[0].len(), 2);
2364
2365                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2366                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2367                 assert_eq!(route.paths[0][0].fee_msat, 200);
2368                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2369                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2370                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2371
2372                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2373                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2374                 assert_eq!(route.paths[0][1].fee_msat, 100);
2375                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2376                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2377                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2378         }
2379
2380         #[test]
2381         fn disable_node_test() {
2382                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2383                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2384                 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2385                 let scorer = test_utils::TestScorer::with_penalty(0);
2386
2387                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2388                 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2389                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2390                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2391                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2392
2393                 // If all nodes require some features we don't understand, route should fail
2394                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2395                         assert_eq!(err, "Failed to find a path to the given destination");
2396                 } else { panic!(); }
2397
2398                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2399                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2400                 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2401                 assert_eq!(route.paths[0].len(), 2);
2402
2403                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2404                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2405                 assert_eq!(route.paths[0][0].fee_msat, 200);
2406                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2407                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2408                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2409
2410                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2411                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2412                 assert_eq!(route.paths[0][1].fee_msat, 100);
2413                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2414                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2415                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2416
2417                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2418                 // naively) assume that the user checked the feature bits on the invoice, which override
2419                 // the node_announcement.
2420         }
2421
2422         #[test]
2423         fn our_chans_test() {
2424                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2425                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2426                 let scorer = test_utils::TestScorer::with_penalty(0);
2427
2428                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2429                 let payment_params = PaymentParameters::from_node_id(nodes[0]);
2430                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2431                 assert_eq!(route.paths[0].len(), 3);
2432
2433                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2434                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2435                 assert_eq!(route.paths[0][0].fee_msat, 200);
2436                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2437                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2438                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2439
2440                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2441                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2442                 assert_eq!(route.paths[0][1].fee_msat, 100);
2443                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 4) | 2);
2444                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2445                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2446
2447                 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2448                 assert_eq!(route.paths[0][2].short_channel_id, 3);
2449                 assert_eq!(route.paths[0][2].fee_msat, 100);
2450                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2451                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2452                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2453
2454                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2455                 let payment_params = PaymentParameters::from_node_id(nodes[2]);
2456                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2457                 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2458                 assert_eq!(route.paths[0].len(), 2);
2459
2460                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2461                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2462                 assert_eq!(route.paths[0][0].fee_msat, 200);
2463                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
2464                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2465                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2466
2467                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2468                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2469                 assert_eq!(route.paths[0][1].fee_msat, 100);
2470                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2471                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2472                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2473         }
2474
2475         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2476                 let zero_fees = RoutingFees {
2477                         base_msat: 0,
2478                         proportional_millionths: 0,
2479                 };
2480                 vec![RouteHint(vec![RouteHintHop {
2481                         src_node_id: nodes[3],
2482                         short_channel_id: 8,
2483                         fees: zero_fees,
2484                         cltv_expiry_delta: (8 << 4) | 1,
2485                         htlc_minimum_msat: None,
2486                         htlc_maximum_msat: None,
2487                 }
2488                 ]), RouteHint(vec![RouteHintHop {
2489                         src_node_id: nodes[4],
2490                         short_channel_id: 9,
2491                         fees: RoutingFees {
2492                                 base_msat: 1001,
2493                                 proportional_millionths: 0,
2494                         },
2495                         cltv_expiry_delta: (9 << 4) | 1,
2496                         htlc_minimum_msat: None,
2497                         htlc_maximum_msat: None,
2498                 }]), RouteHint(vec![RouteHintHop {
2499                         src_node_id: nodes[5],
2500                         short_channel_id: 10,
2501                         fees: zero_fees,
2502                         cltv_expiry_delta: (10 << 4) | 1,
2503                         htlc_minimum_msat: None,
2504                         htlc_maximum_msat: None,
2505                 }])]
2506         }
2507
2508         fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2509                 let zero_fees = RoutingFees {
2510                         base_msat: 0,
2511                         proportional_millionths: 0,
2512                 };
2513                 vec![RouteHint(vec![RouteHintHop {
2514                         src_node_id: nodes[2],
2515                         short_channel_id: 5,
2516                         fees: RoutingFees {
2517                                 base_msat: 100,
2518                                 proportional_millionths: 0,
2519                         },
2520                         cltv_expiry_delta: (5 << 4) | 1,
2521                         htlc_minimum_msat: None,
2522                         htlc_maximum_msat: None,
2523                 }, RouteHintHop {
2524                         src_node_id: nodes[3],
2525                         short_channel_id: 8,
2526                         fees: zero_fees,
2527                         cltv_expiry_delta: (8 << 4) | 1,
2528                         htlc_minimum_msat: None,
2529                         htlc_maximum_msat: None,
2530                 }
2531                 ]), RouteHint(vec![RouteHintHop {
2532                         src_node_id: nodes[4],
2533                         short_channel_id: 9,
2534                         fees: RoutingFees {
2535                                 base_msat: 1001,
2536                                 proportional_millionths: 0,
2537                         },
2538                         cltv_expiry_delta: (9 << 4) | 1,
2539                         htlc_minimum_msat: None,
2540                         htlc_maximum_msat: None,
2541                 }]), RouteHint(vec![RouteHintHop {
2542                         src_node_id: nodes[5],
2543                         short_channel_id: 10,
2544                         fees: zero_fees,
2545                         cltv_expiry_delta: (10 << 4) | 1,
2546                         htlc_minimum_msat: None,
2547                         htlc_maximum_msat: None,
2548                 }])]
2549         }
2550
2551         #[test]
2552         fn partial_route_hint_test() {
2553                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2554                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2555                 let scorer = test_utils::TestScorer::with_penalty(0);
2556
2557                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2558                 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2559                 // RouteHint may be partially used by the algo to build the best path.
2560
2561                 // First check that last hop can't have its source as the payee.
2562                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2563                         src_node_id: nodes[6],
2564                         short_channel_id: 8,
2565                         fees: RoutingFees {
2566                                 base_msat: 1000,
2567                                 proportional_millionths: 0,
2568                         },
2569                         cltv_expiry_delta: (8 << 4) | 1,
2570                         htlc_minimum_msat: None,
2571                         htlc_maximum_msat: None,
2572                 }]);
2573
2574                 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2575                 invalid_last_hops.push(invalid_last_hop);
2576                 {
2577                         let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2578                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2579                                 assert_eq!(err, "Route hint cannot have the payee as the source.");
2580                         } else { panic!(); }
2581                 }
2582
2583                 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2584                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2585                 assert_eq!(route.paths[0].len(), 5);
2586
2587                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2588                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2589                 assert_eq!(route.paths[0][0].fee_msat, 100);
2590                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2591                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2592                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2593
2594                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2595                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2596                 assert_eq!(route.paths[0][1].fee_msat, 0);
2597                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2598                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2599                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2600
2601                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2602                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2603                 assert_eq!(route.paths[0][2].fee_msat, 0);
2604                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2605                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2606                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2607
2608                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2609                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2610                 assert_eq!(route.paths[0][3].fee_msat, 0);
2611                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2612                 // If we have a peer in the node map, we'll use their features here since we don't have
2613                 // a way of figuring out their features from the invoice:
2614                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2615                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2616
2617                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2618                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2619                 assert_eq!(route.paths[0][4].fee_msat, 100);
2620                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2621                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2622                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2623         }
2624
2625         fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2626                 let zero_fees = RoutingFees {
2627                         base_msat: 0,
2628                         proportional_millionths: 0,
2629                 };
2630                 vec![RouteHint(vec![RouteHintHop {
2631                         src_node_id: nodes[3],
2632                         short_channel_id: 8,
2633                         fees: zero_fees,
2634                         cltv_expiry_delta: (8 << 4) | 1,
2635                         htlc_minimum_msat: None,
2636                         htlc_maximum_msat: None,
2637                 }]), RouteHint(vec![
2638
2639                 ]), RouteHint(vec![RouteHintHop {
2640                         src_node_id: nodes[5],
2641                         short_channel_id: 10,
2642                         fees: zero_fees,
2643                         cltv_expiry_delta: (10 << 4) | 1,
2644                         htlc_minimum_msat: None,
2645                         htlc_maximum_msat: None,
2646                 }])]
2647         }
2648
2649         #[test]
2650         fn ignores_empty_last_hops_test() {
2651                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2652                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2653                 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2654                 let scorer = test_utils::TestScorer::with_penalty(0);
2655
2656                 // Test handling of an empty RouteHint passed in Invoice.
2657
2658                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2659                 assert_eq!(route.paths[0].len(), 5);
2660
2661                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2662                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2663                 assert_eq!(route.paths[0][0].fee_msat, 100);
2664                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2665                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2666                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2667
2668                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2669                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2670                 assert_eq!(route.paths[0][1].fee_msat, 0);
2671                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2672                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2673                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2674
2675                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2676                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2677                 assert_eq!(route.paths[0][2].fee_msat, 0);
2678                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2679                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2680                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2681
2682                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2683                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2684                 assert_eq!(route.paths[0][3].fee_msat, 0);
2685                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2686                 // If we have a peer in the node map, we'll use their features here since we don't have
2687                 // a way of figuring out their features from the invoice:
2688                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2689                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2690
2691                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2692                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2693                 assert_eq!(route.paths[0][4].fee_msat, 100);
2694                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2695                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2696                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2697         }
2698
2699         /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
2700         /// and 0xff01.
2701         fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
2702                 let zero_fees = RoutingFees {
2703                         base_msat: 0,
2704                         proportional_millionths: 0,
2705                 };
2706                 vec![RouteHint(vec![RouteHintHop {
2707                         src_node_id: hint_hops[0],
2708                         short_channel_id: 0xff00,
2709                         fees: RoutingFees {
2710                                 base_msat: 100,
2711                                 proportional_millionths: 0,
2712                         },
2713                         cltv_expiry_delta: (5 << 4) | 1,
2714                         htlc_minimum_msat: None,
2715                         htlc_maximum_msat: None,
2716                 }, RouteHintHop {
2717                         src_node_id: hint_hops[1],
2718                         short_channel_id: 0xff01,
2719                         fees: zero_fees,
2720                         cltv_expiry_delta: (8 << 4) | 1,
2721                         htlc_minimum_msat: None,
2722                         htlc_maximum_msat: None,
2723                 }])]
2724         }
2725
2726         #[test]
2727         fn multi_hint_last_hops_test() {
2728                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2729                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2730                 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
2731                 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2732                 let scorer = test_utils::TestScorer::with_penalty(0);
2733                 // Test through channels 2, 3, 0xff00, 0xff01.
2734                 // Test shows that multiple hop hints are considered.
2735
2736                 // Disabling channels 6 & 7 by flags=2
2737                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2738                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2739                         short_channel_id: 6,
2740                         timestamp: 2,
2741                         flags: 2, // to disable
2742                         cltv_expiry_delta: 0,
2743                         htlc_minimum_msat: 0,
2744                         htlc_maximum_msat: OptionalField::Absent,
2745                         fee_base_msat: 0,
2746                         fee_proportional_millionths: 0,
2747                         excess_data: Vec::new()
2748                 });
2749                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2750                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2751                         short_channel_id: 7,
2752                         timestamp: 2,
2753                         flags: 2, // to disable
2754                         cltv_expiry_delta: 0,
2755                         htlc_minimum_msat: 0,
2756                         htlc_maximum_msat: OptionalField::Absent,
2757                         fee_base_msat: 0,
2758                         fee_proportional_millionths: 0,
2759                         excess_data: Vec::new()
2760                 });
2761
2762                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2763                 assert_eq!(route.paths[0].len(), 4);
2764
2765                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2766                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2767                 assert_eq!(route.paths[0][0].fee_msat, 200);
2768                 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2769                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2770                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2771
2772                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2773                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2774                 assert_eq!(route.paths[0][1].fee_msat, 100);
2775                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2776                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2777                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2778
2779                 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2780                 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2781                 assert_eq!(route.paths[0][2].fee_msat, 0);
2782                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2783                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2784                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2785
2786                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2787                 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2788                 assert_eq!(route.paths[0][3].fee_msat, 100);
2789                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2790                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2791                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2792         }
2793
2794         #[test]
2795         fn private_multi_hint_last_hops_test() {
2796                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2797                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2798
2799                 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
2800                 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
2801
2802                 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
2803                 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2804                 let scorer = test_utils::TestScorer::with_penalty(0);
2805                 // Test through channels 2, 3, 0xff00, 0xff01.
2806                 // Test shows that multiple hop hints are considered.
2807
2808                 // Disabling channels 6 & 7 by flags=2
2809                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2810                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2811                         short_channel_id: 6,
2812                         timestamp: 2,
2813                         flags: 2, // to disable
2814                         cltv_expiry_delta: 0,
2815                         htlc_minimum_msat: 0,
2816                         htlc_maximum_msat: OptionalField::Absent,
2817                         fee_base_msat: 0,
2818                         fee_proportional_millionths: 0,
2819                         excess_data: Vec::new()
2820                 });
2821                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2822                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2823                         short_channel_id: 7,
2824                         timestamp: 2,
2825                         flags: 2, // to disable
2826                         cltv_expiry_delta: 0,
2827                         htlc_minimum_msat: 0,
2828                         htlc_maximum_msat: OptionalField::Absent,
2829                         fee_base_msat: 0,
2830                         fee_proportional_millionths: 0,
2831                         excess_data: Vec::new()
2832                 });
2833
2834                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2835                 assert_eq!(route.paths[0].len(), 4);
2836
2837                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2838                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2839                 assert_eq!(route.paths[0][0].fee_msat, 200);
2840                 assert_eq!(route.paths[0][0].cltv_expiry_delta, 65);
2841                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2842                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2843
2844                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2845                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2846                 assert_eq!(route.paths[0][1].fee_msat, 100);
2847                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 81);
2848                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2849                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2850
2851                 assert_eq!(route.paths[0][2].pubkey, non_announced_pubkey);
2852                 assert_eq!(route.paths[0][2].short_channel_id, last_hops[0].0[0].short_channel_id);
2853                 assert_eq!(route.paths[0][2].fee_msat, 0);
2854                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 129);
2855                 assert_eq!(route.paths[0][2].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2856                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2857
2858                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2859                 assert_eq!(route.paths[0][3].short_channel_id, last_hops[0].0[1].short_channel_id);
2860                 assert_eq!(route.paths[0][3].fee_msat, 100);
2861                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2862                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2863                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2864         }
2865
2866         fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2867                 let zero_fees = RoutingFees {
2868                         base_msat: 0,
2869                         proportional_millionths: 0,
2870                 };
2871                 vec![RouteHint(vec![RouteHintHop {
2872                         src_node_id: nodes[4],
2873                         short_channel_id: 11,
2874                         fees: zero_fees,
2875                         cltv_expiry_delta: (11 << 4) | 1,
2876                         htlc_minimum_msat: None,
2877                         htlc_maximum_msat: None,
2878                 }, RouteHintHop {
2879                         src_node_id: nodes[3],
2880                         short_channel_id: 8,
2881                         fees: zero_fees,
2882                         cltv_expiry_delta: (8 << 4) | 1,
2883                         htlc_minimum_msat: None,
2884                         htlc_maximum_msat: None,
2885                 }]), RouteHint(vec![RouteHintHop {
2886                         src_node_id: nodes[4],
2887                         short_channel_id: 9,
2888                         fees: RoutingFees {
2889                                 base_msat: 1001,
2890                                 proportional_millionths: 0,
2891                         },
2892                         cltv_expiry_delta: (9 << 4) | 1,
2893                         htlc_minimum_msat: None,
2894                         htlc_maximum_msat: None,
2895                 }]), RouteHint(vec![RouteHintHop {
2896                         src_node_id: nodes[5],
2897                         short_channel_id: 10,
2898                         fees: zero_fees,
2899                         cltv_expiry_delta: (10 << 4) | 1,
2900                         htlc_minimum_msat: None,
2901                         htlc_maximum_msat: None,
2902                 }])]
2903         }
2904
2905         #[test]
2906         fn last_hops_with_public_channel_test() {
2907                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2908                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2909                 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2910                 let scorer = test_utils::TestScorer::with_penalty(0);
2911                 // This test shows that public routes can be present in the invoice
2912                 // which would be handled in the same manner.
2913
2914                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2915                 assert_eq!(route.paths[0].len(), 5);
2916
2917                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2918                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2919                 assert_eq!(route.paths[0][0].fee_msat, 100);
2920                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2921                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2922                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2923
2924                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2925                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2926                 assert_eq!(route.paths[0][1].fee_msat, 0);
2927                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
2928                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2929                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2930
2931                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2932                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2933                 assert_eq!(route.paths[0][2].fee_msat, 0);
2934                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
2935                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2936                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2937
2938                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2939                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2940                 assert_eq!(route.paths[0][3].fee_msat, 0);
2941                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
2942                 // If we have a peer in the node map, we'll use their features here since we don't have
2943                 // a way of figuring out their features from the invoice:
2944                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2945                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2946
2947                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2948                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2949                 assert_eq!(route.paths[0][4].fee_msat, 100);
2950                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2951                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2952                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2953         }
2954
2955         #[test]
2956         fn our_chans_last_hop_connect_test() {
2957                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2958                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2959                 let scorer = test_utils::TestScorer::with_penalty(0);
2960
2961                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2962                 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2963                 let mut last_hops = last_hops(&nodes);
2964                 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2965                 let route = get_route(&our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2966                 assert_eq!(route.paths[0].len(), 2);
2967
2968                 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2969                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2970                 assert_eq!(route.paths[0][0].fee_msat, 0);
2971                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
2972                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2973                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2974
2975                 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2976                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2977                 assert_eq!(route.paths[0][1].fee_msat, 100);
2978                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2979                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2980                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2981
2982                 last_hops[0].0[0].fees.base_msat = 1000;
2983
2984                 // Revert to via 6 as the fee on 8 goes up
2985                 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops);
2986                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2987                 assert_eq!(route.paths[0].len(), 4);
2988
2989                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2990                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2991                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2992                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
2993                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2994                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2995
2996                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2997                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2998                 assert_eq!(route.paths[0][1].fee_msat, 100);
2999                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 4) | 1);
3000                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3001                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3002
3003                 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
3004                 assert_eq!(route.paths[0][2].short_channel_id, 7);
3005                 assert_eq!(route.paths[0][2].fee_msat, 0);
3006                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 4) | 1);
3007                 // If we have a peer in the node map, we'll use their features here since we don't have
3008                 // a way of figuring out their features from the invoice:
3009                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3010                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
3011
3012                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
3013                 assert_eq!(route.paths[0][3].short_channel_id, 10);
3014                 assert_eq!(route.paths[0][3].fee_msat, 100);
3015                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
3016                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3017                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3018
3019                 // ...but still use 8 for larger payments as 6 has a variable feerate
3020                 let route = get_route(&our_id, &payment_params, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
3021                 assert_eq!(route.paths[0].len(), 5);
3022
3023                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3024                 assert_eq!(route.paths[0][0].short_channel_id, 2);
3025                 assert_eq!(route.paths[0][0].fee_msat, 3000);
3026                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 4) | 1);
3027                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
3028                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
3029
3030                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3031                 assert_eq!(route.paths[0][1].short_channel_id, 4);
3032                 assert_eq!(route.paths[0][1].fee_msat, 0);
3033                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 4) | 1);
3034                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3035                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
3036
3037                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
3038                 assert_eq!(route.paths[0][2].short_channel_id, 6);
3039                 assert_eq!(route.paths[0][2].fee_msat, 0);
3040                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 4) | 1);
3041                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
3042                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
3043
3044                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
3045                 assert_eq!(route.paths[0][3].short_channel_id, 11);
3046                 assert_eq!(route.paths[0][3].fee_msat, 1000);
3047                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 4) | 1);
3048                 // If we have a peer in the node map, we'll use their features here since we don't have
3049                 // a way of figuring out their features from the invoice:
3050                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
3051                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
3052
3053                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
3054                 assert_eq!(route.paths[0][4].short_channel_id, 8);
3055                 assert_eq!(route.paths[0][4].fee_msat, 2000);
3056                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
3057                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
3058                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3059         }
3060
3061         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> {
3062                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3063                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3064                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3065
3066                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3067                 let last_hops = RouteHint(vec![RouteHintHop {
3068                         src_node_id: middle_node_id,
3069                         short_channel_id: 8,
3070                         fees: RoutingFees {
3071                                 base_msat: 1000,
3072                                 proportional_millionths: last_hop_fee_prop,
3073                         },
3074                         cltv_expiry_delta: (8 << 4) | 1,
3075                         htlc_minimum_msat: None,
3076                         htlc_maximum_msat: last_hop_htlc_max,
3077                 }]);
3078                 let payment_params = PaymentParameters::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
3079                 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3080                 let scorer = test_utils::TestScorer::with_penalty(0);
3081                 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)
3082         }
3083
3084         #[test]
3085         fn unannounced_path_test() {
3086                 // We should be able to send a payment to a destination without any help of a routing graph
3087                 // if we have a channel with a common counterparty that appears in the first and last hop
3088                 // hints.
3089                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3090
3091                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3092                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3093                 assert_eq!(route.paths[0].len(), 2);
3094
3095                 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
3096                 assert_eq!(route.paths[0][0].short_channel_id, 42);
3097                 assert_eq!(route.paths[0][0].fee_msat, 1001);
3098                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 4) | 1);
3099                 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
3100                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3101
3102                 assert_eq!(route.paths[0][1].pubkey, target_node_id);
3103                 assert_eq!(route.paths[0][1].short_channel_id, 8);
3104                 assert_eq!(route.paths[0][1].fee_msat, 1000000);
3105                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3106                 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
3107                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3108         }
3109
3110         #[test]
3111         fn overflow_unannounced_path_test_liquidity_underflow() {
3112                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3113                 // the last-hop had a fee which overflowed a u64, we'd panic.
3114                 // This was due to us adding the first-hop from us unconditionally, causing us to think
3115                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3116                 // In this test, we previously hit a subtraction underflow due to having less available
3117                 // liquidity at the last hop than 0.
3118                 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());
3119         }
3120
3121         #[test]
3122         fn overflow_unannounced_path_test_feerate_overflow() {
3123                 // This tests for the same case as above, except instead of hitting a subtraction
3124                 // underflow, we hit a case where the fee charged at a hop overflowed.
3125                 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());
3126         }
3127
3128         #[test]
3129         fn available_amount_while_routing_test() {
3130                 // Tests whether we choose the correct available channel amount while routing.
3131
3132                 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
3133                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3134                 let scorer = test_utils::TestScorer::with_penalty(0);
3135                 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3136
3137                 // We will use a simple single-path route from
3138                 // our node to node2 via node0: channels {1, 3}.
3139
3140                 // First disable all other paths.
3141                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3142                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3143                         short_channel_id: 2,
3144                         timestamp: 2,
3145                         flags: 2,
3146                         cltv_expiry_delta: 0,
3147                         htlc_minimum_msat: 0,
3148                         htlc_maximum_msat: OptionalField::Present(100_000),
3149                         fee_base_msat: 0,
3150                         fee_proportional_millionths: 0,
3151                         excess_data: Vec::new()
3152                 });
3153                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3154                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3155                         short_channel_id: 12,
3156                         timestamp: 2,
3157                         flags: 2,
3158                         cltv_expiry_delta: 0,
3159                         htlc_minimum_msat: 0,
3160                         htlc_maximum_msat: OptionalField::Present(100_000),
3161                         fee_base_msat: 0,
3162                         fee_proportional_millionths: 0,
3163                         excess_data: Vec::new()
3164                 });
3165
3166                 // Make the first channel (#1) very permissive,
3167                 // and we will be testing all limits on the second channel.
3168                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3169                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3170                         short_channel_id: 1,
3171                         timestamp: 2,
3172                         flags: 0,
3173                         cltv_expiry_delta: 0,
3174                         htlc_minimum_msat: 0,
3175                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3176                         fee_base_msat: 0,
3177                         fee_proportional_millionths: 0,
3178                         excess_data: Vec::new()
3179                 });
3180
3181                 // First, let's see if routing works if we have absolutely no idea about the available amount.
3182                 // In this case, it should be set to 250_000 sats.
3183                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3184                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3185                         short_channel_id: 3,
3186                         timestamp: 2,
3187                         flags: 0,
3188                         cltv_expiry_delta: 0,
3189                         htlc_minimum_msat: 0,
3190                         htlc_maximum_msat: OptionalField::Absent,
3191                         fee_base_msat: 0,
3192                         fee_proportional_millionths: 0,
3193                         excess_data: Vec::new()
3194                 });
3195
3196                 {
3197                         // Attempt to route more than available results in a failure.
3198                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3199                                         &our_id, &payment_params, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3200                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3201                         } else { panic!(); }
3202                 }
3203
3204                 {
3205                         // Now, attempt to route an exact amount we have should be fine.
3206                         let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3207                         assert_eq!(route.paths.len(), 1);
3208                         let path = route.paths.last().unwrap();
3209                         assert_eq!(path.len(), 2);
3210                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3211                         assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3212                 }
3213
3214                 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3215                 // Disable channel #1 and use another first hop.
3216                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3217                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3218                         short_channel_id: 1,
3219                         timestamp: 3,
3220                         flags: 2,
3221                         cltv_expiry_delta: 0,
3222                         htlc_minimum_msat: 0,
3223                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3224                         fee_base_msat: 0,
3225                         fee_proportional_millionths: 0,
3226                         excess_data: Vec::new()
3227                 });
3228
3229                 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3230                 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3231
3232                 {
3233                         // Attempt to route more than available results in a failure.
3234                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3235                                         &our_id, &payment_params, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3236                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3237                         } else { panic!(); }
3238                 }
3239
3240                 {
3241                         // Now, attempt to route an exact amount we have should be fine.
3242                         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();
3243                         assert_eq!(route.paths.len(), 1);
3244                         let path = route.paths.last().unwrap();
3245                         assert_eq!(path.len(), 2);
3246                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3247                         assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3248                 }
3249
3250                 // Enable channel #1 back.
3251                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3252                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3253                         short_channel_id: 1,
3254                         timestamp: 4,
3255                         flags: 0,
3256                         cltv_expiry_delta: 0,
3257                         htlc_minimum_msat: 0,
3258                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3259                         fee_base_msat: 0,
3260                         fee_proportional_millionths: 0,
3261                         excess_data: Vec::new()
3262                 });
3263
3264
3265                 // Now let's see if routing works if we know only htlc_maximum_msat.
3266                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3267                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3268                         short_channel_id: 3,
3269                         timestamp: 3,
3270                         flags: 0,
3271                         cltv_expiry_delta: 0,
3272                         htlc_minimum_msat: 0,
3273                         htlc_maximum_msat: OptionalField::Present(15_000),
3274                         fee_base_msat: 0,
3275                         fee_proportional_millionths: 0,
3276                         excess_data: Vec::new()
3277                 });
3278
3279                 {
3280                         // Attempt to route more than available results in a failure.
3281                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3282                                         &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3283                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3284                         } else { panic!(); }
3285                 }
3286
3287                 {
3288                         // Now, attempt to route an exact amount we have should be fine.
3289                         let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3290                         assert_eq!(route.paths.len(), 1);
3291                         let path = route.paths.last().unwrap();
3292                         assert_eq!(path.len(), 2);
3293                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3294                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
3295                 }
3296
3297                 // Now let's see if routing works if we know only capacity from the UTXO.
3298
3299                 // We can't change UTXO capacity on the fly, so we'll disable
3300                 // the existing channel and add another one with the capacity we need.
3301                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3302                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3303                         short_channel_id: 3,
3304                         timestamp: 4,
3305                         flags: 2,
3306                         cltv_expiry_delta: 0,
3307                         htlc_minimum_msat: 0,
3308                         htlc_maximum_msat: OptionalField::Absent,
3309                         fee_base_msat: 0,
3310                         fee_proportional_millionths: 0,
3311                         excess_data: Vec::new()
3312                 });
3313
3314                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3315                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3316                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3317                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3318                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3319
3320                 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3321                 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3322
3323                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3324                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3325                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3326                         short_channel_id: 333,
3327                         timestamp: 1,
3328                         flags: 0,
3329                         cltv_expiry_delta: (3 << 4) | 1,
3330                         htlc_minimum_msat: 0,
3331                         htlc_maximum_msat: OptionalField::Absent,
3332                         fee_base_msat: 0,
3333                         fee_proportional_millionths: 0,
3334                         excess_data: Vec::new()
3335                 });
3336                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3337                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3338                         short_channel_id: 333,
3339                         timestamp: 1,
3340                         flags: 1,
3341                         cltv_expiry_delta: (3 << 4) | 2,
3342                         htlc_minimum_msat: 0,
3343                         htlc_maximum_msat: OptionalField::Absent,
3344                         fee_base_msat: 100,
3345                         fee_proportional_millionths: 0,
3346                         excess_data: Vec::new()
3347                 });
3348
3349                 {
3350                         // Attempt to route more than available results in a failure.
3351                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3352                                         &our_id, &payment_params, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3353                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3354                         } else { panic!(); }
3355                 }
3356
3357                 {
3358                         // Now, attempt to route an exact amount we have should be fine.
3359                         let route = get_route(&our_id, &payment_params, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3360                         assert_eq!(route.paths.len(), 1);
3361                         let path = route.paths.last().unwrap();
3362                         assert_eq!(path.len(), 2);
3363                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3364                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
3365                 }
3366
3367                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3368                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3369                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3370                         short_channel_id: 333,
3371                         timestamp: 6,
3372                         flags: 0,
3373                         cltv_expiry_delta: 0,
3374                         htlc_minimum_msat: 0,
3375                         htlc_maximum_msat: OptionalField::Present(10_000),
3376                         fee_base_msat: 0,
3377                         fee_proportional_millionths: 0,
3378                         excess_data: Vec::new()
3379                 });
3380
3381                 {
3382                         // Attempt to route more than available results in a failure.
3383                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3384                                         &our_id, &payment_params, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3385                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3386                         } else { panic!(); }
3387                 }
3388
3389                 {
3390                         // Now, attempt to route an exact amount we have should be fine.
3391                         let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3392                         assert_eq!(route.paths.len(), 1);
3393                         let path = route.paths.last().unwrap();
3394                         assert_eq!(path.len(), 2);
3395                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3396                         assert_eq!(path.last().unwrap().fee_msat, 10_000);
3397                 }
3398         }
3399
3400         #[test]
3401         fn available_liquidity_last_hop_test() {
3402                 // Check that available liquidity properly limits the path even when only
3403                 // one of the latter hops is limited.
3404                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3405                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3406                 let scorer = test_utils::TestScorer::with_penalty(0);
3407                 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3408
3409                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3410                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3411                 // Total capacity: 50 sats.
3412
3413                 // Disable other potential paths.
3414                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3415                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3416                         short_channel_id: 2,
3417                         timestamp: 2,
3418                         flags: 2,
3419                         cltv_expiry_delta: 0,
3420                         htlc_minimum_msat: 0,
3421                         htlc_maximum_msat: OptionalField::Present(100_000),
3422                         fee_base_msat: 0,
3423                         fee_proportional_millionths: 0,
3424                         excess_data: Vec::new()
3425                 });
3426                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3427                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3428                         short_channel_id: 7,
3429                         timestamp: 2,
3430                         flags: 2,
3431                         cltv_expiry_delta: 0,
3432                         htlc_minimum_msat: 0,
3433                         htlc_maximum_msat: OptionalField::Present(100_000),
3434                         fee_base_msat: 0,
3435                         fee_proportional_millionths: 0,
3436                         excess_data: Vec::new()
3437                 });
3438
3439                 // Limit capacities
3440
3441                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3442                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3443                         short_channel_id: 12,
3444                         timestamp: 2,
3445                         flags: 0,
3446                         cltv_expiry_delta: 0,
3447                         htlc_minimum_msat: 0,
3448                         htlc_maximum_msat: OptionalField::Present(100_000),
3449                         fee_base_msat: 0,
3450                         fee_proportional_millionths: 0,
3451                         excess_data: Vec::new()
3452                 });
3453                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3454                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3455                         short_channel_id: 13,
3456                         timestamp: 2,
3457                         flags: 0,
3458                         cltv_expiry_delta: 0,
3459                         htlc_minimum_msat: 0,
3460                         htlc_maximum_msat: OptionalField::Present(100_000),
3461                         fee_base_msat: 0,
3462                         fee_proportional_millionths: 0,
3463                         excess_data: Vec::new()
3464                 });
3465
3466                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3467                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3468                         short_channel_id: 6,
3469                         timestamp: 2,
3470                         flags: 0,
3471                         cltv_expiry_delta: 0,
3472                         htlc_minimum_msat: 0,
3473                         htlc_maximum_msat: OptionalField::Present(50_000),
3474                         fee_base_msat: 0,
3475                         fee_proportional_millionths: 0,
3476                         excess_data: Vec::new()
3477                 });
3478                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3479                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3480                         short_channel_id: 11,
3481                         timestamp: 2,
3482                         flags: 0,
3483                         cltv_expiry_delta: 0,
3484                         htlc_minimum_msat: 0,
3485                         htlc_maximum_msat: OptionalField::Present(100_000),
3486                         fee_base_msat: 0,
3487                         fee_proportional_millionths: 0,
3488                         excess_data: Vec::new()
3489                 });
3490                 {
3491                         // Attempt to route more than available results in a failure.
3492                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3493                                         &our_id, &payment_params, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3494                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3495                         } else { panic!(); }
3496                 }
3497
3498                 {
3499                         // Now, attempt to route 49 sats (just a bit below the capacity).
3500                         let route = get_route(&our_id, &payment_params, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3501                         assert_eq!(route.paths.len(), 1);
3502                         let mut total_amount_paid_msat = 0;
3503                         for path in &route.paths {
3504                                 assert_eq!(path.len(), 4);
3505                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3506                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3507                         }
3508                         assert_eq!(total_amount_paid_msat, 49_000);
3509                 }
3510
3511                 {
3512                         // Attempt to route an exact amount is also fine
3513                         let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3514                         assert_eq!(route.paths.len(), 1);
3515                         let mut total_amount_paid_msat = 0;
3516                         for path in &route.paths {
3517                                 assert_eq!(path.len(), 4);
3518                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3519                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3520                         }
3521                         assert_eq!(total_amount_paid_msat, 50_000);
3522                 }
3523         }
3524
3525         #[test]
3526         fn ignore_fee_first_hop_test() {
3527                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3528                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3529                 let scorer = test_utils::TestScorer::with_penalty(0);
3530                 let payment_params = PaymentParameters::from_node_id(nodes[2]);
3531
3532                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3533                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3534                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3535                         short_channel_id: 1,
3536                         timestamp: 2,
3537                         flags: 0,
3538                         cltv_expiry_delta: 0,
3539                         htlc_minimum_msat: 0,
3540                         htlc_maximum_msat: OptionalField::Present(100_000),
3541                         fee_base_msat: 1_000_000,
3542                         fee_proportional_millionths: 0,
3543                         excess_data: Vec::new()
3544                 });
3545                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3546                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3547                         short_channel_id: 3,
3548                         timestamp: 2,
3549                         flags: 0,
3550                         cltv_expiry_delta: 0,
3551                         htlc_minimum_msat: 0,
3552                         htlc_maximum_msat: OptionalField::Present(50_000),
3553                         fee_base_msat: 0,
3554                         fee_proportional_millionths: 0,
3555                         excess_data: Vec::new()
3556                 });
3557
3558                 {
3559                         let route = get_route(&our_id, &payment_params, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3560                         assert_eq!(route.paths.len(), 1);
3561                         let mut total_amount_paid_msat = 0;
3562                         for path in &route.paths {
3563                                 assert_eq!(path.len(), 2);
3564                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3565                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3566                         }
3567                         assert_eq!(total_amount_paid_msat, 50_000);
3568                 }
3569         }
3570
3571         #[test]
3572         fn simple_mpp_route_test() {
3573                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3574                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3575                 let scorer = test_utils::TestScorer::with_penalty(0);
3576                 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3577
3578                 // We need a route consisting of 3 paths:
3579                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3580                 // To achieve this, the amount being transferred should be around
3581                 // the total capacity of these 3 paths.
3582
3583                 // First, we set limits on these (previously unlimited) channels.
3584                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3585
3586                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3587                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3588                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3589                         short_channel_id: 1,
3590                         timestamp: 2,
3591                         flags: 0,
3592                         cltv_expiry_delta: 0,
3593                         htlc_minimum_msat: 0,
3594                         htlc_maximum_msat: OptionalField::Present(100_000),
3595                         fee_base_msat: 0,
3596                         fee_proportional_millionths: 0,
3597                         excess_data: Vec::new()
3598                 });
3599                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3600                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3601                         short_channel_id: 3,
3602                         timestamp: 2,
3603                         flags: 0,
3604                         cltv_expiry_delta: 0,
3605                         htlc_minimum_msat: 0,
3606                         htlc_maximum_msat: OptionalField::Present(50_000),
3607                         fee_base_msat: 0,
3608                         fee_proportional_millionths: 0,
3609                         excess_data: Vec::new()
3610                 });
3611
3612                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3613                 // (total limit 60).
3614                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3615                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3616                         short_channel_id: 12,
3617                         timestamp: 2,
3618                         flags: 0,
3619                         cltv_expiry_delta: 0,
3620                         htlc_minimum_msat: 0,
3621                         htlc_maximum_msat: OptionalField::Present(60_000),
3622                         fee_base_msat: 0,
3623                         fee_proportional_millionths: 0,
3624                         excess_data: Vec::new()
3625                 });
3626                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3627                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3628                         short_channel_id: 13,
3629                         timestamp: 2,
3630                         flags: 0,
3631                         cltv_expiry_delta: 0,
3632                         htlc_minimum_msat: 0,
3633                         htlc_maximum_msat: OptionalField::Present(60_000),
3634                         fee_base_msat: 0,
3635                         fee_proportional_millionths: 0,
3636                         excess_data: Vec::new()
3637                 });
3638
3639                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3640                 // (total capacity 180 sats).
3641                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3642                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3643                         short_channel_id: 2,
3644                         timestamp: 2,
3645                         flags: 0,
3646                         cltv_expiry_delta: 0,
3647                         htlc_minimum_msat: 0,
3648                         htlc_maximum_msat: OptionalField::Present(200_000),
3649                         fee_base_msat: 0,
3650                         fee_proportional_millionths: 0,
3651                         excess_data: Vec::new()
3652                 });
3653                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3654                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3655                         short_channel_id: 4,
3656                         timestamp: 2,
3657                         flags: 0,
3658                         cltv_expiry_delta: 0,
3659                         htlc_minimum_msat: 0,
3660                         htlc_maximum_msat: OptionalField::Present(180_000),
3661                         fee_base_msat: 0,
3662                         fee_proportional_millionths: 0,
3663                         excess_data: Vec::new()
3664                 });
3665
3666                 {
3667                         // Attempt to route more than available results in a failure.
3668                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3669                                         &our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3670                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3671                         } else { panic!(); }
3672                 }
3673
3674                 {
3675                         // Now, attempt to route 250 sats (just a bit below the capacity).
3676                         // Our algorithm should provide us with these 3 paths.
3677                         let route = get_route(&our_id, &payment_params, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3678                         assert_eq!(route.paths.len(), 3);
3679                         let mut total_amount_paid_msat = 0;
3680                         for path in &route.paths {
3681                                 assert_eq!(path.len(), 2);
3682                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3683                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3684                         }
3685                         assert_eq!(total_amount_paid_msat, 250_000);
3686                 }
3687
3688                 {
3689                         // Attempt to route an exact amount is also fine
3690                         let route = get_route(&our_id, &payment_params, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3691                         assert_eq!(route.paths.len(), 3);
3692                         let mut total_amount_paid_msat = 0;
3693                         for path in &route.paths {
3694                                 assert_eq!(path.len(), 2);
3695                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3696                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3697                         }
3698                         assert_eq!(total_amount_paid_msat, 290_000);
3699                 }
3700         }
3701
3702         #[test]
3703         fn long_mpp_route_test() {
3704                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3705                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3706                 let scorer = test_utils::TestScorer::with_penalty(0);
3707                 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3708
3709                 // We need a route consisting of 3 paths:
3710                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3711                 // Note that these paths overlap (channels 5, 12, 13).
3712                 // We will route 300 sats.
3713                 // Each path will have 100 sats capacity, those channels which
3714                 // are used twice will have 200 sats capacity.
3715
3716                 // Disable other potential paths.
3717                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3718                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3719                         short_channel_id: 2,
3720                         timestamp: 2,
3721                         flags: 2,
3722                         cltv_expiry_delta: 0,
3723                         htlc_minimum_msat: 0,
3724                         htlc_maximum_msat: OptionalField::Present(100_000),
3725                         fee_base_msat: 0,
3726                         fee_proportional_millionths: 0,
3727                         excess_data: Vec::new()
3728                 });
3729                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3730                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3731                         short_channel_id: 7,
3732                         timestamp: 2,
3733                         flags: 2,
3734                         cltv_expiry_delta: 0,
3735                         htlc_minimum_msat: 0,
3736                         htlc_maximum_msat: OptionalField::Present(100_000),
3737                         fee_base_msat: 0,
3738                         fee_proportional_millionths: 0,
3739                         excess_data: Vec::new()
3740                 });
3741
3742                 // Path via {node0, node2} is channels {1, 3, 5}.
3743                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3744                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3745                         short_channel_id: 1,
3746                         timestamp: 2,
3747                         flags: 0,
3748                         cltv_expiry_delta: 0,
3749                         htlc_minimum_msat: 0,
3750                         htlc_maximum_msat: OptionalField::Present(100_000),
3751                         fee_base_msat: 0,
3752                         fee_proportional_millionths: 0,
3753                         excess_data: Vec::new()
3754                 });
3755                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3756                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3757                         short_channel_id: 3,
3758                         timestamp: 2,
3759                         flags: 0,
3760                         cltv_expiry_delta: 0,
3761                         htlc_minimum_msat: 0,
3762                         htlc_maximum_msat: OptionalField::Present(100_000),
3763                         fee_base_msat: 0,
3764                         fee_proportional_millionths: 0,
3765                         excess_data: Vec::new()
3766                 });
3767
3768                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3769                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3770                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3771                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3772                         short_channel_id: 5,
3773                         timestamp: 2,
3774                         flags: 0,
3775                         cltv_expiry_delta: 0,
3776                         htlc_minimum_msat: 0,
3777                         htlc_maximum_msat: OptionalField::Present(200_000),
3778                         fee_base_msat: 0,
3779                         fee_proportional_millionths: 0,
3780                         excess_data: Vec::new()
3781                 });
3782
3783                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3784                 // Add 100 sats to the capacities of {12, 13}, because these channels
3785                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3786                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3787                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3788                         short_channel_id: 12,
3789                         timestamp: 2,
3790                         flags: 0,
3791                         cltv_expiry_delta: 0,
3792                         htlc_minimum_msat: 0,
3793                         htlc_maximum_msat: OptionalField::Present(200_000),
3794                         fee_base_msat: 0,
3795                         fee_proportional_millionths: 0,
3796                         excess_data: Vec::new()
3797                 });
3798                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3799                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3800                         short_channel_id: 13,
3801                         timestamp: 2,
3802                         flags: 0,
3803                         cltv_expiry_delta: 0,
3804                         htlc_minimum_msat: 0,
3805                         htlc_maximum_msat: OptionalField::Present(200_000),
3806                         fee_base_msat: 0,
3807                         fee_proportional_millionths: 0,
3808                         excess_data: Vec::new()
3809                 });
3810
3811                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3812                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3813                         short_channel_id: 6,
3814                         timestamp: 2,
3815                         flags: 0,
3816                         cltv_expiry_delta: 0,
3817                         htlc_minimum_msat: 0,
3818                         htlc_maximum_msat: OptionalField::Present(100_000),
3819                         fee_base_msat: 0,
3820                         fee_proportional_millionths: 0,
3821                         excess_data: Vec::new()
3822                 });
3823                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3824                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3825                         short_channel_id: 11,
3826                         timestamp: 2,
3827                         flags: 0,
3828                         cltv_expiry_delta: 0,
3829                         htlc_minimum_msat: 0,
3830                         htlc_maximum_msat: OptionalField::Present(100_000),
3831                         fee_base_msat: 0,
3832                         fee_proportional_millionths: 0,
3833                         excess_data: Vec::new()
3834                 });
3835
3836                 // Path via {node7, node2} is channels {12, 13, 5}.
3837                 // We already limited them to 200 sats (they are used twice for 100 sats).
3838                 // Nothing to do here.
3839
3840                 {
3841                         // Attempt to route more than available results in a failure.
3842                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3843                                         &our_id, &payment_params, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3844                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3845                         } else { panic!(); }
3846                 }
3847
3848                 {
3849                         // Now, attempt to route 300 sats (exact amount we can route).
3850                         // Our algorithm should provide us with these 3 paths, 100 sats each.
3851                         let route = get_route(&our_id, &payment_params, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3852                         assert_eq!(route.paths.len(), 3);
3853
3854                         let mut total_amount_paid_msat = 0;
3855                         for path in &route.paths {
3856                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3857                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3858                         }
3859                         assert_eq!(total_amount_paid_msat, 300_000);
3860                 }
3861
3862         }
3863
3864         #[test]
3865         fn mpp_cheaper_route_test() {
3866                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3867                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3868                 let scorer = test_utils::TestScorer::with_penalty(0);
3869                 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3870
3871                 // This test checks that if we have two cheaper paths and one more expensive path,
3872                 // so that liquidity-wise any 2 of 3 combination is sufficient,
3873                 // two cheaper paths will be taken.
3874                 // These paths have equal available liquidity.
3875
3876                 // We need a combination of 3 paths:
3877                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3878                 // Note that these paths overlap (channels 5, 12, 13).
3879                 // Each path will have 100 sats capacity, those channels which
3880                 // are used twice will have 200 sats capacity.
3881
3882                 // Disable other potential paths.
3883                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3884                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3885                         short_channel_id: 2,
3886                         timestamp: 2,
3887                         flags: 2,
3888                         cltv_expiry_delta: 0,
3889                         htlc_minimum_msat: 0,
3890                         htlc_maximum_msat: OptionalField::Present(100_000),
3891                         fee_base_msat: 0,
3892                         fee_proportional_millionths: 0,
3893                         excess_data: Vec::new()
3894                 });
3895                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3896                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3897                         short_channel_id: 7,
3898                         timestamp: 2,
3899                         flags: 2,
3900                         cltv_expiry_delta: 0,
3901                         htlc_minimum_msat: 0,
3902                         htlc_maximum_msat: OptionalField::Present(100_000),
3903                         fee_base_msat: 0,
3904                         fee_proportional_millionths: 0,
3905                         excess_data: Vec::new()
3906                 });
3907
3908                 // Path via {node0, node2} is channels {1, 3, 5}.
3909                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3910                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3911                         short_channel_id: 1,
3912                         timestamp: 2,
3913                         flags: 0,
3914                         cltv_expiry_delta: 0,
3915                         htlc_minimum_msat: 0,
3916                         htlc_maximum_msat: OptionalField::Present(100_000),
3917                         fee_base_msat: 0,
3918                         fee_proportional_millionths: 0,
3919                         excess_data: Vec::new()
3920                 });
3921                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3922                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3923                         short_channel_id: 3,
3924                         timestamp: 2,
3925                         flags: 0,
3926                         cltv_expiry_delta: 0,
3927                         htlc_minimum_msat: 0,
3928                         htlc_maximum_msat: OptionalField::Present(100_000),
3929                         fee_base_msat: 0,
3930                         fee_proportional_millionths: 0,
3931                         excess_data: Vec::new()
3932                 });
3933
3934                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3935                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3936                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3937                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3938                         short_channel_id: 5,
3939                         timestamp: 2,
3940                         flags: 0,
3941                         cltv_expiry_delta: 0,
3942                         htlc_minimum_msat: 0,
3943                         htlc_maximum_msat: OptionalField::Present(200_000),
3944                         fee_base_msat: 0,
3945                         fee_proportional_millionths: 0,
3946                         excess_data: Vec::new()
3947                 });
3948
3949                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3950                 // Add 100 sats to the capacities of {12, 13}, because these channels
3951                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3952                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3953                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3954                         short_channel_id: 12,
3955                         timestamp: 2,
3956                         flags: 0,
3957                         cltv_expiry_delta: 0,
3958                         htlc_minimum_msat: 0,
3959                         htlc_maximum_msat: OptionalField::Present(200_000),
3960                         fee_base_msat: 0,
3961                         fee_proportional_millionths: 0,
3962                         excess_data: Vec::new()
3963                 });
3964                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3965                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3966                         short_channel_id: 13,
3967                         timestamp: 2,
3968                         flags: 0,
3969                         cltv_expiry_delta: 0,
3970                         htlc_minimum_msat: 0,
3971                         htlc_maximum_msat: OptionalField::Present(200_000),
3972                         fee_base_msat: 0,
3973                         fee_proportional_millionths: 0,
3974                         excess_data: Vec::new()
3975                 });
3976
3977                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3978                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3979                         short_channel_id: 6,
3980                         timestamp: 2,
3981                         flags: 0,
3982                         cltv_expiry_delta: 0,
3983                         htlc_minimum_msat: 0,
3984                         htlc_maximum_msat: OptionalField::Present(100_000),
3985                         fee_base_msat: 1_000,
3986                         fee_proportional_millionths: 0,
3987                         excess_data: Vec::new()
3988                 });
3989                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3990                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3991                         short_channel_id: 11,
3992                         timestamp: 2,
3993                         flags: 0,
3994                         cltv_expiry_delta: 0,
3995                         htlc_minimum_msat: 0,
3996                         htlc_maximum_msat: OptionalField::Present(100_000),
3997                         fee_base_msat: 0,
3998                         fee_proportional_millionths: 0,
3999                         excess_data: Vec::new()
4000                 });
4001
4002                 // Path via {node7, node2} is channels {12, 13, 5}.
4003                 // We already limited them to 200 sats (they are used twice for 100 sats).
4004                 // Nothing to do here.
4005
4006                 {
4007                         // Now, attempt to route 180 sats.
4008                         // Our algorithm should provide us with these 2 paths.
4009                         let route = get_route(&our_id, &payment_params, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
4010                         assert_eq!(route.paths.len(), 2);
4011
4012                         let mut total_value_transferred_msat = 0;
4013                         let mut total_paid_msat = 0;
4014                         for path in &route.paths {
4015                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4016                                 total_value_transferred_msat += path.last().unwrap().fee_msat;
4017                                 for hop in path {
4018                                         total_paid_msat += hop.fee_msat;
4019                                 }
4020                         }
4021                         // If we paid fee, this would be higher.
4022                         assert_eq!(total_value_transferred_msat, 180_000);
4023                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4024                         assert_eq!(total_fees_paid, 0);
4025                 }
4026         }
4027
4028         #[test]
4029         fn fees_on_mpp_route_test() {
4030                 // This test makes sure that MPP algorithm properly takes into account
4031                 // fees charged on the channels, by making the fees impactful:
4032                 // if the fee is not properly accounted for, the behavior is different.
4033                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4034                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4035                 let scorer = test_utils::TestScorer::with_penalty(0);
4036                 let payment_params = PaymentParameters::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
4037
4038                 // We need a route consisting of 2 paths:
4039                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4040                 // We will route 200 sats, Each path will have 100 sats capacity.
4041
4042                 // This test is not particularly stable: e.g.,
4043                 // there's a way to route via {node0, node2, node4}.
4044                 // It works while pathfinding is deterministic, but can be broken otherwise.
4045                 // It's fine to ignore this concern for now.
4046
4047                 // Disable other potential paths.
4048                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4049                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4050                         short_channel_id: 2,
4051                         timestamp: 2,
4052                         flags: 2,
4053                         cltv_expiry_delta: 0,
4054                         htlc_minimum_msat: 0,
4055                         htlc_maximum_msat: OptionalField::Present(100_000),
4056                         fee_base_msat: 0,
4057                         fee_proportional_millionths: 0,
4058                         excess_data: Vec::new()
4059                 });
4060
4061                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4062                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4063                         short_channel_id: 7,
4064                         timestamp: 2,
4065                         flags: 2,
4066                         cltv_expiry_delta: 0,
4067                         htlc_minimum_msat: 0,
4068                         htlc_maximum_msat: OptionalField::Present(100_000),
4069                         fee_base_msat: 0,
4070                         fee_proportional_millionths: 0,
4071                         excess_data: Vec::new()
4072                 });
4073
4074                 // Path via {node0, node2} is channels {1, 3, 5}.
4075                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4076                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4077                         short_channel_id: 1,
4078                         timestamp: 2,
4079                         flags: 0,
4080                         cltv_expiry_delta: 0,
4081                         htlc_minimum_msat: 0,
4082                         htlc_maximum_msat: OptionalField::Present(100_000),
4083                         fee_base_msat: 0,
4084                         fee_proportional_millionths: 0,
4085                         excess_data: Vec::new()
4086                 });
4087                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4088                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4089                         short_channel_id: 3,
4090                         timestamp: 2,
4091                         flags: 0,
4092                         cltv_expiry_delta: 0,
4093                         htlc_minimum_msat: 0,
4094                         htlc_maximum_msat: OptionalField::Present(100_000),
4095                         fee_base_msat: 0,
4096                         fee_proportional_millionths: 0,
4097                         excess_data: Vec::new()
4098                 });
4099
4100                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4101                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4102                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4103                         short_channel_id: 5,
4104                         timestamp: 2,
4105                         flags: 0,
4106                         cltv_expiry_delta: 0,
4107                         htlc_minimum_msat: 0,
4108                         htlc_maximum_msat: OptionalField::Present(100_000),
4109                         fee_base_msat: 0,
4110                         fee_proportional_millionths: 0,
4111                         excess_data: Vec::new()
4112                 });
4113
4114                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4115                 // All channels should be 100 sats capacity. But for the fee experiment,
4116                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4117                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4118                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4119                 // so no matter how large are other channels,
4120                 // the whole path will be limited by 100 sats with just these 2 conditions:
4121                 // - channel 12 capacity is 250 sats
4122                 // - fee for channel 6 is 150 sats
4123                 // Let's test this by enforcing these 2 conditions and removing other limits.
4124                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4125                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4126                         short_channel_id: 12,
4127                         timestamp: 2,
4128                         flags: 0,
4129                         cltv_expiry_delta: 0,
4130                         htlc_minimum_msat: 0,
4131                         htlc_maximum_msat: OptionalField::Present(250_000),
4132                         fee_base_msat: 0,
4133                         fee_proportional_millionths: 0,
4134                         excess_data: Vec::new()
4135                 });
4136                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4137                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4138                         short_channel_id: 13,
4139                         timestamp: 2,
4140                         flags: 0,
4141                         cltv_expiry_delta: 0,
4142                         htlc_minimum_msat: 0,
4143                         htlc_maximum_msat: OptionalField::Absent,
4144                         fee_base_msat: 0,
4145                         fee_proportional_millionths: 0,
4146                         excess_data: Vec::new()
4147                 });
4148
4149                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4150                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4151                         short_channel_id: 6,
4152                         timestamp: 2,
4153                         flags: 0,
4154                         cltv_expiry_delta: 0,
4155                         htlc_minimum_msat: 0,
4156                         htlc_maximum_msat: OptionalField::Absent,
4157                         fee_base_msat: 150_000,
4158                         fee_proportional_millionths: 0,
4159                         excess_data: Vec::new()
4160                 });
4161                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4162                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4163                         short_channel_id: 11,
4164                         timestamp: 2,
4165                         flags: 0,
4166                         cltv_expiry_delta: 0,
4167                         htlc_minimum_msat: 0,
4168                         htlc_maximum_msat: OptionalField::Absent,
4169                         fee_base_msat: 0,
4170                         fee_proportional_millionths: 0,
4171                         excess_data: Vec::new()
4172                 });
4173
4174                 {
4175                         // Attempt to route more than available results in a failure.
4176                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4177                                         &our_id, &payment_params, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4178                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4179                         } else { panic!(); }
4180                 }
4181
4182                 {
4183                         // Now, attempt to route 200 sats (exact amount we can route).
4184                         let route = get_route(&our_id, &payment_params, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4185                         assert_eq!(route.paths.len(), 2);
4186
4187                         let mut total_amount_paid_msat = 0;
4188                         for path in &route.paths {
4189                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4190                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
4191                         }
4192                         assert_eq!(total_amount_paid_msat, 200_000);
4193                         assert_eq!(route.get_total_fees(), 150_000);
4194                 }
4195         }
4196
4197         #[test]
4198         fn mpp_with_last_hops() {
4199                 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4200                 // via a single last-hop route hint, we'd fail to route if we first collected routes
4201                 // totaling close but not quite enough to fund the full payment.
4202                 //
4203                 // This was because we considered last-hop hints to have exactly the sought payment amount
4204                 // instead of the amount we were trying to collect, needlessly limiting our path searching
4205                 // at the very first hop.
4206                 //
4207                 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4208                 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4209                 // to only have the remaining to-collect amount in available liquidity.
4210                 //
4211                 // This bug appeared in production in some specific channel configurations.
4212                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4213                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4214                 let scorer = test_utils::TestScorer::with_penalty(0);
4215                 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap()).with_features(InvoiceFeatures::known())
4216                         .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4217                                 src_node_id: nodes[2],
4218                                 short_channel_id: 42,
4219                                 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4220                                 cltv_expiry_delta: 42,
4221                                 htlc_minimum_msat: None,
4222                                 htlc_maximum_msat: None,
4223                         }])]);
4224
4225                 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4226                 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4227                 // would first use the no-fee route and then fail to find a path along the second route as
4228                 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4229                 // under 5% of our payment amount.
4230                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4231                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4232                         short_channel_id: 1,
4233                         timestamp: 2,
4234                         flags: 0,
4235                         cltv_expiry_delta: (5 << 4) | 5,
4236                         htlc_minimum_msat: 0,
4237                         htlc_maximum_msat: OptionalField::Present(99_000),
4238                         fee_base_msat: u32::max_value(),
4239                         fee_proportional_millionths: u32::max_value(),
4240                         excess_data: Vec::new()
4241                 });
4242                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4243                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4244                         short_channel_id: 2,
4245                         timestamp: 2,
4246                         flags: 0,
4247                         cltv_expiry_delta: (5 << 4) | 3,
4248                         htlc_minimum_msat: 0,
4249                         htlc_maximum_msat: OptionalField::Present(99_000),
4250                         fee_base_msat: u32::max_value(),
4251                         fee_proportional_millionths: u32::max_value(),
4252                         excess_data: Vec::new()
4253                 });
4254                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4255                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4256                         short_channel_id: 4,
4257                         timestamp: 2,
4258                         flags: 0,
4259                         cltv_expiry_delta: (4 << 4) | 1,
4260                         htlc_minimum_msat: 0,
4261                         htlc_maximum_msat: OptionalField::Absent,
4262                         fee_base_msat: 1,
4263                         fee_proportional_millionths: 0,
4264                         excess_data: Vec::new()
4265                 });
4266                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4267                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4268                         short_channel_id: 13,
4269                         timestamp: 2,
4270                         flags: 0|2, // Channel disabled
4271                         cltv_expiry_delta: (13 << 4) | 1,
4272                         htlc_minimum_msat: 0,
4273                         htlc_maximum_msat: OptionalField::Absent,
4274                         fee_base_msat: 0,
4275                         fee_proportional_millionths: 2000000,
4276                         excess_data: Vec::new()
4277                 });
4278
4279                 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4280                 // overpay at all.
4281                 let route = get_route(&our_id, &payment_params, &network_graph, None, 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4282                 assert_eq!(route.paths.len(), 2);
4283                 // Paths are somewhat randomly ordered, but:
4284                 // * the first is channel 2 (1 msat fee) -> channel 4 -> channel 42
4285                 // * the second is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4286                 assert_eq!(route.paths[0][0].short_channel_id, 2);
4287                 assert_eq!(route.paths[0][0].fee_msat, 1);
4288                 assert_eq!(route.paths[0][2].fee_msat, 1_000);
4289                 assert_eq!(route.paths[1][0].short_channel_id, 1);
4290                 assert_eq!(route.paths[1][0].fee_msat, 0);
4291                 assert_eq!(route.paths[1][2].fee_msat, 99_000);
4292                 assert_eq!(route.get_total_fees(), 1);
4293                 assert_eq!(route.get_total_amount(), 100_000);
4294         }
4295
4296         #[test]
4297         fn drop_lowest_channel_mpp_route_test() {
4298                 // This test checks that low-capacity channel is dropped when after
4299                 // path finding we realize that we found more capacity than we need.
4300                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4301                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4302                 let scorer = test_utils::TestScorer::with_penalty(0);
4303                 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4304
4305                 // We need a route consisting of 3 paths:
4306                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4307
4308                 // The first and the second paths should be sufficient, but the third should be
4309                 // cheaper, so that we select it but drop later.
4310
4311                 // First, we set limits on these (previously unlimited) channels.
4312                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4313
4314                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4315                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4316                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4317                         short_channel_id: 1,
4318                         timestamp: 2,
4319                         flags: 0,
4320                         cltv_expiry_delta: 0,
4321                         htlc_minimum_msat: 0,
4322                         htlc_maximum_msat: OptionalField::Present(100_000),
4323                         fee_base_msat: 0,
4324                         fee_proportional_millionths: 0,
4325                         excess_data: Vec::new()
4326                 });
4327                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4328                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4329                         short_channel_id: 3,
4330                         timestamp: 2,
4331                         flags: 0,
4332                         cltv_expiry_delta: 0,
4333                         htlc_minimum_msat: 0,
4334                         htlc_maximum_msat: OptionalField::Present(50_000),
4335                         fee_base_msat: 100,
4336                         fee_proportional_millionths: 0,
4337                         excess_data: Vec::new()
4338                 });
4339
4340                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4341                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4342                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4343                         short_channel_id: 12,
4344                         timestamp: 2,
4345                         flags: 0,
4346                         cltv_expiry_delta: 0,
4347                         htlc_minimum_msat: 0,
4348                         htlc_maximum_msat: OptionalField::Present(60_000),
4349                         fee_base_msat: 100,
4350                         fee_proportional_millionths: 0,
4351                         excess_data: Vec::new()
4352                 });
4353                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4354                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4355                         short_channel_id: 13,
4356                         timestamp: 2,
4357                         flags: 0,
4358                         cltv_expiry_delta: 0,
4359                         htlc_minimum_msat: 0,
4360                         htlc_maximum_msat: OptionalField::Present(60_000),
4361                         fee_base_msat: 0,
4362                         fee_proportional_millionths: 0,
4363                         excess_data: Vec::new()
4364                 });
4365
4366                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4367                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4368                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4369                         short_channel_id: 2,
4370                         timestamp: 2,
4371                         flags: 0,
4372                         cltv_expiry_delta: 0,
4373                         htlc_minimum_msat: 0,
4374                         htlc_maximum_msat: OptionalField::Present(20_000),
4375                         fee_base_msat: 0,
4376                         fee_proportional_millionths: 0,
4377                         excess_data: Vec::new()
4378                 });
4379                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4380                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4381                         short_channel_id: 4,
4382                         timestamp: 2,
4383                         flags: 0,
4384                         cltv_expiry_delta: 0,
4385                         htlc_minimum_msat: 0,
4386                         htlc_maximum_msat: OptionalField::Present(20_000),
4387                         fee_base_msat: 0,
4388                         fee_proportional_millionths: 0,
4389                         excess_data: Vec::new()
4390                 });
4391
4392                 {
4393                         // Attempt to route more than available results in a failure.
4394                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4395                                         &our_id, &payment_params, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4396                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4397                         } else { panic!(); }
4398                 }
4399
4400                 {
4401                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4402                         // Our algorithm should provide us with these 3 paths.
4403                         let route = get_route(&our_id, &payment_params, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4404                         assert_eq!(route.paths.len(), 3);
4405                         let mut total_amount_paid_msat = 0;
4406                         for path in &route.paths {
4407                                 assert_eq!(path.len(), 2);
4408                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4409                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
4410                         }
4411                         assert_eq!(total_amount_paid_msat, 125_000);
4412                 }
4413
4414                 {
4415                         // Attempt to route without the last small cheap channel
4416                         let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4417                         assert_eq!(route.paths.len(), 2);
4418                         let mut total_amount_paid_msat = 0;
4419                         for path in &route.paths {
4420                                 assert_eq!(path.len(), 2);
4421                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4422                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
4423                         }
4424                         assert_eq!(total_amount_paid_msat, 90_000);
4425                 }
4426         }
4427
4428         #[test]
4429         fn min_criteria_consistency() {
4430                 // Test that we don't use an inconsistent metric between updating and walking nodes during
4431                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4432                 // was updated with a different criterion from the heap sorting, resulting in loops in
4433                 // calculated paths. We test for that specific case here.
4434
4435                 // We construct a network that looks like this:
4436                 //
4437                 //            node2 -1(3)2- node3
4438                 //              2          2
4439                 //               (2)     (4)
4440                 //                  1   1
4441                 //    node1 -1(5)2- node4 -1(1)2- node6
4442                 //    2
4443                 //   (6)
4444                 //        1
4445                 // our_node
4446                 //
4447                 // We create a loop on the side of our real path - our destination is node 6, with a
4448                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4449                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4450                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4451                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4452                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4453                 // "previous hop" being set to node 3, creating a loop in the path.
4454                 let secp_ctx = Secp256k1::new();
4455                 let logger = Arc::new(test_utils::TestLogger::new());
4456                 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4457                 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4458                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4459                 let scorer = test_utils::TestScorer::with_penalty(0);
4460                 let payment_params = PaymentParameters::from_node_id(nodes[6]);
4461
4462                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4463                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4464                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4465                         short_channel_id: 6,
4466                         timestamp: 1,
4467                         flags: 0,
4468                         cltv_expiry_delta: (6 << 4) | 0,
4469                         htlc_minimum_msat: 0,
4470                         htlc_maximum_msat: OptionalField::Absent,
4471                         fee_base_msat: 0,
4472                         fee_proportional_millionths: 0,
4473                         excess_data: Vec::new()
4474                 });
4475                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4476
4477                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4478                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4479                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4480                         short_channel_id: 5,
4481                         timestamp: 1,
4482                         flags: 0,
4483                         cltv_expiry_delta: (5 << 4) | 0,
4484                         htlc_minimum_msat: 0,
4485                         htlc_maximum_msat: OptionalField::Absent,
4486                         fee_base_msat: 100,
4487                         fee_proportional_millionths: 0,
4488                         excess_data: Vec::new()
4489                 });
4490                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4491
4492                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4493                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4494                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4495                         short_channel_id: 4,
4496                         timestamp: 1,
4497                         flags: 0,
4498                         cltv_expiry_delta: (4 << 4) | 0,
4499                         htlc_minimum_msat: 0,
4500                         htlc_maximum_msat: OptionalField::Absent,
4501                         fee_base_msat: 0,
4502                         fee_proportional_millionths: 0,
4503                         excess_data: Vec::new()
4504                 });
4505                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4506
4507                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4508                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4509                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4510                         short_channel_id: 3,
4511                         timestamp: 1,
4512                         flags: 0,
4513                         cltv_expiry_delta: (3 << 4) | 0,
4514                         htlc_minimum_msat: 0,
4515                         htlc_maximum_msat: OptionalField::Absent,
4516                         fee_base_msat: 0,
4517                         fee_proportional_millionths: 0,
4518                         excess_data: Vec::new()
4519                 });
4520                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4521
4522                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4523                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4524                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4525                         short_channel_id: 2,
4526                         timestamp: 1,
4527                         flags: 0,
4528                         cltv_expiry_delta: (2 << 4) | 0,
4529                         htlc_minimum_msat: 0,
4530                         htlc_maximum_msat: OptionalField::Absent,
4531                         fee_base_msat: 0,
4532                         fee_proportional_millionths: 0,
4533                         excess_data: Vec::new()
4534                 });
4535
4536                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4537                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4538                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4539                         short_channel_id: 1,
4540                         timestamp: 1,
4541                         flags: 0,
4542                         cltv_expiry_delta: (1 << 4) | 0,
4543                         htlc_minimum_msat: 100,
4544                         htlc_maximum_msat: OptionalField::Absent,
4545                         fee_base_msat: 0,
4546                         fee_proportional_millionths: 0,
4547                         excess_data: Vec::new()
4548                 });
4549                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4550
4551                 {
4552                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
4553                         let route = get_route(&our_id, &payment_params, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4554                         assert_eq!(route.paths.len(), 1);
4555                         assert_eq!(route.paths[0].len(), 3);
4556
4557                         assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4558                         assert_eq!(route.paths[0][0].short_channel_id, 6);
4559                         assert_eq!(route.paths[0][0].fee_msat, 100);
4560                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 4) | 0);
4561                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4562                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4563
4564                         assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4565                         assert_eq!(route.paths[0][1].short_channel_id, 5);
4566                         assert_eq!(route.paths[0][1].fee_msat, 0);
4567                         assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 4) | 0);
4568                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4569                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4570
4571                         assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4572                         assert_eq!(route.paths[0][2].short_channel_id, 1);
4573                         assert_eq!(route.paths[0][2].fee_msat, 10_000);
4574                         assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4575                         assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4576                         assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4577                 }
4578         }
4579
4580
4581         #[test]
4582         fn exact_fee_liquidity_limit() {
4583                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4584                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4585                 // we calculated fees on a higher value, resulting in us ignoring such paths.
4586                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4587                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4588                 let scorer = test_utils::TestScorer::with_penalty(0);
4589                 let payment_params = PaymentParameters::from_node_id(nodes[2]);
4590
4591                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4592                 // send.
4593                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4594                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4595                         short_channel_id: 2,
4596                         timestamp: 2,
4597                         flags: 0,
4598                         cltv_expiry_delta: 0,
4599                         htlc_minimum_msat: 0,
4600                         htlc_maximum_msat: OptionalField::Present(85_000),
4601                         fee_base_msat: 0,
4602                         fee_proportional_millionths: 0,
4603                         excess_data: Vec::new()
4604                 });
4605
4606                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4607                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4608                         short_channel_id: 12,
4609                         timestamp: 2,
4610                         flags: 0,
4611                         cltv_expiry_delta: (4 << 4) | 1,
4612                         htlc_minimum_msat: 0,
4613                         htlc_maximum_msat: OptionalField::Present(270_000),
4614                         fee_base_msat: 0,
4615                         fee_proportional_millionths: 1000000,
4616                         excess_data: Vec::new()
4617                 });
4618
4619                 {
4620                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4621                         // 200% fee charged channel 13 in the 1-to-2 direction.
4622                         let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4623                         assert_eq!(route.paths.len(), 1);
4624                         assert_eq!(route.paths[0].len(), 2);
4625
4626                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4627                         assert_eq!(route.paths[0][0].short_channel_id, 12);
4628                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4629                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4630                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4631                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4632
4633                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4634                         assert_eq!(route.paths[0][1].short_channel_id, 13);
4635                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
4636                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4637                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4638                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4639                 }
4640         }
4641
4642         #[test]
4643         fn htlc_max_reduction_below_min() {
4644                 // Test that if, while walking the graph, we reduce the value being sent to meet an
4645                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4646                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4647                 // resulting in us thinking there is no possible path, even if other paths exist.
4648                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4649                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4650                 let scorer = test_utils::TestScorer::with_penalty(0);
4651                 let payment_params = PaymentParameters::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4652
4653                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4654                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4655                 // then try to send 90_000.
4656                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4657                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4658                         short_channel_id: 2,
4659                         timestamp: 2,
4660                         flags: 0,
4661                         cltv_expiry_delta: 0,
4662                         htlc_minimum_msat: 0,
4663                         htlc_maximum_msat: OptionalField::Present(80_000),
4664                         fee_base_msat: 0,
4665                         fee_proportional_millionths: 0,
4666                         excess_data: Vec::new()
4667                 });
4668                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4669                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4670                         short_channel_id: 4,
4671                         timestamp: 2,
4672                         flags: 0,
4673                         cltv_expiry_delta: (4 << 4) | 1,
4674                         htlc_minimum_msat: 90_000,
4675                         htlc_maximum_msat: OptionalField::Absent,
4676                         fee_base_msat: 0,
4677                         fee_proportional_millionths: 0,
4678                         excess_data: Vec::new()
4679                 });
4680
4681                 {
4682                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4683                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4684                         // expensive) channels 12-13 path.
4685                         let route = get_route(&our_id, &payment_params, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4686                         assert_eq!(route.paths.len(), 1);
4687                         assert_eq!(route.paths[0].len(), 2);
4688
4689                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4690                         assert_eq!(route.paths[0][0].short_channel_id, 12);
4691                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4692                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 4) | 1);
4693                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4694                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4695
4696                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4697                         assert_eq!(route.paths[0][1].short_channel_id, 13);
4698                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
4699                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4700                         assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4701                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4702                 }
4703         }
4704
4705         #[test]
4706         fn multiple_direct_first_hops() {
4707                 // Previously we'd only ever considered one first hop path per counterparty.
4708                 // However, as we don't restrict users to one channel per peer, we really need to support
4709                 // looking at all first hop paths.
4710                 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4711                 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4712                 // route over multiple channels with the same first hop.
4713                 let secp_ctx = Secp256k1::new();
4714                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4715                 let logger = Arc::new(test_utils::TestLogger::new());
4716                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4717                 let scorer = test_utils::TestScorer::with_penalty(0);
4718                 let payment_params = PaymentParameters::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4719
4720                 {
4721                         let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4722                                 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4723                                 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4724                         ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4725                         assert_eq!(route.paths.len(), 1);
4726                         assert_eq!(route.paths[0].len(), 1);
4727
4728                         assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4729                         assert_eq!(route.paths[0][0].short_channel_id, 3);
4730                         assert_eq!(route.paths[0][0].fee_msat, 100_000);
4731                 }
4732                 {
4733                         let route = get_route(&our_id, &payment_params, &network_graph, Some(&[
4734                                 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4735                                 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4736                         ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4737                         assert_eq!(route.paths.len(), 2);
4738                         assert_eq!(route.paths[0].len(), 1);
4739                         assert_eq!(route.paths[1].len(), 1);
4740
4741                         assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4742                         assert_eq!(route.paths[0][0].short_channel_id, 3);
4743                         assert_eq!(route.paths[0][0].fee_msat, 50_000);
4744
4745                         assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4746                         assert_eq!(route.paths[1][0].short_channel_id, 2);
4747                         assert_eq!(route.paths[1][0].fee_msat, 50_000);
4748                 }
4749         }
4750
4751         #[test]
4752         fn prefers_shorter_route_with_higher_fees() {
4753                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4754                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4755                 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4756
4757                 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4758                 let scorer = test_utils::TestScorer::with_penalty(0);
4759                 let route = get_route(
4760                         &our_id, &payment_params, &network_graph, None, 100, 42,
4761                         Arc::clone(&logger), &scorer
4762                 ).unwrap();
4763                 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4764
4765                 assert_eq!(route.get_total_fees(), 100);
4766                 assert_eq!(route.get_total_amount(), 100);
4767                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4768
4769                 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4770                 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4771                 let scorer = test_utils::TestScorer::with_penalty(100);
4772                 let route = get_route(
4773                         &our_id, &payment_params, &network_graph, None, 100, 42,
4774                         Arc::clone(&logger), &scorer
4775                 ).unwrap();
4776                 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4777
4778                 assert_eq!(route.get_total_fees(), 300);
4779                 assert_eq!(route.get_total_amount(), 100);
4780                 assert_eq!(path, vec![2, 4, 7, 10]);
4781         }
4782
4783         struct BadChannelScorer {
4784                 short_channel_id: u64,
4785         }
4786
4787         #[cfg(c_bindings)]
4788         impl Writeable for BadChannelScorer {
4789                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4790         }
4791         impl Score for BadChannelScorer {
4792                 fn channel_penalty_msat(&self, short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4793                         if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4794                 }
4795
4796                 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4797                 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4798         }
4799
4800         struct BadNodeScorer {
4801                 node_id: NodeId,
4802         }
4803
4804         #[cfg(c_bindings)]
4805         impl Writeable for BadNodeScorer {
4806                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), ::io::Error> { unimplemented!() }
4807         }
4808
4809         impl Score for BadNodeScorer {
4810                 fn channel_penalty_msat(&self, _short_channel_id: u64, _send_amt: u64, _capacity_msat: u64, _source: &NodeId, target: &NodeId) -> u64 {
4811                         if *target == self.node_id { u64::max_value() } else { 0 }
4812                 }
4813
4814                 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4815                 fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
4816         }
4817
4818         #[test]
4819         fn avoids_routing_through_bad_channels_and_nodes() {
4820                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4821                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4822                 let payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4823
4824                 // A path to nodes[6] exists when no penalties are applied to any channel.
4825                 let scorer = test_utils::TestScorer::with_penalty(0);
4826                 let route = get_route(
4827                         &our_id, &payment_params, &network_graph, None, 100, 42,
4828                         Arc::clone(&logger), &scorer
4829                 ).unwrap();
4830                 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4831
4832                 assert_eq!(route.get_total_fees(), 100);
4833                 assert_eq!(route.get_total_amount(), 100);
4834                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4835
4836                 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4837                 let scorer = BadChannelScorer { short_channel_id: 6 };
4838                 let route = get_route(
4839                         &our_id, &payment_params, &network_graph, None, 100, 42,
4840                         Arc::clone(&logger), &scorer
4841                 ).unwrap();
4842                 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4843
4844                 assert_eq!(route.get_total_fees(), 300);
4845                 assert_eq!(route.get_total_amount(), 100);
4846                 assert_eq!(path, vec![2, 4, 7, 10]);
4847
4848                 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4849                 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4850                 match get_route(
4851                         &our_id, &payment_params, &network_graph, None, 100, 42,
4852                         Arc::clone(&logger), &scorer
4853                 ) {
4854                         Err(LightningError { err, .. } ) => {
4855                                 assert_eq!(err, "Failed to find a path to the given destination");
4856                         },
4857                         Ok(_) => panic!("Expected error"),
4858                 }
4859         }
4860
4861         #[test]
4862         fn total_fees_single_path() {
4863                 let route = Route {
4864                         paths: vec![vec![
4865                                 RouteHop {
4866                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4867                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4868                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4869                                 },
4870                                 RouteHop {
4871                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4872                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4873                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4874                                 },
4875                                 RouteHop {
4876                                         pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4877                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4878                                         short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4879                                 },
4880                         ]],
4881                         payment_params: None,
4882                 };
4883
4884                 assert_eq!(route.get_total_fees(), 250);
4885                 assert_eq!(route.get_total_amount(), 225);
4886         }
4887
4888         #[test]
4889         fn total_fees_multi_path() {
4890                 let route = Route {
4891                         paths: vec![vec![
4892                                 RouteHop {
4893                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4894                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4895                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4896                                 },
4897                                 RouteHop {
4898                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4899                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4900                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4901                                 },
4902                         ],vec![
4903                                 RouteHop {
4904                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4905                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4906                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4907                                 },
4908                                 RouteHop {
4909                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4910                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4911                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4912                                 },
4913                         ]],
4914                         payment_params: None,
4915                 };
4916
4917                 assert_eq!(route.get_total_fees(), 200);
4918                 assert_eq!(route.get_total_amount(), 300);
4919         }
4920
4921         #[test]
4922         fn total_empty_route_no_panic() {
4923                 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4924                 // would both panic if the route was completely empty. We test to ensure they return 0
4925                 // here, even though its somewhat nonsensical as a route.
4926                 let route = Route { paths: Vec::new(), payment_params: None };
4927
4928                 assert_eq!(route.get_total_fees(), 0);
4929                 assert_eq!(route.get_total_amount(), 0);
4930         }
4931
4932         #[test]
4933         fn limits_total_cltv_delta() {
4934                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4935                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4936
4937                 let scorer = test_utils::TestScorer::with_penalty(0);
4938
4939                 // Make sure that generally there is at least one route available
4940                 let feasible_max_total_cltv_delta = 1008;
4941                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4942                         .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
4943                 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
4944                 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4945                 assert_ne!(path.len(), 0);
4946
4947                 // But not if we exclude all paths on the basis of their accumulated CLTV delta
4948                 let fail_max_total_cltv_delta = 23;
4949                 let fail_payment_params = PaymentParameters::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes))
4950                         .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
4951                 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer)
4952                 {
4953                         Err(LightningError { err, .. } ) => {
4954                                 assert_eq!(err, "Failed to find a path to the given destination");
4955                         },
4956                         Ok(_) => panic!("Expected error"),
4957                 }
4958         }
4959
4960         #[cfg(not(feature = "no-std"))]
4961         pub(super) fn random_init_seed() -> u64 {
4962                 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4963                 use core::hash::{BuildHasher, Hasher};
4964                 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4965                 println!("Using seed of {}", seed);
4966                 seed
4967         }
4968         #[cfg(not(feature = "no-std"))]
4969         use util::ser::Readable;
4970
4971         #[test]
4972         #[cfg(not(feature = "no-std"))]
4973         fn generate_routes() {
4974                 let mut d = match super::test_utils::get_route_file() {
4975                         Ok(f) => f,
4976                         Err(e) => {
4977                                 eprintln!("{}", e);
4978                                 return;
4979                         },
4980                 };
4981                 let graph = NetworkGraph::read(&mut d).unwrap();
4982
4983                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4984                 let mut seed = random_init_seed() as usize;
4985                 let nodes = graph.read_only().nodes().clone();
4986                 'load_endpoints: for _ in 0..10 {
4987                         loop {
4988                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4989                                 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4990                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4991                                 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4992                                 let payment_params = PaymentParameters::from_node_id(dst);
4993                                 let amt = seed as u64 % 200_000_000;
4994                                 let params = ProbabilisticScoringParameters::default();
4995                                 let scorer = ProbabilisticScorer::new(params, &graph);
4996                                 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4997                                         continue 'load_endpoints;
4998                                 }
4999                         }
5000                 }
5001         }
5002
5003         #[test]
5004         #[cfg(not(feature = "no-std"))]
5005         fn generate_routes_mpp() {
5006                 let mut d = match super::test_utils::get_route_file() {
5007                         Ok(f) => f,
5008                         Err(e) => {
5009                                 eprintln!("{}", e);
5010                                 return;
5011                         },
5012                 };
5013                 let graph = NetworkGraph::read(&mut d).unwrap();
5014
5015                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5016                 let mut seed = random_init_seed() as usize;
5017                 let nodes = graph.read_only().nodes().clone();
5018                 'load_endpoints: for _ in 0..10 {
5019                         loop {
5020                                 seed = seed.overflowing_mul(0xdeadbeef).0;
5021                                 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5022                                 seed = seed.overflowing_mul(0xdeadbeef).0;
5023                                 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5024                                 let payment_params = PaymentParameters::from_node_id(dst).with_features(InvoiceFeatures::known());
5025                                 let amt = seed as u64 % 200_000_000;
5026                                 let params = ProbabilisticScoringParameters::default();
5027                                 let scorer = ProbabilisticScorer::new(params, &graph);
5028                                 if get_route(src, &payment_params, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
5029                                         continue 'load_endpoints;
5030                                 }
5031                         }
5032                 }
5033         }
5034 }
5035
5036 #[cfg(all(test, not(feature = "no-std")))]
5037 pub(crate) mod test_utils {
5038         use std::fs::File;
5039         /// Tries to open a network graph file, or panics with a URL to fetch it.
5040         pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
5041                 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
5042                         .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
5043                         .or_else(|_| { // Fall back to guessing based on the binary location
5044                                 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
5045                                 let mut path = std::env::current_exe().unwrap();
5046                                 path.pop(); // lightning-...
5047                                 path.pop(); // deps
5048                                 path.pop(); // debug
5049                                 path.pop(); // target
5050                                 path.push("lightning");
5051                                 path.push("net_graph-2021-05-31.bin");
5052                                 eprintln!("{}", path.to_str().unwrap());
5053                                 File::open(path)
5054                         })
5055                 .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");
5056                 #[cfg(require_route_graph_test)]
5057                 return Ok(res.unwrap());
5058                 #[cfg(not(require_route_graph_test))]
5059                 return res;
5060         }
5061 }
5062
5063 #[cfg(all(test, feature = "_bench_unstable", not(feature = "no-std")))]
5064 mod benches {
5065         use super::*;
5066         use bitcoin::hashes::Hash;
5067         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
5068         use chain::transaction::OutPoint;
5069         use ln::channelmanager::{ChannelCounterparty, ChannelDetails};
5070         use ln::features::{InitFeatures, InvoiceFeatures};
5071         use routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringParameters, Scorer};
5072         use util::logger::{Logger, Record};
5073
5074         use test::Bencher;
5075
5076         struct DummyLogger {}
5077         impl Logger for DummyLogger {
5078                 fn log(&self, _record: &Record) {}
5079         }
5080
5081         fn read_network_graph() -> NetworkGraph {
5082                 let mut d = test_utils::get_route_file().unwrap();
5083                 NetworkGraph::read(&mut d).unwrap()
5084         }
5085
5086         fn payer_pubkey() -> PublicKey {
5087                 let secp_ctx = Secp256k1::new();
5088                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
5089         }
5090
5091         #[inline]
5092         fn first_hop(node_id: PublicKey) -> ChannelDetails {
5093                 ChannelDetails {
5094                         channel_id: [0; 32],
5095                         counterparty: ChannelCounterparty {
5096                                 features: InitFeatures::known(),
5097                                 node_id,
5098                                 unspendable_punishment_reserve: 0,
5099                                 forwarding_info: None,
5100                         },
5101                         funding_txo: Some(OutPoint {
5102                                 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
5103                         }),
5104                         short_channel_id: Some(1),
5105                         inbound_scid_alias: None,
5106                         channel_value_satoshis: 10_000_000,
5107                         user_channel_id: 0,
5108                         balance_msat: 10_000_000,
5109                         outbound_capacity_msat: 10_000_000,
5110                         inbound_capacity_msat: 0,
5111                         unspendable_punishment_reserve: None,
5112                         confirmations_required: None,
5113                         force_close_spend_delay: None,
5114                         is_outbound: true,
5115                         is_funding_locked: true,
5116                         is_usable: true,
5117                         is_public: true,
5118                 }
5119         }
5120
5121         #[bench]
5122         fn generate_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5123                 let network_graph = read_network_graph();
5124                 let scorer = FixedPenaltyScorer::with_penalty(0);
5125                 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5126         }
5127
5128         #[bench]
5129         fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Bencher) {
5130                 let network_graph = read_network_graph();
5131                 let scorer = FixedPenaltyScorer::with_penalty(0);
5132                 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5133         }
5134
5135         #[bench]
5136         fn generate_routes_with_default_scorer(bench: &mut Bencher) {
5137                 let network_graph = read_network_graph();
5138                 let scorer = Scorer::default();
5139                 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5140         }
5141
5142         #[bench]
5143         fn generate_mpp_routes_with_default_scorer(bench: &mut Bencher) {
5144                 let network_graph = read_network_graph();
5145                 let scorer = Scorer::default();
5146                 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5147         }
5148
5149         #[bench]
5150         fn generate_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5151                 let network_graph = read_network_graph();
5152                 let params = ProbabilisticScoringParameters::default();
5153                 let scorer = ProbabilisticScorer::new(params, &network_graph);
5154                 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::empty());
5155         }
5156
5157         #[bench]
5158         fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Bencher) {
5159                 let network_graph = read_network_graph();
5160                 let params = ProbabilisticScoringParameters::default();
5161                 let scorer = ProbabilisticScorer::new(params, &network_graph);
5162                 generate_routes(bench, &network_graph, scorer, InvoiceFeatures::known());
5163         }
5164
5165         fn generate_routes<S: Score>(
5166                 bench: &mut Bencher, graph: &NetworkGraph, mut scorer: S, features: InvoiceFeatures
5167         ) {
5168                 let nodes = graph.read_only().nodes().clone();
5169                 let payer = payer_pubkey();
5170
5171                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
5172                 let mut routes = Vec::new();
5173                 let mut route_endpoints = Vec::new();
5174                 let mut seed: usize = 0xdeadbeef;
5175                 'load_endpoints: for _ in 0..100 {
5176                         loop {
5177                                 seed *= 0xdeadbeef;
5178                                 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5179                                 seed *= 0xdeadbeef;
5180                                 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
5181                                 let params = PaymentParameters::from_node_id(dst).with_features(features.clone());
5182                                 let first_hop = first_hop(src);
5183                                 let amt = seed as u64 % 1_000_000;
5184                                 if let Ok(route) = get_route(&payer, &params, &graph, Some(&[&first_hop]), amt, 42, &DummyLogger{}, &scorer) {
5185                                         routes.push(route);
5186                                         route_endpoints.push((first_hop, params, amt));
5187                                         continue 'load_endpoints;
5188                                 }
5189                         }
5190                 }
5191
5192                 // ...and seed the scorer with success and failure data...
5193                 for route in routes {
5194                         let amount = route.get_total_amount();
5195                         if amount < 250_000 {
5196                                 for path in route.paths {
5197                                         scorer.payment_path_successful(&path.iter().collect::<Vec<_>>());
5198                                 }
5199                         } else if amount > 750_000 {
5200                                 for path in route.paths {
5201                                         let short_channel_id = path[path.len() / 2].short_channel_id;
5202                                         scorer.payment_path_failed(&path.iter().collect::<Vec<_>>(), short_channel_id);
5203                                 }
5204                         }
5205                 }
5206
5207                 // ...then benchmark finding paths between the nodes we learned.
5208                 let mut idx = 0;
5209                 bench.iter(|| {
5210                         let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
5211                         assert!(get_route(&payer, params, &graph, Some(&[first_hop]), *amt, 42, &DummyLogger{}, &scorer).is_ok());
5212                         idx += 1;
5213                 });
5214         }
5215 }