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