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