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