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