Add `(C-not exported)` tag to a `Payee` modifier with move semantics
[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;
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: routing::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: routing::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. Prooceed 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) then
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 bookkeeped_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 channel *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 = bookkeeped_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 path
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
896                                                                 .checked_add(scorer.channel_penalty_msat($chan_id.clone(), &$src_node_id, &$dest_node_id))
897                                                                 .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                 // bookkeeped_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                                         let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
1117                                                 0 => 999,
1118                                                 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
1119                                         }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
1120
1121                                         let src_node_id = NodeId::from_pubkey(&hop.src_node_id);
1122                                         let dest_node_id = NodeId::from_pubkey(&prev_hop_id);
1123                                         aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1124                                                 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, &src_node_id, &dest_node_id))
1125                                                 .unwrap_or_else(|| u64::max_value());
1126
1127                                         // We assume that the recipient only included route hints for routes which had
1128                                         // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
1129                                         // invoices where the invoice does not specify value this may not be the case, but
1130                                         // better to include the hints than not.
1131                                         if !add_entry!(hop.short_channel_id, src_node_id, dest_node_id, directional_info, reqd_channel_cap, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat) {
1132                                                 // If this hop was not used then there is no use checking the preceding hops
1133                                                 // in the RouteHint. We can break by just searching for a direct channel between
1134                                                 // last checked hop and first_hop_targets
1135                                                 hop_used = false;
1136                                         }
1137
1138                                         // Searching for a direct channel between last checked hop and first_hop_targets
1139                                         if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1140                                                 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1141                                                         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);
1142                                                 }
1143                                         }
1144
1145                                         if !hop_used {
1146                                                 break;
1147                                         }
1148
1149                                         // In the next values of the iterator, the aggregate fees already reflects
1150                                         // the sum of value sent from payer (final_value_msat) and routing fees
1151                                         // for the last node in the RouteHint. We need to just add the fees to
1152                                         // route through the current node so that the preceeding node (next iteration)
1153                                         // can use it.
1154                                         let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1155                                                 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1156                                         aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1157
1158                                         let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1159                                         let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1160                                                 .checked_add(hop_htlc_minimum_msat_inc);
1161                                         aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1162
1163                                         if idx == route.0.len() - 1 {
1164                                                 // The last hop in this iterator is the first hop in
1165                                                 // overall RouteHint.
1166                                                 // If this hop connects to a node with which we have a direct channel,
1167                                                 // ignore the network graph and, if the last hop was added, add our
1168                                                 // direct channel to the candidate set.
1169                                                 //
1170                                                 // Note that we *must* check if the last hop was added as `add_entry`
1171                                                 // always assumes that the third argument is a node to which we have a
1172                                                 // path.
1173                                                 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1174                                                         for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1175                                                                 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);
1176                                                         }
1177                                                 }
1178                                         }
1179                                 }
1180                         }
1181                 }
1182
1183                 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1184
1185                 // At this point, targets are filled with the data from first and
1186                 // last hops communicated by the caller, and the payment receiver.
1187                 let mut found_new_path = false;
1188
1189                 // Step (3).
1190                 // If this loop terminates due the exhaustion of targets, two situations are possible:
1191                 // - not enough outgoing liquidity:
1192                 //   0 < already_collected_value_msat < final_value_msat
1193                 // - enough outgoing liquidity:
1194                 //   final_value_msat <= already_collected_value_msat < recommended_value_msat
1195                 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1196                 // paths_collection will be stopped because found_new_path==false.
1197                 // This is not necessarily a routing failure.
1198                 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1199
1200                         // Since we're going payee-to-payer, hitting our node as a target means we should stop
1201                         // traversing the graph and arrange the path out of what we found.
1202                         if node_id == our_node_id {
1203                                 let mut new_entry = dist.remove(&our_node_id).unwrap();
1204                                 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1205
1206                                 'path_walk: loop {
1207                                         let mut features_set = false;
1208                                         if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1209                                                 for (scid, _, _, ref features) in first_channels {
1210                                                         if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1211                                                                 ordered_hops.last_mut().unwrap().1 = features.clone();
1212                                                                 features_set = true;
1213                                                                 break;
1214                                                         }
1215                                                 }
1216                                         }
1217                                         if !features_set {
1218                                                 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1219                                                         if let Some(node_info) = node.announcement_info.as_ref() {
1220                                                                 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1221                                                         } else {
1222                                                                 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1223                                                         }
1224                                                 } else {
1225                                                         // We should be able to fill in features for everything except the last
1226                                                         // hop, if the last hop was provided via a BOLT 11 invoice (though we
1227                                                         // should be able to extend it further as BOLT 11 does have feature
1228                                                         // flags for the last hop node itself).
1229                                                         assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1230                                                 }
1231                                         }
1232
1233                                         // Means we succesfully traversed from the payer to the payee, now
1234                                         // save this path for the payment route. Also, update the liquidity
1235                                         // remaining on the used hops, so that we take them into account
1236                                         // while looking for more paths.
1237                                         if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1238                                                 break 'path_walk;
1239                                         }
1240
1241                                         new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1242                                                 Some(payment_hop) => payment_hop,
1243                                                 // We can't arrive at None because, if we ever add an entry to targets,
1244                                                 // we also fill in the entry in dist (see add_entry!).
1245                                                 None => unreachable!(),
1246                                         };
1247                                         // We "propagate" the fees one hop backward (topologically) here,
1248                                         // so that fees paid for a HTLC forwarding on the current channel are
1249                                         // associated with the previous channel (where they will be subtracted).
1250                                         ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1251                                         ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1252                                         ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1253                                 }
1254                                 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1255                                 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1256                                 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv_expiry_delta;
1257
1258                                 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1259                                         ordered_hops.len(), value_contribution_msat, ordered_hops);
1260
1261                                 let mut payment_path = PaymentPath {hops: ordered_hops};
1262
1263                                 // We could have possibly constructed a slightly inconsistent path: since we reduce
1264                                 // value being transferred along the way, we could have violated htlc_minimum_msat
1265                                 // on some channels we already passed (assuming dest->source direction). Here, we
1266                                 // recompute the fees again, so that if that's the case, we match the currently
1267                                 // underpaid htlc_minimum_msat with fees.
1268                                 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1269
1270                                 // Since a path allows to transfer as much value as
1271                                 // the smallest channel it has ("bottleneck"), we should recompute
1272                                 // the fees so sender HTLC don't overpay fees when traversing
1273                                 // larger channels than the bottleneck. This may happen because
1274                                 // when we were selecting those channels we were not aware how much value
1275                                 // this path will transfer, and the relative fee for them
1276                                 // might have been computed considering a larger value.
1277                                 // Remember that we used these channels so that we don't rely
1278                                 // on the same liquidity in future paths.
1279                                 let mut prevented_redundant_path_selection = false;
1280                                 for (payment_hop, _) in payment_path.hops.iter() {
1281                                         let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1282                                         let mut spent_on_hop_msat = value_contribution_msat;
1283                                         let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1284                                         spent_on_hop_msat += next_hops_fee_msat;
1285                                         if spent_on_hop_msat == *channel_liquidity_available_msat {
1286                                                 // If this path used all of this channel's available liquidity, we know
1287                                                 // this path will not be selected again in the next loop iteration.
1288                                                 prevented_redundant_path_selection = true;
1289                                         }
1290                                         *channel_liquidity_available_msat -= spent_on_hop_msat;
1291                                 }
1292                                 if !prevented_redundant_path_selection {
1293                                         // If we weren't capped by hitting a liquidity limit on a channel in the path,
1294                                         // we'll probably end up picking the same path again on the next iteration.
1295                                         // Decrease the available liquidity of a hop in the middle of the path.
1296                                         let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1297                                         log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1298                                         let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1299                                         *victim_liquidity = 0;
1300                                 }
1301
1302                                 // Track the total amount all our collected paths allow to send so that we:
1303                                 // - know when to stop looking for more paths
1304                                 // - know which of the hops are useless considering how much more sats we need
1305                                 //   (contributes_sufficient_value)
1306                                 already_collected_value_msat += value_contribution_msat;
1307
1308                                 payment_paths.push(payment_path);
1309                                 found_new_path = true;
1310                                 break 'path_construction;
1311                         }
1312
1313                         // If we found a path back to the payee, we shouldn't try to process it again. This is
1314                         // the equivalent of the `elem.was_processed` check in
1315                         // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1316                         if node_id == payee_node_id { continue 'path_construction; }
1317
1318                         // Otherwise, since the current target node is not us,
1319                         // keep "unrolling" the payment graph from payee to payer by
1320                         // finding a way to reach the current target from the payer side.
1321                         match network_nodes.get(&node_id) {
1322                                 None => {},
1323                                 Some(node) => {
1324                                         add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1325                                 },
1326                         }
1327                 }
1328
1329                 if !allow_mpp {
1330                         // If we don't support MPP, no use trying to gather more value ever.
1331                         break 'paths_collection;
1332                 }
1333
1334                 // Step (4).
1335                 // Stop either when the recommended value is reached or if no new path was found in this
1336                 // iteration.
1337                 // In the latter case, making another path finding attempt won't help,
1338                 // because we deterministically terminated the search due to low liquidity.
1339                 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1340                         log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1341                                 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1342                         break 'paths_collection;
1343                 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1344                         // Further, if this was our first walk of the graph, and we weren't limited by an
1345                         // htlc_minimum_msat, return immediately because this path should suffice. If we were
1346                         // limited by an htlc_minimum_msat value, find another path with a higher value,
1347                         // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1348                         // still keeping a lower total fee than this path.
1349                         if !hit_minimum_limit {
1350                                 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1351                                 break 'paths_collection;
1352                         }
1353                         log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1354                         path_value_msat = recommended_value_msat;
1355                 }
1356         }
1357
1358         // Step (5).
1359         if payment_paths.len() == 0 {
1360                 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1361         }
1362
1363         if already_collected_value_msat < final_value_msat {
1364                 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1365         }
1366
1367         // Sort by total fees and take the best paths.
1368         payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1369         if payment_paths.len() > 50 {
1370                 payment_paths.truncate(50);
1371         }
1372
1373         // Draw multiple sufficient routes by randomly combining the selected paths.
1374         let mut drawn_routes = Vec::new();
1375         for i in 0..payment_paths.len() {
1376                 let mut cur_route = Vec::<PaymentPath>::new();
1377                 let mut aggregate_route_value_msat = 0;
1378
1379                 // Step (6).
1380                 // TODO: real random shuffle
1381                 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1382                 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1383
1384                 // Step (7).
1385                 for payment_path in cur_payment_paths {
1386                         cur_route.push(payment_path.clone());
1387                         aggregate_route_value_msat += payment_path.get_value_msat();
1388                         if aggregate_route_value_msat > final_value_msat {
1389                                 // Last path likely overpaid. Substract it from the most expensive
1390                                 // (in terms of proportional fee) path in this route and recompute fees.
1391                                 // This might be not the most economically efficient way, but fewer paths
1392                                 // also makes routing more reliable.
1393                                 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1394
1395                                 // First, drop some expensive low-value paths entirely if possible.
1396                                 // Sort by value so that we drop many really-low values first, since
1397                                 // fewer paths is better: the payment is less likely to fail.
1398                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1399                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1400                                 cur_route.sort_by_key(|path| path.get_value_msat());
1401                                 // We should make sure that at least 1 path left.
1402                                 let mut paths_left = cur_route.len();
1403                                 cur_route.retain(|path| {
1404                                         if paths_left == 1 {
1405                                                 return true
1406                                         }
1407                                         let mut keep = true;
1408                                         let path_value_msat = path.get_value_msat();
1409                                         if path_value_msat <= overpaid_value_msat {
1410                                                 keep = false;
1411                                                 overpaid_value_msat -= path_value_msat;
1412                                                 paths_left -= 1;
1413                                         }
1414                                         keep
1415                                 });
1416
1417                                 if overpaid_value_msat == 0 {
1418                                         break;
1419                                 }
1420
1421                                 assert!(cur_route.len() > 0);
1422
1423                                 // Step (8).
1424                                 // Now, substract the overpaid value from the most-expensive path.
1425                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1426                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1427                                 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1428                                 let expensive_payment_path = cur_route.first_mut().unwrap();
1429                                 // We already dropped all the small channels above, meaning all the
1430                                 // remaining channels are larger than remaining overpaid_value_msat.
1431                                 // Thus, this can't be negative.
1432                                 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1433                                 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1434                                 break;
1435                         }
1436                 }
1437                 drawn_routes.push(cur_route);
1438         }
1439
1440         // Step (9).
1441         // Select the best route by lowest total fee.
1442         drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1443         let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1444         for payment_path in drawn_routes.first().unwrap() {
1445                 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1446                         Ok(RouteHop {
1447                                 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)})?,
1448                                 node_features: node_features.clone(),
1449                                 short_channel_id: payment_hop.short_channel_id,
1450                                 channel_features: payment_hop.channel_features.clone(),
1451                                 fee_msat: payment_hop.fee_msat,
1452                                 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1453                         })
1454                 }).collect());
1455         }
1456
1457         if let Some(features) = &payee.features {
1458                 for path in selected_paths.iter_mut() {
1459                         if let Ok(route_hop) = path.last_mut().unwrap() {
1460                                 route_hop.node_features = features.to_context();
1461                         }
1462                 }
1463         }
1464
1465         let route = Route {
1466                 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1467                 payee: Some(payee.clone()),
1468         };
1469         log_info!(logger, "Got route to {}: {}", payee.pubkey, log_route!(route));
1470         Ok(route)
1471 }
1472
1473 #[cfg(test)]
1474 mod tests {
1475         use routing;
1476         use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1477         use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1478         use chain::transaction::OutPoint;
1479         use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1480         use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1481            NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1482         use ln::channelmanager;
1483         use util::test_utils;
1484         use util::ser::Writeable;
1485
1486         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1487         use bitcoin::hashes::Hash;
1488         use bitcoin::network::constants::Network;
1489         use bitcoin::blockdata::constants::genesis_block;
1490         use bitcoin::blockdata::script::Builder;
1491         use bitcoin::blockdata::opcodes;
1492         use bitcoin::blockdata::transaction::TxOut;
1493
1494         use hex;
1495
1496         use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1497         use bitcoin::secp256k1::{Secp256k1, All};
1498
1499         use prelude::*;
1500         use sync::{self, Arc};
1501
1502         fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1503                         features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1504                 channelmanager::ChannelDetails {
1505                         channel_id: [0; 32],
1506                         counterparty: channelmanager::ChannelCounterparty {
1507                                 features,
1508                                 node_id,
1509                                 unspendable_punishment_reserve: 0,
1510                                 forwarding_info: None,
1511                         },
1512                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1513                         short_channel_id,
1514                         channel_value_satoshis: 0,
1515                         user_channel_id: 0,
1516                         outbound_capacity_msat,
1517                         inbound_capacity_msat: 42,
1518                         unspendable_punishment_reserve: None,
1519                         confirmations_required: None,
1520                         force_close_spend_delay: None,
1521                         is_outbound: true, is_funding_locked: true,
1522                         is_usable: true, is_public: true,
1523                 }
1524         }
1525
1526         // Using the same keys for LN and BTC ids
1527         fn add_channel(
1528                 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1529                 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1530         ) {
1531                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1532                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1533
1534                 let unsigned_announcement = UnsignedChannelAnnouncement {
1535                         features,
1536                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1537                         short_channel_id,
1538                         node_id_1,
1539                         node_id_2,
1540                         bitcoin_key_1: node_id_1,
1541                         bitcoin_key_2: node_id_2,
1542                         excess_data: Vec::new(),
1543                 };
1544
1545                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1546                 let valid_announcement = ChannelAnnouncement {
1547                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1548                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1549                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1550                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1551                         contents: unsigned_announcement.clone(),
1552                 };
1553                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1554                         Ok(res) => assert!(res),
1555                         _ => panic!()
1556                 };
1557         }
1558
1559         fn update_channel(
1560                 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1561                 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1562         ) {
1563                 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1564                 let valid_channel_update = ChannelUpdate {
1565                         signature: secp_ctx.sign(&msghash, node_privkey),
1566                         contents: update.clone()
1567                 };
1568
1569                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1570                         Ok(res) => assert!(res),
1571                         Err(_) => panic!()
1572                 };
1573         }
1574
1575         fn add_or_update_node(
1576                 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1577                 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1578         ) {
1579                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1580                 let unsigned_announcement = UnsignedNodeAnnouncement {
1581                         features,
1582                         timestamp,
1583                         node_id,
1584                         rgb: [0; 3],
1585                         alias: [0; 32],
1586                         addresses: Vec::new(),
1587                         excess_address_data: Vec::new(),
1588                         excess_data: Vec::new(),
1589                 };
1590                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1591                 let valid_announcement = NodeAnnouncement {
1592                         signature: secp_ctx.sign(&msghash, node_privkey),
1593                         contents: unsigned_announcement.clone()
1594                 };
1595
1596                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1597                         Ok(_) => (),
1598                         Err(_) => panic!()
1599                 };
1600         }
1601
1602         fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1603                 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1604                         SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1605                 }).collect();
1606
1607                 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1608
1609                 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1610                 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1611
1612                 (our_privkey, our_id, privkeys, pubkeys)
1613         }
1614
1615         fn id_to_feature_flags(id: u8) -> Vec<u8> {
1616                 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1617                 // test for it later.
1618                 let idx = (id - 1) * 2 + 1;
1619                 if idx > 8*3 {
1620                         vec![1 << (idx - 8*3), 0, 0, 0]
1621                 } else if idx > 8*2 {
1622                         vec![1 << (idx - 8*2), 0, 0]
1623                 } else if idx > 8*1 {
1624                         vec![1 << (idx - 8*1), 0]
1625                 } else {
1626                         vec![1 << idx]
1627                 }
1628         }
1629
1630         fn build_graph() -> (
1631                 Secp256k1<All>,
1632                 sync::Arc<NetworkGraph>,
1633                 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1634                 sync::Arc<test_utils::TestChainSource>,
1635                 sync::Arc<test_utils::TestLogger>,
1636         ) {
1637                 let secp_ctx = Secp256k1::new();
1638                 let logger = Arc::new(test_utils::TestLogger::new());
1639                 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1640                 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1641                 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1642                 // Build network from our_id to node6:
1643                 //
1644                 //        -1(1)2-  node0  -1(3)2-
1645                 //       /                       \
1646                 // our_id -1(12)2- node7 -1(13)2--- node2
1647                 //       \                       /
1648                 //        -1(2)2-  node1  -1(4)2-
1649                 //
1650                 //
1651                 // chan1  1-to-2: disabled
1652                 // chan1  2-to-1: enabled, 0 fee
1653                 //
1654                 // chan2  1-to-2: enabled, ignored fee
1655                 // chan2  2-to-1: enabled, 0 fee
1656                 //
1657                 // chan3  1-to-2: enabled, 0 fee
1658                 // chan3  2-to-1: enabled, 100 msat fee
1659                 //
1660                 // chan4  1-to-2: enabled, 100% fee
1661                 // chan4  2-to-1: enabled, 0 fee
1662                 //
1663                 // chan12 1-to-2: enabled, ignored fee
1664                 // chan12 2-to-1: enabled, 0 fee
1665                 //
1666                 // chan13 1-to-2: enabled, 200% fee
1667                 // chan13 2-to-1: enabled, 0 fee
1668                 //
1669                 //
1670                 //       -1(5)2- node3 -1(8)2--
1671                 //       |         2          |
1672                 //       |       (11)         |
1673                 //      /          1           \
1674                 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1675                 //      \                      /
1676                 //       -1(7)2- node5 -1(10)2-
1677                 //
1678                 // Channels 5, 8, 9 and 10 are private channels.
1679                 //
1680                 // chan5  1-to-2: enabled, 100 msat fee
1681                 // chan5  2-to-1: enabled, 0 fee
1682                 //
1683                 // chan6  1-to-2: enabled, 0 fee
1684                 // chan6  2-to-1: enabled, 0 fee
1685                 //
1686                 // chan7  1-to-2: enabled, 100% fee
1687                 // chan7  2-to-1: enabled, 0 fee
1688                 //
1689                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
1690                 // chan8  2-to-1: enabled, 0 fee
1691                 //
1692                 // chan9  1-to-2: enabled, 1001 msat fee
1693                 // chan9  2-to-1: enabled, 0 fee
1694                 //
1695                 // chan10 1-to-2: enabled, 0 fee
1696                 // chan10 2-to-1: enabled, 0 fee
1697                 //
1698                 // chan11 1-to-2: enabled, 0 fee
1699                 // chan11 2-to-1: enabled, 0 fee
1700
1701                 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1702
1703                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1704                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1705                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1706                         short_channel_id: 1,
1707                         timestamp: 1,
1708                         flags: 1,
1709                         cltv_expiry_delta: 0,
1710                         htlc_minimum_msat: 0,
1711                         htlc_maximum_msat: OptionalField::Absent,
1712                         fee_base_msat: 0,
1713                         fee_proportional_millionths: 0,
1714                         excess_data: Vec::new()
1715                 });
1716
1717                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1718
1719                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1720                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1721                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1722                         short_channel_id: 2,
1723                         timestamp: 1,
1724                         flags: 0,
1725                         cltv_expiry_delta: u16::max_value(),
1726                         htlc_minimum_msat: 0,
1727                         htlc_maximum_msat: OptionalField::Absent,
1728                         fee_base_msat: u32::max_value(),
1729                         fee_proportional_millionths: u32::max_value(),
1730                         excess_data: Vec::new()
1731                 });
1732                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1733                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1734                         short_channel_id: 2,
1735                         timestamp: 1,
1736                         flags: 1,
1737                         cltv_expiry_delta: 0,
1738                         htlc_minimum_msat: 0,
1739                         htlc_maximum_msat: OptionalField::Absent,
1740                         fee_base_msat: 0,
1741                         fee_proportional_millionths: 0,
1742                         excess_data: Vec::new()
1743                 });
1744
1745                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1746
1747                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1748                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1749                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1750                         short_channel_id: 12,
1751                         timestamp: 1,
1752                         flags: 0,
1753                         cltv_expiry_delta: u16::max_value(),
1754                         htlc_minimum_msat: 0,
1755                         htlc_maximum_msat: OptionalField::Absent,
1756                         fee_base_msat: u32::max_value(),
1757                         fee_proportional_millionths: u32::max_value(),
1758                         excess_data: Vec::new()
1759                 });
1760                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1761                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1762                         short_channel_id: 12,
1763                         timestamp: 1,
1764                         flags: 1,
1765                         cltv_expiry_delta: 0,
1766                         htlc_minimum_msat: 0,
1767                         htlc_maximum_msat: OptionalField::Absent,
1768                         fee_base_msat: 0,
1769                         fee_proportional_millionths: 0,
1770                         excess_data: Vec::new()
1771                 });
1772
1773                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1774
1775                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1776                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1777                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1778                         short_channel_id: 3,
1779                         timestamp: 1,
1780                         flags: 0,
1781                         cltv_expiry_delta: (3 << 8) | 1,
1782                         htlc_minimum_msat: 0,
1783                         htlc_maximum_msat: OptionalField::Absent,
1784                         fee_base_msat: 0,
1785                         fee_proportional_millionths: 0,
1786                         excess_data: Vec::new()
1787                 });
1788                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1789                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1790                         short_channel_id: 3,
1791                         timestamp: 1,
1792                         flags: 1,
1793                         cltv_expiry_delta: (3 << 8) | 2,
1794                         htlc_minimum_msat: 0,
1795                         htlc_maximum_msat: OptionalField::Absent,
1796                         fee_base_msat: 100,
1797                         fee_proportional_millionths: 0,
1798                         excess_data: Vec::new()
1799                 });
1800
1801                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1802                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1803                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1804                         short_channel_id: 4,
1805                         timestamp: 1,
1806                         flags: 0,
1807                         cltv_expiry_delta: (4 << 8) | 1,
1808                         htlc_minimum_msat: 0,
1809                         htlc_maximum_msat: OptionalField::Absent,
1810                         fee_base_msat: 0,
1811                         fee_proportional_millionths: 1000000,
1812                         excess_data: Vec::new()
1813                 });
1814                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1815                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1816                         short_channel_id: 4,
1817                         timestamp: 1,
1818                         flags: 1,
1819                         cltv_expiry_delta: (4 << 8) | 2,
1820                         htlc_minimum_msat: 0,
1821                         htlc_maximum_msat: OptionalField::Absent,
1822                         fee_base_msat: 0,
1823                         fee_proportional_millionths: 0,
1824                         excess_data: Vec::new()
1825                 });
1826
1827                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1828                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1829                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1830                         short_channel_id: 13,
1831                         timestamp: 1,
1832                         flags: 0,
1833                         cltv_expiry_delta: (13 << 8) | 1,
1834                         htlc_minimum_msat: 0,
1835                         htlc_maximum_msat: OptionalField::Absent,
1836                         fee_base_msat: 0,
1837                         fee_proportional_millionths: 2000000,
1838                         excess_data: Vec::new()
1839                 });
1840                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1841                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1842                         short_channel_id: 13,
1843                         timestamp: 1,
1844                         flags: 1,
1845                         cltv_expiry_delta: (13 << 8) | 2,
1846                         htlc_minimum_msat: 0,
1847                         htlc_maximum_msat: OptionalField::Absent,
1848                         fee_base_msat: 0,
1849                         fee_proportional_millionths: 0,
1850                         excess_data: Vec::new()
1851                 });
1852
1853                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1854
1855                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1856                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1857                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1858                         short_channel_id: 6,
1859                         timestamp: 1,
1860                         flags: 0,
1861                         cltv_expiry_delta: (6 << 8) | 1,
1862                         htlc_minimum_msat: 0,
1863                         htlc_maximum_msat: OptionalField::Absent,
1864                         fee_base_msat: 0,
1865                         fee_proportional_millionths: 0,
1866                         excess_data: Vec::new()
1867                 });
1868                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1869                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1870                         short_channel_id: 6,
1871                         timestamp: 1,
1872                         flags: 1,
1873                         cltv_expiry_delta: (6 << 8) | 2,
1874                         htlc_minimum_msat: 0,
1875                         htlc_maximum_msat: OptionalField::Absent,
1876                         fee_base_msat: 0,
1877                         fee_proportional_millionths: 0,
1878                         excess_data: Vec::new(),
1879                 });
1880
1881                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1882                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1883                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1884                         short_channel_id: 11,
1885                         timestamp: 1,
1886                         flags: 0,
1887                         cltv_expiry_delta: (11 << 8) | 1,
1888                         htlc_minimum_msat: 0,
1889                         htlc_maximum_msat: OptionalField::Absent,
1890                         fee_base_msat: 0,
1891                         fee_proportional_millionths: 0,
1892                         excess_data: Vec::new()
1893                 });
1894                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1895                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1896                         short_channel_id: 11,
1897                         timestamp: 1,
1898                         flags: 1,
1899                         cltv_expiry_delta: (11 << 8) | 2,
1900                         htlc_minimum_msat: 0,
1901                         htlc_maximum_msat: OptionalField::Absent,
1902                         fee_base_msat: 0,
1903                         fee_proportional_millionths: 0,
1904                         excess_data: Vec::new()
1905                 });
1906
1907                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1908
1909                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1910
1911                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1912                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1913                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1914                         short_channel_id: 7,
1915                         timestamp: 1,
1916                         flags: 0,
1917                         cltv_expiry_delta: (7 << 8) | 1,
1918                         htlc_minimum_msat: 0,
1919                         htlc_maximum_msat: OptionalField::Absent,
1920                         fee_base_msat: 0,
1921                         fee_proportional_millionths: 1000000,
1922                         excess_data: Vec::new()
1923                 });
1924                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1925                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1926                         short_channel_id: 7,
1927                         timestamp: 1,
1928                         flags: 1,
1929                         cltv_expiry_delta: (7 << 8) | 2,
1930                         htlc_minimum_msat: 0,
1931                         htlc_maximum_msat: OptionalField::Absent,
1932                         fee_base_msat: 0,
1933                         fee_proportional_millionths: 0,
1934                         excess_data: Vec::new()
1935                 });
1936
1937                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1938
1939                 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1940         }
1941
1942         #[test]
1943         fn simple_route_test() {
1944                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1945                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1946                 let payee = Payee::from_node_id(nodes[2]);
1947                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1948
1949                 // Simple route to 2 via 1
1950
1951                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
1952                         assert_eq!(err, "Cannot send a payment of 0 msat");
1953                 } else { panic!(); }
1954
1955                 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1956                 assert_eq!(route.paths[0].len(), 2);
1957
1958                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1959                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1960                 assert_eq!(route.paths[0][0].fee_msat, 100);
1961                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1962                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1963                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1964
1965                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1966                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1967                 assert_eq!(route.paths[0][1].fee_msat, 100);
1968                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1969                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1970                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1971         }
1972
1973         #[test]
1974         fn invalid_first_hop_test() {
1975                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1976                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1977                 let payee = Payee::from_node_id(nodes[2]);
1978                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1979
1980                 // Simple route to 2 via 1
1981
1982                 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1983
1984                 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) {
1985                         assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1986                 } else { panic!(); }
1987
1988                 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1989                 assert_eq!(route.paths[0].len(), 2);
1990         }
1991
1992         #[test]
1993         fn htlc_minimum_test() {
1994                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
1995                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1996                 let payee = Payee::from_node_id(nodes[2]);
1997                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1998
1999                 // Simple route to 2 via 1
2000
2001                 // Disable other paths
2002                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2003                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2004                         short_channel_id: 12,
2005                         timestamp: 2,
2006                         flags: 2, // to disable
2007                         cltv_expiry_delta: 0,
2008                         htlc_minimum_msat: 0,
2009                         htlc_maximum_msat: OptionalField::Absent,
2010                         fee_base_msat: 0,
2011                         fee_proportional_millionths: 0,
2012                         excess_data: Vec::new()
2013                 });
2014                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2015                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2016                         short_channel_id: 3,
2017                         timestamp: 2,
2018                         flags: 2, // to disable
2019                         cltv_expiry_delta: 0,
2020                         htlc_minimum_msat: 0,
2021                         htlc_maximum_msat: OptionalField::Absent,
2022                         fee_base_msat: 0,
2023                         fee_proportional_millionths: 0,
2024                         excess_data: Vec::new()
2025                 });
2026                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2027                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2028                         short_channel_id: 13,
2029                         timestamp: 2,
2030                         flags: 2, // to disable
2031                         cltv_expiry_delta: 0,
2032                         htlc_minimum_msat: 0,
2033                         htlc_maximum_msat: OptionalField::Absent,
2034                         fee_base_msat: 0,
2035                         fee_proportional_millionths: 0,
2036                         excess_data: Vec::new()
2037                 });
2038                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2039                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2040                         short_channel_id: 6,
2041                         timestamp: 2,
2042                         flags: 2, // to disable
2043                         cltv_expiry_delta: 0,
2044                         htlc_minimum_msat: 0,
2045                         htlc_maximum_msat: OptionalField::Absent,
2046                         fee_base_msat: 0,
2047                         fee_proportional_millionths: 0,
2048                         excess_data: Vec::new()
2049                 });
2050                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2051                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2052                         short_channel_id: 7,
2053                         timestamp: 2,
2054                         flags: 2, // to disable
2055                         cltv_expiry_delta: 0,
2056                         htlc_minimum_msat: 0,
2057                         htlc_maximum_msat: OptionalField::Absent,
2058                         fee_base_msat: 0,
2059                         fee_proportional_millionths: 0,
2060                         excess_data: Vec::new()
2061                 });
2062
2063                 // Check against amount_to_transfer_over_msat.
2064                 // Set minimal HTLC of 200_000_000 msat.
2065                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2066                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2067                         short_channel_id: 2,
2068                         timestamp: 3,
2069                         flags: 0,
2070                         cltv_expiry_delta: 0,
2071                         htlc_minimum_msat: 200_000_000,
2072                         htlc_maximum_msat: OptionalField::Absent,
2073                         fee_base_msat: 0,
2074                         fee_proportional_millionths: 0,
2075                         excess_data: Vec::new()
2076                 });
2077
2078                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2079                 // be used.
2080                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2081                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2082                         short_channel_id: 4,
2083                         timestamp: 3,
2084                         flags: 0,
2085                         cltv_expiry_delta: 0,
2086                         htlc_minimum_msat: 0,
2087                         htlc_maximum_msat: OptionalField::Present(199_999_999),
2088                         fee_base_msat: 0,
2089                         fee_proportional_millionths: 0,
2090                         excess_data: Vec::new()
2091                 });
2092
2093                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2094                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2095                         assert_eq!(err, "Failed to find a path to the given destination");
2096                 } else { panic!(); }
2097
2098                 // Lift the restriction on the first hop.
2099                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2100                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2101                         short_channel_id: 2,
2102                         timestamp: 4,
2103                         flags: 0,
2104                         cltv_expiry_delta: 0,
2105                         htlc_minimum_msat: 0,
2106                         htlc_maximum_msat: OptionalField::Absent,
2107                         fee_base_msat: 0,
2108                         fee_proportional_millionths: 0,
2109                         excess_data: Vec::new()
2110                 });
2111
2112                 // A payment above the minimum should pass
2113                 let route = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2114                 assert_eq!(route.paths[0].len(), 2);
2115         }
2116
2117         #[test]
2118         fn htlc_minimum_overpay_test() {
2119                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2120                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2121                 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2122                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2123
2124                 // A route to node#2 via two paths.
2125                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2126                 // Thus, they can't send 60 without overpaying.
2127                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2128                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2129                         short_channel_id: 2,
2130                         timestamp: 2,
2131                         flags: 0,
2132                         cltv_expiry_delta: 0,
2133                         htlc_minimum_msat: 35_000,
2134                         htlc_maximum_msat: OptionalField::Present(40_000),
2135                         fee_base_msat: 0,
2136                         fee_proportional_millionths: 0,
2137                         excess_data: Vec::new()
2138                 });
2139                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2140                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2141                         short_channel_id: 12,
2142                         timestamp: 3,
2143                         flags: 0,
2144                         cltv_expiry_delta: 0,
2145                         htlc_minimum_msat: 35_000,
2146                         htlc_maximum_msat: OptionalField::Present(40_000),
2147                         fee_base_msat: 0,
2148                         fee_proportional_millionths: 0,
2149                         excess_data: Vec::new()
2150                 });
2151
2152                 // Make 0 fee.
2153                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2154                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2155                         short_channel_id: 13,
2156                         timestamp: 2,
2157                         flags: 0,
2158                         cltv_expiry_delta: 0,
2159                         htlc_minimum_msat: 0,
2160                         htlc_maximum_msat: OptionalField::Absent,
2161                         fee_base_msat: 0,
2162                         fee_proportional_millionths: 0,
2163                         excess_data: Vec::new()
2164                 });
2165                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2166                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2167                         short_channel_id: 4,
2168                         timestamp: 2,
2169                         flags: 0,
2170                         cltv_expiry_delta: 0,
2171                         htlc_minimum_msat: 0,
2172                         htlc_maximum_msat: OptionalField::Absent,
2173                         fee_base_msat: 0,
2174                         fee_proportional_millionths: 0,
2175                         excess_data: Vec::new()
2176                 });
2177
2178                 // Disable other paths
2179                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2180                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2181                         short_channel_id: 1,
2182                         timestamp: 3,
2183                         flags: 2, // to disable
2184                         cltv_expiry_delta: 0,
2185                         htlc_minimum_msat: 0,
2186                         htlc_maximum_msat: OptionalField::Absent,
2187                         fee_base_msat: 0,
2188                         fee_proportional_millionths: 0,
2189                         excess_data: Vec::new()
2190                 });
2191
2192                 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2193                 // Overpay fees to hit htlc_minimum_msat.
2194                 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2195                 // TODO: this could be better balanced to overpay 10k and not 15k.
2196                 assert_eq!(overpaid_fees, 15_000);
2197
2198                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2199                 // while taking even more fee to match htlc_minimum_msat.
2200                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2201                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2202                         short_channel_id: 12,
2203                         timestamp: 4,
2204                         flags: 0,
2205                         cltv_expiry_delta: 0,
2206                         htlc_minimum_msat: 65_000,
2207                         htlc_maximum_msat: OptionalField::Present(80_000),
2208                         fee_base_msat: 0,
2209                         fee_proportional_millionths: 0,
2210                         excess_data: Vec::new()
2211                 });
2212                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2213                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2214                         short_channel_id: 2,
2215                         timestamp: 3,
2216                         flags: 0,
2217                         cltv_expiry_delta: 0,
2218                         htlc_minimum_msat: 0,
2219                         htlc_maximum_msat: OptionalField::Absent,
2220                         fee_base_msat: 0,
2221                         fee_proportional_millionths: 0,
2222                         excess_data: Vec::new()
2223                 });
2224                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2225                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2226                         short_channel_id: 4,
2227                         timestamp: 4,
2228                         flags: 0,
2229                         cltv_expiry_delta: 0,
2230                         htlc_minimum_msat: 0,
2231                         htlc_maximum_msat: OptionalField::Absent,
2232                         fee_base_msat: 0,
2233                         fee_proportional_millionths: 100_000,
2234                         excess_data: Vec::new()
2235                 });
2236
2237                 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2238                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2239                 assert_eq!(route.paths.len(), 1);
2240                 assert_eq!(route.paths[0][0].short_channel_id, 12);
2241                 let fees = route.paths[0][0].fee_msat;
2242                 assert_eq!(fees, 5_000);
2243
2244                 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2245                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2246                 // the other channel.
2247                 assert_eq!(route.paths.len(), 1);
2248                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2249                 let fees = route.paths[0][0].fee_msat;
2250                 assert_eq!(fees, 5_000);
2251         }
2252
2253         #[test]
2254         fn disable_channels_test() {
2255                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2256                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2257                 let payee = Payee::from_node_id(nodes[2]);
2258                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2259
2260                 // // Disable channels 4 and 12 by flags=2
2261                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2262                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2263                         short_channel_id: 4,
2264                         timestamp: 2,
2265                         flags: 2, // to disable
2266                         cltv_expiry_delta: 0,
2267                         htlc_minimum_msat: 0,
2268                         htlc_maximum_msat: OptionalField::Absent,
2269                         fee_base_msat: 0,
2270                         fee_proportional_millionths: 0,
2271                         excess_data: Vec::new()
2272                 });
2273                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2274                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2275                         short_channel_id: 12,
2276                         timestamp: 2,
2277                         flags: 2, // to disable
2278                         cltv_expiry_delta: 0,
2279                         htlc_minimum_msat: 0,
2280                         htlc_maximum_msat: OptionalField::Absent,
2281                         fee_base_msat: 0,
2282                         fee_proportional_millionths: 0,
2283                         excess_data: Vec::new()
2284                 });
2285
2286                 // If all the channels require some features we don't understand, route should fail
2287                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2288                         assert_eq!(err, "Failed to find a path to the given destination");
2289                 } else { panic!(); }
2290
2291                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2292                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2293                 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2294                 assert_eq!(route.paths[0].len(), 2);
2295
2296                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2297                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2298                 assert_eq!(route.paths[0][0].fee_msat, 200);
2299                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2300                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2301                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2302
2303                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2304                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2305                 assert_eq!(route.paths[0][1].fee_msat, 100);
2306                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2307                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2308                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2309         }
2310
2311         #[test]
2312         fn disable_node_test() {
2313                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2314                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2315                 let payee = Payee::from_node_id(nodes[2]);
2316                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2317
2318                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2319                 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2320                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2321                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2322                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2323
2324                 // If all nodes require some features we don't understand, route should fail
2325                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2326                         assert_eq!(err, "Failed to find a path to the given destination");
2327                 } else { panic!(); }
2328
2329                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2330                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2331                 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2332                 assert_eq!(route.paths[0].len(), 2);
2333
2334                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2335                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2336                 assert_eq!(route.paths[0][0].fee_msat, 200);
2337                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2338                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2339                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2340
2341                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2342                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2343                 assert_eq!(route.paths[0][1].fee_msat, 100);
2344                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2345                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2346                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2347
2348                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2349                 // naively) assume that the user checked the feature bits on the invoice, which override
2350                 // the node_announcement.
2351         }
2352
2353         #[test]
2354         fn our_chans_test() {
2355                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2356                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2357                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2358
2359                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2360                 let payee = Payee::from_node_id(nodes[0]);
2361                 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2362                 assert_eq!(route.paths[0].len(), 3);
2363
2364                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2365                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2366                 assert_eq!(route.paths[0][0].fee_msat, 200);
2367                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2368                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2369                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2370
2371                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2372                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2373                 assert_eq!(route.paths[0][1].fee_msat, 100);
2374                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2375                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2376                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2377
2378                 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2379                 assert_eq!(route.paths[0][2].short_channel_id, 3);
2380                 assert_eq!(route.paths[0][2].fee_msat, 100);
2381                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2382                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2383                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2384
2385                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2386                 let payee = Payee::from_node_id(nodes[2]);
2387                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2388                 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2389                 assert_eq!(route.paths[0].len(), 2);
2390
2391                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2392                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2393                 assert_eq!(route.paths[0][0].fee_msat, 200);
2394                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2395                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2396                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2397
2398                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2399                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2400                 assert_eq!(route.paths[0][1].fee_msat, 100);
2401                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2402                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2403                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2404         }
2405
2406         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2407                 let zero_fees = RoutingFees {
2408                         base_msat: 0,
2409                         proportional_millionths: 0,
2410                 };
2411                 vec![RouteHint(vec![RouteHintHop {
2412                         src_node_id: nodes[3],
2413                         short_channel_id: 8,
2414                         fees: zero_fees,
2415                         cltv_expiry_delta: (8 << 8) | 1,
2416                         htlc_minimum_msat: None,
2417                         htlc_maximum_msat: None,
2418                 }
2419                 ]), RouteHint(vec![RouteHintHop {
2420                         src_node_id: nodes[4],
2421                         short_channel_id: 9,
2422                         fees: RoutingFees {
2423                                 base_msat: 1001,
2424                                 proportional_millionths: 0,
2425                         },
2426                         cltv_expiry_delta: (9 << 8) | 1,
2427                         htlc_minimum_msat: None,
2428                         htlc_maximum_msat: None,
2429                 }]), RouteHint(vec![RouteHintHop {
2430                         src_node_id: nodes[5],
2431                         short_channel_id: 10,
2432                         fees: zero_fees,
2433                         cltv_expiry_delta: (10 << 8) | 1,
2434                         htlc_minimum_msat: None,
2435                         htlc_maximum_msat: None,
2436                 }])]
2437         }
2438
2439         fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2440                 let zero_fees = RoutingFees {
2441                         base_msat: 0,
2442                         proportional_millionths: 0,
2443                 };
2444                 vec![RouteHint(vec![RouteHintHop {
2445                         src_node_id: nodes[2],
2446                         short_channel_id: 5,
2447                         fees: RoutingFees {
2448                                 base_msat: 100,
2449                                 proportional_millionths: 0,
2450                         },
2451                         cltv_expiry_delta: (5 << 8) | 1,
2452                         htlc_minimum_msat: None,
2453                         htlc_maximum_msat: None,
2454                 }, RouteHintHop {
2455                         src_node_id: nodes[3],
2456                         short_channel_id: 8,
2457                         fees: zero_fees,
2458                         cltv_expiry_delta: (8 << 8) | 1,
2459                         htlc_minimum_msat: None,
2460                         htlc_maximum_msat: None,
2461                 }
2462                 ]), RouteHint(vec![RouteHintHop {
2463                         src_node_id: nodes[4],
2464                         short_channel_id: 9,
2465                         fees: RoutingFees {
2466                                 base_msat: 1001,
2467                                 proportional_millionths: 0,
2468                         },
2469                         cltv_expiry_delta: (9 << 8) | 1,
2470                         htlc_minimum_msat: None,
2471                         htlc_maximum_msat: None,
2472                 }]), RouteHint(vec![RouteHintHop {
2473                         src_node_id: nodes[5],
2474                         short_channel_id: 10,
2475                         fees: zero_fees,
2476                         cltv_expiry_delta: (10 << 8) | 1,
2477                         htlc_minimum_msat: None,
2478                         htlc_maximum_msat: None,
2479                 }])]
2480         }
2481
2482         #[test]
2483         fn partial_route_hint_test() {
2484                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2485                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2486                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2487
2488                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2489                 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2490                 // RouteHint may be partially used by the algo to build the best path.
2491
2492                 // First check that last hop can't have its source as the payee.
2493                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2494                         src_node_id: nodes[6],
2495                         short_channel_id: 8,
2496                         fees: RoutingFees {
2497                                 base_msat: 1000,
2498                                 proportional_millionths: 0,
2499                         },
2500                         cltv_expiry_delta: (8 << 8) | 1,
2501                         htlc_minimum_msat: None,
2502                         htlc_maximum_msat: None,
2503                 }]);
2504
2505                 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2506                 invalid_last_hops.push(invalid_last_hop);
2507                 {
2508                         let payee = Payee::from_node_id(nodes[6]).with_route_hints(invalid_last_hops);
2509                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2510                                 assert_eq!(err, "Route hint cannot have the payee as the source.");
2511                         } else { panic!(); }
2512                 }
2513
2514                 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2515                 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2516                 assert_eq!(route.paths[0].len(), 5);
2517
2518                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2519                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2520                 assert_eq!(route.paths[0][0].fee_msat, 100);
2521                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2522                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2523                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2524
2525                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2526                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2527                 assert_eq!(route.paths[0][1].fee_msat, 0);
2528                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2529                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2530                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2531
2532                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2533                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2534                 assert_eq!(route.paths[0][2].fee_msat, 0);
2535                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2536                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2537                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2538
2539                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2540                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2541                 assert_eq!(route.paths[0][3].fee_msat, 0);
2542                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2543                 // If we have a peer in the node map, we'll use their features here since we don't have
2544                 // a way of figuring out their features from the invoice:
2545                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2546                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2547
2548                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2549                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2550                 assert_eq!(route.paths[0][4].fee_msat, 100);
2551                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2552                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2553                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2554         }
2555
2556         fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2557                 let zero_fees = RoutingFees {
2558                         base_msat: 0,
2559                         proportional_millionths: 0,
2560                 };
2561                 vec![RouteHint(vec![RouteHintHop {
2562                         src_node_id: nodes[3],
2563                         short_channel_id: 8,
2564                         fees: zero_fees,
2565                         cltv_expiry_delta: (8 << 8) | 1,
2566                         htlc_minimum_msat: None,
2567                         htlc_maximum_msat: None,
2568                 }]), RouteHint(vec![
2569
2570                 ]), RouteHint(vec![RouteHintHop {
2571                         src_node_id: nodes[5],
2572                         short_channel_id: 10,
2573                         fees: zero_fees,
2574                         cltv_expiry_delta: (10 << 8) | 1,
2575                         htlc_minimum_msat: None,
2576                         htlc_maximum_msat: None,
2577                 }])]
2578         }
2579
2580         #[test]
2581         fn ignores_empty_last_hops_test() {
2582                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2583                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2584                 let payee = Payee::from_node_id(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2585                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2586
2587                 // Test handling of an empty RouteHint passed in Invoice.
2588
2589                 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2590                 assert_eq!(route.paths[0].len(), 5);
2591
2592                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2593                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2594                 assert_eq!(route.paths[0][0].fee_msat, 100);
2595                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2596                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2597                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2598
2599                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2600                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2601                 assert_eq!(route.paths[0][1].fee_msat, 0);
2602                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2603                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2604                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2605
2606                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2607                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2608                 assert_eq!(route.paths[0][2].fee_msat, 0);
2609                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2610                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2611                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2612
2613                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2614                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2615                 assert_eq!(route.paths[0][3].fee_msat, 0);
2616                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2617                 // If we have a peer in the node map, we'll use their features here since we don't have
2618                 // a way of figuring out their features from the invoice:
2619                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2620                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2621
2622                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2623                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2624                 assert_eq!(route.paths[0][4].fee_msat, 100);
2625                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2626                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2627                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2628         }
2629
2630         fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2631                 let zero_fees = RoutingFees {
2632                         base_msat: 0,
2633                         proportional_millionths: 0,
2634                 };
2635                 vec![RouteHint(vec![RouteHintHop {
2636                         src_node_id: nodes[2],
2637                         short_channel_id: 5,
2638                         fees: RoutingFees {
2639                                 base_msat: 100,
2640                                 proportional_millionths: 0,
2641                         },
2642                         cltv_expiry_delta: (5 << 8) | 1,
2643                         htlc_minimum_msat: None,
2644                         htlc_maximum_msat: None,
2645                 }, RouteHintHop {
2646                         src_node_id: nodes[3],
2647                         short_channel_id: 8,
2648                         fees: zero_fees,
2649                         cltv_expiry_delta: (8 << 8) | 1,
2650                         htlc_minimum_msat: None,
2651                         htlc_maximum_msat: None,
2652                 }]), RouteHint(vec![RouteHintHop {
2653                         src_node_id: nodes[5],
2654                         short_channel_id: 10,
2655                         fees: zero_fees,
2656                         cltv_expiry_delta: (10 << 8) | 1,
2657                         htlc_minimum_msat: None,
2658                         htlc_maximum_msat: None,
2659                 }])]
2660         }
2661
2662         #[test]
2663         fn multi_hint_last_hops_test() {
2664                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2665                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2666                 let payee = Payee::from_node_id(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2667                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2668                 // Test through channels 2, 3, 5, 8.
2669                 // Test shows that multiple hop hints are considered.
2670
2671                 // Disabling channels 6 & 7 by flags=2
2672                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2673                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2674                         short_channel_id: 6,
2675                         timestamp: 2,
2676                         flags: 2, // to disable
2677                         cltv_expiry_delta: 0,
2678                         htlc_minimum_msat: 0,
2679                         htlc_maximum_msat: OptionalField::Absent,
2680                         fee_base_msat: 0,
2681                         fee_proportional_millionths: 0,
2682                         excess_data: Vec::new()
2683                 });
2684                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2685                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2686                         short_channel_id: 7,
2687                         timestamp: 2,
2688                         flags: 2, // to disable
2689                         cltv_expiry_delta: 0,
2690                         htlc_minimum_msat: 0,
2691                         htlc_maximum_msat: OptionalField::Absent,
2692                         fee_base_msat: 0,
2693                         fee_proportional_millionths: 0,
2694                         excess_data: Vec::new()
2695                 });
2696
2697                 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2698                 assert_eq!(route.paths[0].len(), 4);
2699
2700                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2701                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2702                 assert_eq!(route.paths[0][0].fee_msat, 200);
2703                 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2704                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2705                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2706
2707                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2708                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2709                 assert_eq!(route.paths[0][1].fee_msat, 100);
2710                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2711                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2712                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2713
2714                 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2715                 assert_eq!(route.paths[0][2].short_channel_id, 5);
2716                 assert_eq!(route.paths[0][2].fee_msat, 0);
2717                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2718                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2719                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2720
2721                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2722                 assert_eq!(route.paths[0][3].short_channel_id, 8);
2723                 assert_eq!(route.paths[0][3].fee_msat, 100);
2724                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2725                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2726                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2727         }
2728
2729         fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2730                 let zero_fees = RoutingFees {
2731                         base_msat: 0,
2732                         proportional_millionths: 0,
2733                 };
2734                 vec![RouteHint(vec![RouteHintHop {
2735                         src_node_id: nodes[4],
2736                         short_channel_id: 11,
2737                         fees: zero_fees,
2738                         cltv_expiry_delta: (11 << 8) | 1,
2739                         htlc_minimum_msat: None,
2740                         htlc_maximum_msat: None,
2741                 }, RouteHintHop {
2742                         src_node_id: nodes[3],
2743                         short_channel_id: 8,
2744                         fees: zero_fees,
2745                         cltv_expiry_delta: (8 << 8) | 1,
2746                         htlc_minimum_msat: None,
2747                         htlc_maximum_msat: None,
2748                 }]), RouteHint(vec![RouteHintHop {
2749                         src_node_id: nodes[4],
2750                         short_channel_id: 9,
2751                         fees: RoutingFees {
2752                                 base_msat: 1001,
2753                                 proportional_millionths: 0,
2754                         },
2755                         cltv_expiry_delta: (9 << 8) | 1,
2756                         htlc_minimum_msat: None,
2757                         htlc_maximum_msat: None,
2758                 }]), RouteHint(vec![RouteHintHop {
2759                         src_node_id: nodes[5],
2760                         short_channel_id: 10,
2761                         fees: zero_fees,
2762                         cltv_expiry_delta: (10 << 8) | 1,
2763                         htlc_minimum_msat: None,
2764                         htlc_maximum_msat: None,
2765                 }])]
2766         }
2767
2768         #[test]
2769         fn last_hops_with_public_channel_test() {
2770                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2771                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2772                 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2773                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2774                 // This test shows that public routes can be present in the invoice
2775                 // which would be handled in the same manner.
2776
2777                 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2778                 assert_eq!(route.paths[0].len(), 5);
2779
2780                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2781                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2782                 assert_eq!(route.paths[0][0].fee_msat, 100);
2783                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2784                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2785                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2786
2787                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2788                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2789                 assert_eq!(route.paths[0][1].fee_msat, 0);
2790                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2791                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2792                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2793
2794                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2795                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2796                 assert_eq!(route.paths[0][2].fee_msat, 0);
2797                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2798                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2799                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2800
2801                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2802                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2803                 assert_eq!(route.paths[0][3].fee_msat, 0);
2804                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2805                 // If we have a peer in the node map, we'll use their features here since we don't have
2806                 // a way of figuring out their features from the invoice:
2807                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2808                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2809
2810                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2811                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2812                 assert_eq!(route.paths[0][4].fee_msat, 100);
2813                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2814                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2815                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2816         }
2817
2818         #[test]
2819         fn our_chans_last_hop_connect_test() {
2820                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2821                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2822                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2823
2824                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2825                 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2826                 let mut last_hops = last_hops(&nodes);
2827                 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops.clone());
2828                 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2829                 assert_eq!(route.paths[0].len(), 2);
2830
2831                 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2832                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2833                 assert_eq!(route.paths[0][0].fee_msat, 0);
2834                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2835                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2836                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2837
2838                 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2839                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2840                 assert_eq!(route.paths[0][1].fee_msat, 100);
2841                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2842                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2843                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2844
2845                 last_hops[0].0[0].fees.base_msat = 1000;
2846
2847                 // Revert to via 6 as the fee on 8 goes up
2848                 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops);
2849                 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2850                 assert_eq!(route.paths[0].len(), 4);
2851
2852                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2853                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2854                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2855                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2856                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2857                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2858
2859                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2860                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2861                 assert_eq!(route.paths[0][1].fee_msat, 100);
2862                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2863                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2864                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2865
2866                 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2867                 assert_eq!(route.paths[0][2].short_channel_id, 7);
2868                 assert_eq!(route.paths[0][2].fee_msat, 0);
2869                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2870                 // If we have a peer in the node map, we'll use their features here since we don't have
2871                 // a way of figuring out their features from the invoice:
2872                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2873                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2874
2875                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2876                 assert_eq!(route.paths[0][3].short_channel_id, 10);
2877                 assert_eq!(route.paths[0][3].fee_msat, 100);
2878                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2879                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2880                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2881
2882                 // ...but still use 8 for larger payments as 6 has a variable feerate
2883                 let route = get_route(&our_id, &payee, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2884                 assert_eq!(route.paths[0].len(), 5);
2885
2886                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2887                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2888                 assert_eq!(route.paths[0][0].fee_msat, 3000);
2889                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2890                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2891                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2892
2893                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2894                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2895                 assert_eq!(route.paths[0][1].fee_msat, 0);
2896                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2897                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2898                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2899
2900                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2901                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2902                 assert_eq!(route.paths[0][2].fee_msat, 0);
2903                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2904                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2905                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2906
2907                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2908                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2909                 assert_eq!(route.paths[0][3].fee_msat, 1000);
2910                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2911                 // If we have a peer in the node map, we'll use their features here since we don't have
2912                 // a way of figuring out their features from the invoice:
2913                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2914                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2915
2916                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2917                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2918                 assert_eq!(route.paths[0][4].fee_msat, 2000);
2919                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2920                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2921                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2922         }
2923
2924         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> {
2925                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2926                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2927                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2928
2929                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2930                 let last_hops = RouteHint(vec![RouteHintHop {
2931                         src_node_id: middle_node_id,
2932                         short_channel_id: 8,
2933                         fees: RoutingFees {
2934                                 base_msat: 1000,
2935                                 proportional_millionths: last_hop_fee_prop,
2936                         },
2937                         cltv_expiry_delta: (8 << 8) | 1,
2938                         htlc_minimum_msat: None,
2939                         htlc_maximum_msat: last_hop_htlc_max,
2940                 }]);
2941                 let payee = Payee::from_node_id(target_node_id).with_route_hints(vec![last_hops]);
2942                 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2943                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2944                 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)
2945         }
2946
2947         #[test]
2948         fn unannounced_path_test() {
2949                 // We should be able to send a payment to a destination without any help of a routing graph
2950                 // if we have a channel with a common counterparty that appears in the first and last hop
2951                 // hints.
2952                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2953
2954                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2955                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2956                 assert_eq!(route.paths[0].len(), 2);
2957
2958                 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2959                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2960                 assert_eq!(route.paths[0][0].fee_msat, 1001);
2961                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2962                 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2963                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2964
2965                 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2966                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2967                 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2968                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2969                 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2970                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2971         }
2972
2973         #[test]
2974         fn overflow_unannounced_path_test_liquidity_underflow() {
2975                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2976                 // the last-hop had a fee which overflowed a u64, we'd panic.
2977                 // This was due to us adding the first-hop from us unconditionally, causing us to think
2978                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2979                 // In this test, we previously hit a subtraction underflow due to having less available
2980                 // liquidity at the last hop than 0.
2981                 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());
2982         }
2983
2984         #[test]
2985         fn overflow_unannounced_path_test_feerate_overflow() {
2986                 // This tests for the same case as above, except instead of hitting a subtraction
2987                 // underflow, we hit a case where the fee charged at a hop overflowed.
2988                 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());
2989         }
2990
2991         #[test]
2992         fn available_amount_while_routing_test() {
2993                 // Tests whether we choose the correct available channel amount while routing.
2994
2995                 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2996                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2997                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2998                 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
2999
3000                 // We will use a simple single-path route from
3001                 // our node to node2 via node0: channels {1, 3}.
3002
3003                 // First disable all other paths.
3004                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3005                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3006                         short_channel_id: 2,
3007                         timestamp: 2,
3008                         flags: 2,
3009                         cltv_expiry_delta: 0,
3010                         htlc_minimum_msat: 0,
3011                         htlc_maximum_msat: OptionalField::Present(100_000),
3012                         fee_base_msat: 0,
3013                         fee_proportional_millionths: 0,
3014                         excess_data: Vec::new()
3015                 });
3016                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3017                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3018                         short_channel_id: 12,
3019                         timestamp: 2,
3020                         flags: 2,
3021                         cltv_expiry_delta: 0,
3022                         htlc_minimum_msat: 0,
3023                         htlc_maximum_msat: OptionalField::Present(100_000),
3024                         fee_base_msat: 0,
3025                         fee_proportional_millionths: 0,
3026                         excess_data: Vec::new()
3027                 });
3028
3029                 // Make the first channel (#1) very permissive,
3030                 // and we will be testing all limits on the second channel.
3031                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3032                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3033                         short_channel_id: 1,
3034                         timestamp: 2,
3035                         flags: 0,
3036                         cltv_expiry_delta: 0,
3037                         htlc_minimum_msat: 0,
3038                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3039                         fee_base_msat: 0,
3040                         fee_proportional_millionths: 0,
3041                         excess_data: Vec::new()
3042                 });
3043
3044                 // First, let's see if routing works if we have absolutely no idea about the available amount.
3045                 // In this case, it should be set to 250_000 sats.
3046                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3047                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3048                         short_channel_id: 3,
3049                         timestamp: 2,
3050                         flags: 0,
3051                         cltv_expiry_delta: 0,
3052                         htlc_minimum_msat: 0,
3053                         htlc_maximum_msat: OptionalField::Absent,
3054                         fee_base_msat: 0,
3055                         fee_proportional_millionths: 0,
3056                         excess_data: Vec::new()
3057                 });
3058
3059                 {
3060                         // Attempt to route more than available results in a failure.
3061                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3062                                         &our_id, &payee, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3063                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3064                         } else { panic!(); }
3065                 }
3066
3067                 {
3068                         // Now, attempt to route an exact amount we have should be fine.
3069                         let route = get_route(&our_id, &payee, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3070                         assert_eq!(route.paths.len(), 1);
3071                         let path = route.paths.last().unwrap();
3072                         assert_eq!(path.len(), 2);
3073                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3074                         assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3075                 }
3076
3077                 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3078                 // Disable channel #1 and use another first hop.
3079                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3080                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3081                         short_channel_id: 1,
3082                         timestamp: 3,
3083                         flags: 2,
3084                         cltv_expiry_delta: 0,
3085                         htlc_minimum_msat: 0,
3086                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3087                         fee_base_msat: 0,
3088                         fee_proportional_millionths: 0,
3089                         excess_data: Vec::new()
3090                 });
3091
3092                 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3093                 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3094
3095                 {
3096                         // Attempt to route more than available results in a failure.
3097                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3098                                         &our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3099                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3100                         } else { panic!(); }
3101                 }
3102
3103                 {
3104                         // Now, attempt to route an exact amount we have should be fine.
3105                         let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3106                         assert_eq!(route.paths.len(), 1);
3107                         let path = route.paths.last().unwrap();
3108                         assert_eq!(path.len(), 2);
3109                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3110                         assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3111                 }
3112
3113                 // Enable channel #1 back.
3114                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3115                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3116                         short_channel_id: 1,
3117                         timestamp: 4,
3118                         flags: 0,
3119                         cltv_expiry_delta: 0,
3120                         htlc_minimum_msat: 0,
3121                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3122                         fee_base_msat: 0,
3123                         fee_proportional_millionths: 0,
3124                         excess_data: Vec::new()
3125                 });
3126
3127
3128                 // Now let's see if routing works if we know only htlc_maximum_msat.
3129                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3130                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3131                         short_channel_id: 3,
3132                         timestamp: 3,
3133                         flags: 0,
3134                         cltv_expiry_delta: 0,
3135                         htlc_minimum_msat: 0,
3136                         htlc_maximum_msat: OptionalField::Present(15_000),
3137                         fee_base_msat: 0,
3138                         fee_proportional_millionths: 0,
3139                         excess_data: Vec::new()
3140                 });
3141
3142                 {
3143                         // Attempt to route more than available results in a failure.
3144                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3145                                         &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3146                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3147                         } else { panic!(); }
3148                 }
3149
3150                 {
3151                         // Now, attempt to route an exact amount we have should be fine.
3152                         let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3153                         assert_eq!(route.paths.len(), 1);
3154                         let path = route.paths.last().unwrap();
3155                         assert_eq!(path.len(), 2);
3156                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3157                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
3158                 }
3159
3160                 // Now let's see if routing works if we know only capacity from the UTXO.
3161
3162                 // We can't change UTXO capacity on the fly, so we'll disable
3163                 // the existing channel and add another one with the capacity we need.
3164                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3165                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3166                         short_channel_id: 3,
3167                         timestamp: 4,
3168                         flags: 2,
3169                         cltv_expiry_delta: 0,
3170                         htlc_minimum_msat: 0,
3171                         htlc_maximum_msat: OptionalField::Absent,
3172                         fee_base_msat: 0,
3173                         fee_proportional_millionths: 0,
3174                         excess_data: Vec::new()
3175                 });
3176
3177                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3178                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3179                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3180                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3181                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3182
3183                 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3184                 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3185
3186                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3187                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3188                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3189                         short_channel_id: 333,
3190                         timestamp: 1,
3191                         flags: 0,
3192                         cltv_expiry_delta: (3 << 8) | 1,
3193                         htlc_minimum_msat: 0,
3194                         htlc_maximum_msat: OptionalField::Absent,
3195                         fee_base_msat: 0,
3196                         fee_proportional_millionths: 0,
3197                         excess_data: Vec::new()
3198                 });
3199                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3200                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3201                         short_channel_id: 333,
3202                         timestamp: 1,
3203                         flags: 1,
3204                         cltv_expiry_delta: (3 << 8) | 2,
3205                         htlc_minimum_msat: 0,
3206                         htlc_maximum_msat: OptionalField::Absent,
3207                         fee_base_msat: 100,
3208                         fee_proportional_millionths: 0,
3209                         excess_data: Vec::new()
3210                 });
3211
3212                 {
3213                         // Attempt to route more than available results in a failure.
3214                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3215                                         &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3216                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3217                         } else { panic!(); }
3218                 }
3219
3220                 {
3221                         // Now, attempt to route an exact amount we have should be fine.
3222                         let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3223                         assert_eq!(route.paths.len(), 1);
3224                         let path = route.paths.last().unwrap();
3225                         assert_eq!(path.len(), 2);
3226                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3227                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
3228                 }
3229
3230                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3231                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3232                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3233                         short_channel_id: 333,
3234                         timestamp: 6,
3235                         flags: 0,
3236                         cltv_expiry_delta: 0,
3237                         htlc_minimum_msat: 0,
3238                         htlc_maximum_msat: OptionalField::Present(10_000),
3239                         fee_base_msat: 0,
3240                         fee_proportional_millionths: 0,
3241                         excess_data: Vec::new()
3242                 });
3243
3244                 {
3245                         // Attempt to route more than available results in a failure.
3246                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3247                                         &our_id, &payee, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3248                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3249                         } else { panic!(); }
3250                 }
3251
3252                 {
3253                         // Now, attempt to route an exact amount we have should be fine.
3254                         let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3255                         assert_eq!(route.paths.len(), 1);
3256                         let path = route.paths.last().unwrap();
3257                         assert_eq!(path.len(), 2);
3258                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3259                         assert_eq!(path.last().unwrap().fee_msat, 10_000);
3260                 }
3261         }
3262
3263         #[test]
3264         fn available_liquidity_last_hop_test() {
3265                 // Check that available liquidity properly limits the path even when only
3266                 // one of the latter hops is limited.
3267                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3268                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3269                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3270                 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3271
3272                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3273                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3274                 // Total capacity: 50 sats.
3275
3276                 // Disable other potential paths.
3277                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3278                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3279                         short_channel_id: 2,
3280                         timestamp: 2,
3281                         flags: 2,
3282                         cltv_expiry_delta: 0,
3283                         htlc_minimum_msat: 0,
3284                         htlc_maximum_msat: OptionalField::Present(100_000),
3285                         fee_base_msat: 0,
3286                         fee_proportional_millionths: 0,
3287                         excess_data: Vec::new()
3288                 });
3289                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3290                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3291                         short_channel_id: 7,
3292                         timestamp: 2,
3293                         flags: 2,
3294                         cltv_expiry_delta: 0,
3295                         htlc_minimum_msat: 0,
3296                         htlc_maximum_msat: OptionalField::Present(100_000),
3297                         fee_base_msat: 0,
3298                         fee_proportional_millionths: 0,
3299                         excess_data: Vec::new()
3300                 });
3301
3302                 // Limit capacities
3303
3304                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3305                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3306                         short_channel_id: 12,
3307                         timestamp: 2,
3308                         flags: 0,
3309                         cltv_expiry_delta: 0,
3310                         htlc_minimum_msat: 0,
3311                         htlc_maximum_msat: OptionalField::Present(100_000),
3312                         fee_base_msat: 0,
3313                         fee_proportional_millionths: 0,
3314                         excess_data: Vec::new()
3315                 });
3316                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3317                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3318                         short_channel_id: 13,
3319                         timestamp: 2,
3320                         flags: 0,
3321                         cltv_expiry_delta: 0,
3322                         htlc_minimum_msat: 0,
3323                         htlc_maximum_msat: OptionalField::Present(100_000),
3324                         fee_base_msat: 0,
3325                         fee_proportional_millionths: 0,
3326                         excess_data: Vec::new()
3327                 });
3328
3329                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3330                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3331                         short_channel_id: 6,
3332                         timestamp: 2,
3333                         flags: 0,
3334                         cltv_expiry_delta: 0,
3335                         htlc_minimum_msat: 0,
3336                         htlc_maximum_msat: OptionalField::Present(50_000),
3337                         fee_base_msat: 0,
3338                         fee_proportional_millionths: 0,
3339                         excess_data: Vec::new()
3340                 });
3341                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3342                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3343                         short_channel_id: 11,
3344                         timestamp: 2,
3345                         flags: 0,
3346                         cltv_expiry_delta: 0,
3347                         htlc_minimum_msat: 0,
3348                         htlc_maximum_msat: OptionalField::Present(100_000),
3349                         fee_base_msat: 0,
3350                         fee_proportional_millionths: 0,
3351                         excess_data: Vec::new()
3352                 });
3353                 {
3354                         // Attempt to route more than available results in a failure.
3355                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3356                                         &our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3357                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3358                         } else { panic!(); }
3359                 }
3360
3361                 {
3362                         // Now, attempt to route 49 sats (just a bit below the capacity).
3363                         let route = get_route(&our_id, &payee, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3364                         assert_eq!(route.paths.len(), 1);
3365                         let mut total_amount_paid_msat = 0;
3366                         for path in &route.paths {
3367                                 assert_eq!(path.len(), 4);
3368                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3369                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3370                         }
3371                         assert_eq!(total_amount_paid_msat, 49_000);
3372                 }
3373
3374                 {
3375                         // Attempt to route an exact amount is also fine
3376                         let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3377                         assert_eq!(route.paths.len(), 1);
3378                         let mut total_amount_paid_msat = 0;
3379                         for path in &route.paths {
3380                                 assert_eq!(path.len(), 4);
3381                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3382                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3383                         }
3384                         assert_eq!(total_amount_paid_msat, 50_000);
3385                 }
3386         }
3387
3388         #[test]
3389         fn ignore_fee_first_hop_test() {
3390                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3391                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3392                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3393                 let payee = Payee::from_node_id(nodes[2]);
3394
3395                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3396                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3397                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3398                         short_channel_id: 1,
3399                         timestamp: 2,
3400                         flags: 0,
3401                         cltv_expiry_delta: 0,
3402                         htlc_minimum_msat: 0,
3403                         htlc_maximum_msat: OptionalField::Present(100_000),
3404                         fee_base_msat: 1_000_000,
3405                         fee_proportional_millionths: 0,
3406                         excess_data: Vec::new()
3407                 });
3408                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3409                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3410                         short_channel_id: 3,
3411                         timestamp: 2,
3412                         flags: 0,
3413                         cltv_expiry_delta: 0,
3414                         htlc_minimum_msat: 0,
3415                         htlc_maximum_msat: OptionalField::Present(50_000),
3416                         fee_base_msat: 0,
3417                         fee_proportional_millionths: 0,
3418                         excess_data: Vec::new()
3419                 });
3420
3421                 {
3422                         let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3423                         assert_eq!(route.paths.len(), 1);
3424                         let mut total_amount_paid_msat = 0;
3425                         for path in &route.paths {
3426                                 assert_eq!(path.len(), 2);
3427                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3428                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3429                         }
3430                         assert_eq!(total_amount_paid_msat, 50_000);
3431                 }
3432         }
3433
3434         #[test]
3435         fn simple_mpp_route_test() {
3436                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3437                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3438                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3439                 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
3440
3441                 // We need a route consisting of 3 paths:
3442                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3443                 // To achieve this, the amount being transferred should be around
3444                 // the total capacity of these 3 paths.
3445
3446                 // First, we set limits on these (previously unlimited) channels.
3447                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3448
3449                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3450                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3451                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3452                         short_channel_id: 1,
3453                         timestamp: 2,
3454                         flags: 0,
3455                         cltv_expiry_delta: 0,
3456                         htlc_minimum_msat: 0,
3457                         htlc_maximum_msat: OptionalField::Present(100_000),
3458                         fee_base_msat: 0,
3459                         fee_proportional_millionths: 0,
3460                         excess_data: Vec::new()
3461                 });
3462                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3463                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3464                         short_channel_id: 3,
3465                         timestamp: 2,
3466                         flags: 0,
3467                         cltv_expiry_delta: 0,
3468                         htlc_minimum_msat: 0,
3469                         htlc_maximum_msat: OptionalField::Present(50_000),
3470                         fee_base_msat: 0,
3471                         fee_proportional_millionths: 0,
3472                         excess_data: Vec::new()
3473                 });
3474
3475                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3476                 // (total limit 60).
3477                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3478                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3479                         short_channel_id: 12,
3480                         timestamp: 2,
3481                         flags: 0,
3482                         cltv_expiry_delta: 0,
3483                         htlc_minimum_msat: 0,
3484                         htlc_maximum_msat: OptionalField::Present(60_000),
3485                         fee_base_msat: 0,
3486                         fee_proportional_millionths: 0,
3487                         excess_data: Vec::new()
3488                 });
3489                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3490                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3491                         short_channel_id: 13,
3492                         timestamp: 2,
3493                         flags: 0,
3494                         cltv_expiry_delta: 0,
3495                         htlc_minimum_msat: 0,
3496                         htlc_maximum_msat: OptionalField::Present(60_000),
3497                         fee_base_msat: 0,
3498                         fee_proportional_millionths: 0,
3499                         excess_data: Vec::new()
3500                 });
3501
3502                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3503                 // (total capacity 180 sats).
3504                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3505                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3506                         short_channel_id: 2,
3507                         timestamp: 2,
3508                         flags: 0,
3509                         cltv_expiry_delta: 0,
3510                         htlc_minimum_msat: 0,
3511                         htlc_maximum_msat: OptionalField::Present(200_000),
3512                         fee_base_msat: 0,
3513                         fee_proportional_millionths: 0,
3514                         excess_data: Vec::new()
3515                 });
3516                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3517                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3518                         short_channel_id: 4,
3519                         timestamp: 2,
3520                         flags: 0,
3521                         cltv_expiry_delta: 0,
3522                         htlc_minimum_msat: 0,
3523                         htlc_maximum_msat: OptionalField::Present(180_000),
3524                         fee_base_msat: 0,
3525                         fee_proportional_millionths: 0,
3526                         excess_data: Vec::new()
3527                 });
3528
3529                 {
3530                         // Attempt to route more than available results in a failure.
3531                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3532                                         &our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3533                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3534                         } else { panic!(); }
3535                 }
3536
3537                 {
3538                         // Now, attempt to route 250 sats (just a bit below the capacity).
3539                         // Our algorithm should provide us with these 3 paths.
3540                         let route = get_route(&our_id, &payee, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3541                         assert_eq!(route.paths.len(), 3);
3542                         let mut total_amount_paid_msat = 0;
3543                         for path in &route.paths {
3544                                 assert_eq!(path.len(), 2);
3545                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3546                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3547                         }
3548                         assert_eq!(total_amount_paid_msat, 250_000);
3549                 }
3550
3551                 {
3552                         // Attempt to route an exact amount is also fine
3553                         let route = get_route(&our_id, &payee, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3554                         assert_eq!(route.paths.len(), 3);
3555                         let mut total_amount_paid_msat = 0;
3556                         for path in &route.paths {
3557                                 assert_eq!(path.len(), 2);
3558                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3559                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3560                         }
3561                         assert_eq!(total_amount_paid_msat, 290_000);
3562                 }
3563         }
3564
3565         #[test]
3566         fn long_mpp_route_test() {
3567                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3568                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3569                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3570                 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3571
3572                 // We need a route consisting of 3 paths:
3573                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3574                 // Note that these paths overlap (channels 5, 12, 13).
3575                 // We will route 300 sats.
3576                 // Each path will have 100 sats capacity, those channels which
3577                 // are used twice will have 200 sats capacity.
3578
3579                 // Disable other potential paths.
3580                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3581                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3582                         short_channel_id: 2,
3583                         timestamp: 2,
3584                         flags: 2,
3585                         cltv_expiry_delta: 0,
3586                         htlc_minimum_msat: 0,
3587                         htlc_maximum_msat: OptionalField::Present(100_000),
3588                         fee_base_msat: 0,
3589                         fee_proportional_millionths: 0,
3590                         excess_data: Vec::new()
3591                 });
3592                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3593                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3594                         short_channel_id: 7,
3595                         timestamp: 2,
3596                         flags: 2,
3597                         cltv_expiry_delta: 0,
3598                         htlc_minimum_msat: 0,
3599                         htlc_maximum_msat: OptionalField::Present(100_000),
3600                         fee_base_msat: 0,
3601                         fee_proportional_millionths: 0,
3602                         excess_data: Vec::new()
3603                 });
3604
3605                 // Path via {node0, node2} is channels {1, 3, 5}.
3606                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3607                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3608                         short_channel_id: 1,
3609                         timestamp: 2,
3610                         flags: 0,
3611                         cltv_expiry_delta: 0,
3612                         htlc_minimum_msat: 0,
3613                         htlc_maximum_msat: OptionalField::Present(100_000),
3614                         fee_base_msat: 0,
3615                         fee_proportional_millionths: 0,
3616                         excess_data: Vec::new()
3617                 });
3618                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3619                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3620                         short_channel_id: 3,
3621                         timestamp: 2,
3622                         flags: 0,
3623                         cltv_expiry_delta: 0,
3624                         htlc_minimum_msat: 0,
3625                         htlc_maximum_msat: OptionalField::Present(100_000),
3626                         fee_base_msat: 0,
3627                         fee_proportional_millionths: 0,
3628                         excess_data: Vec::new()
3629                 });
3630
3631                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3632                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3633                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3634                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3635                         short_channel_id: 5,
3636                         timestamp: 2,
3637                         flags: 0,
3638                         cltv_expiry_delta: 0,
3639                         htlc_minimum_msat: 0,
3640                         htlc_maximum_msat: OptionalField::Present(200_000),
3641                         fee_base_msat: 0,
3642                         fee_proportional_millionths: 0,
3643                         excess_data: Vec::new()
3644                 });
3645
3646                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3647                 // Add 100 sats to the capacities of {12, 13}, because these channels
3648                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3649                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3650                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3651                         short_channel_id: 12,
3652                         timestamp: 2,
3653                         flags: 0,
3654                         cltv_expiry_delta: 0,
3655                         htlc_minimum_msat: 0,
3656                         htlc_maximum_msat: OptionalField::Present(200_000),
3657                         fee_base_msat: 0,
3658                         fee_proportional_millionths: 0,
3659                         excess_data: Vec::new()
3660                 });
3661                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3662                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3663                         short_channel_id: 13,
3664                         timestamp: 2,
3665                         flags: 0,
3666                         cltv_expiry_delta: 0,
3667                         htlc_minimum_msat: 0,
3668                         htlc_maximum_msat: OptionalField::Present(200_000),
3669                         fee_base_msat: 0,
3670                         fee_proportional_millionths: 0,
3671                         excess_data: Vec::new()
3672                 });
3673
3674                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3675                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3676                         short_channel_id: 6,
3677                         timestamp: 2,
3678                         flags: 0,
3679                         cltv_expiry_delta: 0,
3680                         htlc_minimum_msat: 0,
3681                         htlc_maximum_msat: OptionalField::Present(100_000),
3682                         fee_base_msat: 0,
3683                         fee_proportional_millionths: 0,
3684                         excess_data: Vec::new()
3685                 });
3686                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3687                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3688                         short_channel_id: 11,
3689                         timestamp: 2,
3690                         flags: 0,
3691                         cltv_expiry_delta: 0,
3692                         htlc_minimum_msat: 0,
3693                         htlc_maximum_msat: OptionalField::Present(100_000),
3694                         fee_base_msat: 0,
3695                         fee_proportional_millionths: 0,
3696                         excess_data: Vec::new()
3697                 });
3698
3699                 // Path via {node7, node2} is channels {12, 13, 5}.
3700                 // We already limited them to 200 sats (they are used twice for 100 sats).
3701                 // Nothing to do here.
3702
3703                 {
3704                         // Attempt to route more than available results in a failure.
3705                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3706                                         &our_id, &payee, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3707                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3708                         } else { panic!(); }
3709                 }
3710
3711                 {
3712                         // Now, attempt to route 300 sats (exact amount we can route).
3713                         // Our algorithm should provide us with these 3 paths, 100 sats each.
3714                         let route = get_route(&our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3715                         assert_eq!(route.paths.len(), 3);
3716
3717                         let mut total_amount_paid_msat = 0;
3718                         for path in &route.paths {
3719                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3720                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3721                         }
3722                         assert_eq!(total_amount_paid_msat, 300_000);
3723                 }
3724
3725         }
3726
3727         #[test]
3728         fn mpp_cheaper_route_test() {
3729                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3730                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3731                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3732                 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3733
3734                 // This test checks that if we have two cheaper paths and one more expensive path,
3735                 // so that liquidity-wise any 2 of 3 combination is sufficient,
3736                 // two cheaper paths will be taken.
3737                 // These paths have equal available liquidity.
3738
3739                 // We need a combination of 3 paths:
3740                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3741                 // Note that these paths overlap (channels 5, 12, 13).
3742                 // Each path will have 100 sats capacity, those channels which
3743                 // are used twice will have 200 sats capacity.
3744
3745                 // Disable other potential paths.
3746                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3747                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3748                         short_channel_id: 2,
3749                         timestamp: 2,
3750                         flags: 2,
3751                         cltv_expiry_delta: 0,
3752                         htlc_minimum_msat: 0,
3753                         htlc_maximum_msat: OptionalField::Present(100_000),
3754                         fee_base_msat: 0,
3755                         fee_proportional_millionths: 0,
3756                         excess_data: Vec::new()
3757                 });
3758                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3759                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3760                         short_channel_id: 7,
3761                         timestamp: 2,
3762                         flags: 2,
3763                         cltv_expiry_delta: 0,
3764                         htlc_minimum_msat: 0,
3765                         htlc_maximum_msat: OptionalField::Present(100_000),
3766                         fee_base_msat: 0,
3767                         fee_proportional_millionths: 0,
3768                         excess_data: Vec::new()
3769                 });
3770
3771                 // Path via {node0, node2} is channels {1, 3, 5}.
3772                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3773                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3774                         short_channel_id: 1,
3775                         timestamp: 2,
3776                         flags: 0,
3777                         cltv_expiry_delta: 0,
3778                         htlc_minimum_msat: 0,
3779                         htlc_maximum_msat: OptionalField::Present(100_000),
3780                         fee_base_msat: 0,
3781                         fee_proportional_millionths: 0,
3782                         excess_data: Vec::new()
3783                 });
3784                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3785                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3786                         short_channel_id: 3,
3787                         timestamp: 2,
3788                         flags: 0,
3789                         cltv_expiry_delta: 0,
3790                         htlc_minimum_msat: 0,
3791                         htlc_maximum_msat: OptionalField::Present(100_000),
3792                         fee_base_msat: 0,
3793                         fee_proportional_millionths: 0,
3794                         excess_data: Vec::new()
3795                 });
3796
3797                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3798                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3799                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3800                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3801                         short_channel_id: 5,
3802                         timestamp: 2,
3803                         flags: 0,
3804                         cltv_expiry_delta: 0,
3805                         htlc_minimum_msat: 0,
3806                         htlc_maximum_msat: OptionalField::Present(200_000),
3807                         fee_base_msat: 0,
3808                         fee_proportional_millionths: 0,
3809                         excess_data: Vec::new()
3810                 });
3811
3812                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3813                 // Add 100 sats to the capacities of {12, 13}, because these channels
3814                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3815                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3816                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3817                         short_channel_id: 12,
3818                         timestamp: 2,
3819                         flags: 0,
3820                         cltv_expiry_delta: 0,
3821                         htlc_minimum_msat: 0,
3822                         htlc_maximum_msat: OptionalField::Present(200_000),
3823                         fee_base_msat: 0,
3824                         fee_proportional_millionths: 0,
3825                         excess_data: Vec::new()
3826                 });
3827                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3828                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3829                         short_channel_id: 13,
3830                         timestamp: 2,
3831                         flags: 0,
3832                         cltv_expiry_delta: 0,
3833                         htlc_minimum_msat: 0,
3834                         htlc_maximum_msat: OptionalField::Present(200_000),
3835                         fee_base_msat: 0,
3836                         fee_proportional_millionths: 0,
3837                         excess_data: Vec::new()
3838                 });
3839
3840                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3841                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3842                         short_channel_id: 6,
3843                         timestamp: 2,
3844                         flags: 0,
3845                         cltv_expiry_delta: 0,
3846                         htlc_minimum_msat: 0,
3847                         htlc_maximum_msat: OptionalField::Present(100_000),
3848                         fee_base_msat: 1_000,
3849                         fee_proportional_millionths: 0,
3850                         excess_data: Vec::new()
3851                 });
3852                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3853                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3854                         short_channel_id: 11,
3855                         timestamp: 2,
3856                         flags: 0,
3857                         cltv_expiry_delta: 0,
3858                         htlc_minimum_msat: 0,
3859                         htlc_maximum_msat: OptionalField::Present(100_000),
3860                         fee_base_msat: 0,
3861                         fee_proportional_millionths: 0,
3862                         excess_data: Vec::new()
3863                 });
3864
3865                 // Path via {node7, node2} is channels {12, 13, 5}.
3866                 // We already limited them to 200 sats (they are used twice for 100 sats).
3867                 // Nothing to do here.
3868
3869                 {
3870                         // Now, attempt to route 180 sats.
3871                         // Our algorithm should provide us with these 2 paths.
3872                         let route = get_route(&our_id, &payee, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3873                         assert_eq!(route.paths.len(), 2);
3874
3875                         let mut total_value_transferred_msat = 0;
3876                         let mut total_paid_msat = 0;
3877                         for path in &route.paths {
3878                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3879                                 total_value_transferred_msat += path.last().unwrap().fee_msat;
3880                                 for hop in path {
3881                                         total_paid_msat += hop.fee_msat;
3882                                 }
3883                         }
3884                         // If we paid fee, this would be higher.
3885                         assert_eq!(total_value_transferred_msat, 180_000);
3886                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3887                         assert_eq!(total_fees_paid, 0);
3888                 }
3889         }
3890
3891         #[test]
3892         fn fees_on_mpp_route_test() {
3893                 // This test makes sure that MPP algorithm properly takes into account
3894                 // fees charged on the channels, by making the fees impactful:
3895                 // if the fee is not properly accounted for, the behavior is different.
3896                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3897                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3898                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3899                 let payee = Payee::from_node_id(nodes[3]).with_features(InvoiceFeatures::known());
3900
3901                 // We need a route consisting of 2 paths:
3902                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3903                 // We will route 200 sats, Each path will have 100 sats capacity.
3904
3905                 // This test is not particularly stable: e.g.,
3906                 // there's a way to route via {node0, node2, node4}.
3907                 // It works while pathfinding is deterministic, but can be broken otherwise.
3908                 // It's fine to ignore this concern for now.
3909
3910                 // Disable other potential paths.
3911                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3912                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3913                         short_channel_id: 2,
3914                         timestamp: 2,
3915                         flags: 2,
3916                         cltv_expiry_delta: 0,
3917                         htlc_minimum_msat: 0,
3918                         htlc_maximum_msat: OptionalField::Present(100_000),
3919                         fee_base_msat: 0,
3920                         fee_proportional_millionths: 0,
3921                         excess_data: Vec::new()
3922                 });
3923
3924                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3925                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3926                         short_channel_id: 7,
3927                         timestamp: 2,
3928                         flags: 2,
3929                         cltv_expiry_delta: 0,
3930                         htlc_minimum_msat: 0,
3931                         htlc_maximum_msat: OptionalField::Present(100_000),
3932                         fee_base_msat: 0,
3933                         fee_proportional_millionths: 0,
3934                         excess_data: Vec::new()
3935                 });
3936
3937                 // Path via {node0, node2} is channels {1, 3, 5}.
3938                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3939                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3940                         short_channel_id: 1,
3941                         timestamp: 2,
3942                         flags: 0,
3943                         cltv_expiry_delta: 0,
3944                         htlc_minimum_msat: 0,
3945                         htlc_maximum_msat: OptionalField::Present(100_000),
3946                         fee_base_msat: 0,
3947                         fee_proportional_millionths: 0,
3948                         excess_data: Vec::new()
3949                 });
3950                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3951                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3952                         short_channel_id: 3,
3953                         timestamp: 2,
3954                         flags: 0,
3955                         cltv_expiry_delta: 0,
3956                         htlc_minimum_msat: 0,
3957                         htlc_maximum_msat: OptionalField::Present(100_000),
3958                         fee_base_msat: 0,
3959                         fee_proportional_millionths: 0,
3960                         excess_data: Vec::new()
3961                 });
3962
3963                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3964                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3965                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3966                         short_channel_id: 5,
3967                         timestamp: 2,
3968                         flags: 0,
3969                         cltv_expiry_delta: 0,
3970                         htlc_minimum_msat: 0,
3971                         htlc_maximum_msat: OptionalField::Present(100_000),
3972                         fee_base_msat: 0,
3973                         fee_proportional_millionths: 0,
3974                         excess_data: Vec::new()
3975                 });
3976
3977                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3978                 // All channels should be 100 sats capacity. But for the fee experiment,
3979                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3980                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3981                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3982                 // so no matter how large are other channels,
3983                 // the whole path will be limited by 100 sats with just these 2 conditions:
3984                 // - channel 12 capacity is 250 sats
3985                 // - fee for channel 6 is 150 sats
3986                 // Let's test this by enforcing these 2 conditions and removing other limits.
3987                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3988                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3989                         short_channel_id: 12,
3990                         timestamp: 2,
3991                         flags: 0,
3992                         cltv_expiry_delta: 0,
3993                         htlc_minimum_msat: 0,
3994                         htlc_maximum_msat: OptionalField::Present(250_000),
3995                         fee_base_msat: 0,
3996                         fee_proportional_millionths: 0,
3997                         excess_data: Vec::new()
3998                 });
3999                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4000                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4001                         short_channel_id: 13,
4002                         timestamp: 2,
4003                         flags: 0,
4004                         cltv_expiry_delta: 0,
4005                         htlc_minimum_msat: 0,
4006                         htlc_maximum_msat: OptionalField::Absent,
4007                         fee_base_msat: 0,
4008                         fee_proportional_millionths: 0,
4009                         excess_data: Vec::new()
4010                 });
4011
4012                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4013                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4014                         short_channel_id: 6,
4015                         timestamp: 2,
4016                         flags: 0,
4017                         cltv_expiry_delta: 0,
4018                         htlc_minimum_msat: 0,
4019                         htlc_maximum_msat: OptionalField::Absent,
4020                         fee_base_msat: 150_000,
4021                         fee_proportional_millionths: 0,
4022                         excess_data: Vec::new()
4023                 });
4024                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4025                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4026                         short_channel_id: 11,
4027                         timestamp: 2,
4028                         flags: 0,
4029                         cltv_expiry_delta: 0,
4030                         htlc_minimum_msat: 0,
4031                         htlc_maximum_msat: OptionalField::Absent,
4032                         fee_base_msat: 0,
4033                         fee_proportional_millionths: 0,
4034                         excess_data: Vec::new()
4035                 });
4036
4037                 {
4038                         // Attempt to route more than available results in a failure.
4039                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4040                                         &our_id, &payee, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4041                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4042                         } else { panic!(); }
4043                 }
4044
4045                 {
4046                         // Now, attempt to route 200 sats (exact amount we can route).
4047                         let route = get_route(&our_id, &payee, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4048                         assert_eq!(route.paths.len(), 2);
4049
4050                         let mut total_amount_paid_msat = 0;
4051                         for path in &route.paths {
4052                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4053                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
4054                         }
4055                         assert_eq!(total_amount_paid_msat, 200_000);
4056                         assert_eq!(route.get_total_fees(), 150_000);
4057                 }
4058
4059         }
4060
4061         #[test]
4062         fn drop_lowest_channel_mpp_route_test() {
4063                 // This test checks that low-capacity channel is dropped when after
4064                 // path finding we realize that we found more capacity than we need.
4065                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4066                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4067                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4068                 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4069
4070                 // We need a route consisting of 3 paths:
4071                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4072
4073                 // The first and the second paths should be sufficient, but the third should be
4074                 // cheaper, so that we select it but drop later.
4075
4076                 // First, we set limits on these (previously unlimited) channels.
4077                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4078
4079                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4080                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4081                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4082                         short_channel_id: 1,
4083                         timestamp: 2,
4084                         flags: 0,
4085                         cltv_expiry_delta: 0,
4086                         htlc_minimum_msat: 0,
4087                         htlc_maximum_msat: OptionalField::Present(100_000),
4088                         fee_base_msat: 0,
4089                         fee_proportional_millionths: 0,
4090                         excess_data: Vec::new()
4091                 });
4092                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4093                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4094                         short_channel_id: 3,
4095                         timestamp: 2,
4096                         flags: 0,
4097                         cltv_expiry_delta: 0,
4098                         htlc_minimum_msat: 0,
4099                         htlc_maximum_msat: OptionalField::Present(50_000),
4100                         fee_base_msat: 100,
4101                         fee_proportional_millionths: 0,
4102                         excess_data: Vec::new()
4103                 });
4104
4105                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4106                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4107                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4108                         short_channel_id: 12,
4109                         timestamp: 2,
4110                         flags: 0,
4111                         cltv_expiry_delta: 0,
4112                         htlc_minimum_msat: 0,
4113                         htlc_maximum_msat: OptionalField::Present(60_000),
4114                         fee_base_msat: 100,
4115                         fee_proportional_millionths: 0,
4116                         excess_data: Vec::new()
4117                 });
4118                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4119                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4120                         short_channel_id: 13,
4121                         timestamp: 2,
4122                         flags: 0,
4123                         cltv_expiry_delta: 0,
4124                         htlc_minimum_msat: 0,
4125                         htlc_maximum_msat: OptionalField::Present(60_000),
4126                         fee_base_msat: 0,
4127                         fee_proportional_millionths: 0,
4128                         excess_data: Vec::new()
4129                 });
4130
4131                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4132                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4133                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4134                         short_channel_id: 2,
4135                         timestamp: 2,
4136                         flags: 0,
4137                         cltv_expiry_delta: 0,
4138                         htlc_minimum_msat: 0,
4139                         htlc_maximum_msat: OptionalField::Present(20_000),
4140                         fee_base_msat: 0,
4141                         fee_proportional_millionths: 0,
4142                         excess_data: Vec::new()
4143                 });
4144                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4145                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4146                         short_channel_id: 4,
4147                         timestamp: 2,
4148                         flags: 0,
4149                         cltv_expiry_delta: 0,
4150                         htlc_minimum_msat: 0,
4151                         htlc_maximum_msat: OptionalField::Present(20_000),
4152                         fee_base_msat: 0,
4153                         fee_proportional_millionths: 0,
4154                         excess_data: Vec::new()
4155                 });
4156
4157                 {
4158                         // Attempt to route more than available results in a failure.
4159                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4160                                         &our_id, &payee, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4161                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4162                         } else { panic!(); }
4163                 }
4164
4165                 {
4166                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4167                         // Our algorithm should provide us with these 3 paths.
4168                         let route = get_route(&our_id, &payee, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4169                         assert_eq!(route.paths.len(), 3);
4170                         let mut total_amount_paid_msat = 0;
4171                         for path in &route.paths {
4172                                 assert_eq!(path.len(), 2);
4173                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4174                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
4175                         }
4176                         assert_eq!(total_amount_paid_msat, 125_000);
4177                 }
4178
4179                 {
4180                         // Attempt to route without the last small cheap channel
4181                         let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4182                         assert_eq!(route.paths.len(), 2);
4183                         let mut total_amount_paid_msat = 0;
4184                         for path in &route.paths {
4185                                 assert_eq!(path.len(), 2);
4186                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4187                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
4188                         }
4189                         assert_eq!(total_amount_paid_msat, 90_000);
4190                 }
4191         }
4192
4193         #[test]
4194         fn min_criteria_consistency() {
4195                 // Test that we don't use an inconsistent metric between updating and walking nodes during
4196                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4197                 // was updated with a different criterion from the heap sorting, resulting in loops in
4198                 // calculated paths. We test for that specific case here.
4199
4200                 // We construct a network that looks like this:
4201                 //
4202                 //            node2 -1(3)2- node3
4203                 //              2          2
4204                 //               (2)     (4)
4205                 //                  1   1
4206                 //    node1 -1(5)2- node4 -1(1)2- node6
4207                 //    2
4208                 //   (6)
4209                 //        1
4210                 // our_node
4211                 //
4212                 // We create a loop on the side of our real path - our destination is node 6, with a
4213                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4214                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4215                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4216                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4217                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4218                 // "previous hop" being set to node 3, creating a loop in the path.
4219                 let secp_ctx = Secp256k1::new();
4220                 let logger = Arc::new(test_utils::TestLogger::new());
4221                 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4222                 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4223                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4224                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4225                 let payee = Payee::from_node_id(nodes[6]);
4226
4227                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4228                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4229                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4230                         short_channel_id: 6,
4231                         timestamp: 1,
4232                         flags: 0,
4233                         cltv_expiry_delta: (6 << 8) | 0,
4234                         htlc_minimum_msat: 0,
4235                         htlc_maximum_msat: OptionalField::Absent,
4236                         fee_base_msat: 0,
4237                         fee_proportional_millionths: 0,
4238                         excess_data: Vec::new()
4239                 });
4240                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4241
4242                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4243                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4244                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4245                         short_channel_id: 5,
4246                         timestamp: 1,
4247                         flags: 0,
4248                         cltv_expiry_delta: (5 << 8) | 0,
4249                         htlc_minimum_msat: 0,
4250                         htlc_maximum_msat: OptionalField::Absent,
4251                         fee_base_msat: 100,
4252                         fee_proportional_millionths: 0,
4253                         excess_data: Vec::new()
4254                 });
4255                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4256
4257                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4258                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4259                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260                         short_channel_id: 4,
4261                         timestamp: 1,
4262                         flags: 0,
4263                         cltv_expiry_delta: (4 << 8) | 0,
4264                         htlc_minimum_msat: 0,
4265                         htlc_maximum_msat: OptionalField::Absent,
4266                         fee_base_msat: 0,
4267                         fee_proportional_millionths: 0,
4268                         excess_data: Vec::new()
4269                 });
4270                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4271
4272                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4273                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4274                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4275                         short_channel_id: 3,
4276                         timestamp: 1,
4277                         flags: 0,
4278                         cltv_expiry_delta: (3 << 8) | 0,
4279                         htlc_minimum_msat: 0,
4280                         htlc_maximum_msat: OptionalField::Absent,
4281                         fee_base_msat: 0,
4282                         fee_proportional_millionths: 0,
4283                         excess_data: Vec::new()
4284                 });
4285                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4286
4287                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4288                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4289                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4290                         short_channel_id: 2,
4291                         timestamp: 1,
4292                         flags: 0,
4293                         cltv_expiry_delta: (2 << 8) | 0,
4294                         htlc_minimum_msat: 0,
4295                         htlc_maximum_msat: OptionalField::Absent,
4296                         fee_base_msat: 0,
4297                         fee_proportional_millionths: 0,
4298                         excess_data: Vec::new()
4299                 });
4300
4301                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4302                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4303                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4304                         short_channel_id: 1,
4305                         timestamp: 1,
4306                         flags: 0,
4307                         cltv_expiry_delta: (1 << 8) | 0,
4308                         htlc_minimum_msat: 100,
4309                         htlc_maximum_msat: OptionalField::Absent,
4310                         fee_base_msat: 0,
4311                         fee_proportional_millionths: 0,
4312                         excess_data: Vec::new()
4313                 });
4314                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4315
4316                 {
4317                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
4318                         let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4319                         assert_eq!(route.paths.len(), 1);
4320                         assert_eq!(route.paths[0].len(), 3);
4321
4322                         assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4323                         assert_eq!(route.paths[0][0].short_channel_id, 6);
4324                         assert_eq!(route.paths[0][0].fee_msat, 100);
4325                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4326                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4327                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4328
4329                         assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4330                         assert_eq!(route.paths[0][1].short_channel_id, 5);
4331                         assert_eq!(route.paths[0][1].fee_msat, 0);
4332                         assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4333                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4334                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4335
4336                         assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4337                         assert_eq!(route.paths[0][2].short_channel_id, 1);
4338                         assert_eq!(route.paths[0][2].fee_msat, 10_000);
4339                         assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4340                         assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4341                         assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4342                 }
4343         }
4344
4345
4346         #[test]
4347         fn exact_fee_liquidity_limit() {
4348                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4349                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4350                 // we calculated fees on a higher value, resulting in us ignoring such paths.
4351                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4352                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4353                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4354                 let payee = Payee::from_node_id(nodes[2]);
4355
4356                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4357                 // send.
4358                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4359                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4360                         short_channel_id: 2,
4361                         timestamp: 2,
4362                         flags: 0,
4363                         cltv_expiry_delta: 0,
4364                         htlc_minimum_msat: 0,
4365                         htlc_maximum_msat: OptionalField::Present(85_000),
4366                         fee_base_msat: 0,
4367                         fee_proportional_millionths: 0,
4368                         excess_data: Vec::new()
4369                 });
4370
4371                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4372                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4373                         short_channel_id: 12,
4374                         timestamp: 2,
4375                         flags: 0,
4376                         cltv_expiry_delta: (4 << 8) | 1,
4377                         htlc_minimum_msat: 0,
4378                         htlc_maximum_msat: OptionalField::Present(270_000),
4379                         fee_base_msat: 0,
4380                         fee_proportional_millionths: 1000000,
4381                         excess_data: Vec::new()
4382                 });
4383
4384                 {
4385                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4386                         // 200% fee charged channel 13 in the 1-to-2 direction.
4387                         let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4388                         assert_eq!(route.paths.len(), 1);
4389                         assert_eq!(route.paths[0].len(), 2);
4390
4391                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4392                         assert_eq!(route.paths[0][0].short_channel_id, 12);
4393                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4394                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4395                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4396                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4397
4398                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4399                         assert_eq!(route.paths[0][1].short_channel_id, 13);
4400                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
4401                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4402                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4403                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4404                 }
4405         }
4406
4407         #[test]
4408         fn htlc_max_reduction_below_min() {
4409                 // Test that if, while walking the graph, we reduce the value being sent to meet an
4410                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4411                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4412                 // resulting in us thinking there is no possible path, even if other paths exist.
4413                 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4414                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4415                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4416                 let payee = Payee::from_node_id(nodes[2]).with_features(InvoiceFeatures::known());
4417
4418                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4419                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4420                 // then try to send 90_000.
4421                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4422                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4423                         short_channel_id: 2,
4424                         timestamp: 2,
4425                         flags: 0,
4426                         cltv_expiry_delta: 0,
4427                         htlc_minimum_msat: 0,
4428                         htlc_maximum_msat: OptionalField::Present(80_000),
4429                         fee_base_msat: 0,
4430                         fee_proportional_millionths: 0,
4431                         excess_data: Vec::new()
4432                 });
4433                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4434                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4435                         short_channel_id: 4,
4436                         timestamp: 2,
4437                         flags: 0,
4438                         cltv_expiry_delta: (4 << 8) | 1,
4439                         htlc_minimum_msat: 90_000,
4440                         htlc_maximum_msat: OptionalField::Absent,
4441                         fee_base_msat: 0,
4442                         fee_proportional_millionths: 0,
4443                         excess_data: Vec::new()
4444                 });
4445
4446                 {
4447                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4448                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4449                         // expensive) channels 12-13 path.
4450                         let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4451                         assert_eq!(route.paths.len(), 1);
4452                         assert_eq!(route.paths[0].len(), 2);
4453
4454                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4455                         assert_eq!(route.paths[0][0].short_channel_id, 12);
4456                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4457                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4458                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4459                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4460
4461                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4462                         assert_eq!(route.paths[0][1].short_channel_id, 13);
4463                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
4464                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4465                         assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4466                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4467                 }
4468         }
4469
4470         #[test]
4471         fn multiple_direct_first_hops() {
4472                 // Previously we'd only ever considered one first hop path per counterparty.
4473                 // However, as we don't restrict users to one channel per peer, we really need to support
4474                 // looking at all first hop paths.
4475                 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4476                 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4477                 // route over multiple channels with the same first hop.
4478                 let secp_ctx = Secp256k1::new();
4479                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4480                 let logger = Arc::new(test_utils::TestLogger::new());
4481                 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4482                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4483                 let payee = Payee::from_node_id(nodes[0]).with_features(InvoiceFeatures::known());
4484
4485                 {
4486                         let route = get_route(&our_id, &payee, &network_graph, Some(&[
4487                                 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4488                                 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4489                         ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4490                         assert_eq!(route.paths.len(), 1);
4491                         assert_eq!(route.paths[0].len(), 1);
4492
4493                         assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4494                         assert_eq!(route.paths[0][0].short_channel_id, 3);
4495                         assert_eq!(route.paths[0][0].fee_msat, 100_000);
4496                 }
4497                 {
4498                         let route = get_route(&our_id, &payee, &network_graph, Some(&[
4499                                 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4500                                 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4501                         ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4502                         assert_eq!(route.paths.len(), 2);
4503                         assert_eq!(route.paths[0].len(), 1);
4504                         assert_eq!(route.paths[1].len(), 1);
4505
4506                         assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4507                         assert_eq!(route.paths[0][0].short_channel_id, 3);
4508                         assert_eq!(route.paths[0][0].fee_msat, 50_000);
4509
4510                         assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4511                         assert_eq!(route.paths[1][0].short_channel_id, 2);
4512                         assert_eq!(route.paths[1][0].fee_msat, 50_000);
4513                 }
4514         }
4515
4516         #[test]
4517         fn prefers_shorter_route_with_higher_fees() {
4518                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4519                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4520                 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4521
4522                 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4523                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4524                 let route = get_route(
4525                         &our_id, &payee, &network_graph, None, 100, 42,
4526                         Arc::clone(&logger), &scorer
4527                 ).unwrap();
4528                 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4529
4530                 assert_eq!(route.get_total_fees(), 100);
4531                 assert_eq!(route.get_total_amount(), 100);
4532                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4533
4534                 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4535                 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4536                 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4537                 let route = get_route(
4538                         &our_id, &payee, &network_graph, None, 100, 42,
4539                         Arc::clone(&logger), &scorer
4540                 ).unwrap();
4541                 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4542
4543                 assert_eq!(route.get_total_fees(), 300);
4544                 assert_eq!(route.get_total_amount(), 100);
4545                 assert_eq!(path, vec![2, 4, 7, 10]);
4546         }
4547
4548         struct BadChannelScorer {
4549                 short_channel_id: u64,
4550         }
4551
4552         impl routing::Score for BadChannelScorer {
4553                 fn channel_penalty_msat(&self, short_channel_id: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4554                         if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4555                 }
4556
4557                 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4558         }
4559
4560         struct BadNodeScorer {
4561                 node_id: NodeId,
4562         }
4563
4564         impl routing::Score for BadNodeScorer {
4565                 fn channel_penalty_msat(&self, _short_channel_id: u64, _source: &NodeId, target: &NodeId) -> u64 {
4566                         if *target == self.node_id { u64::max_value() } else { 0 }
4567                 }
4568
4569                 fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
4570         }
4571
4572         #[test]
4573         fn avoids_routing_through_bad_channels_and_nodes() {
4574                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4575                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4576                 let payee = Payee::from_node_id(nodes[6]).with_route_hints(last_hops(&nodes));
4577
4578                 // A path to nodes[6] exists when no penalties are applied to any channel.
4579                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4580                 let route = get_route(
4581                         &our_id, &payee, &network_graph, None, 100, 42,
4582                         Arc::clone(&logger), &scorer
4583                 ).unwrap();
4584                 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4585
4586                 assert_eq!(route.get_total_fees(), 100);
4587                 assert_eq!(route.get_total_amount(), 100);
4588                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4589
4590                 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4591                 let scorer = BadChannelScorer { short_channel_id: 6 };
4592                 let route = get_route(
4593                         &our_id, &payee, &network_graph, None, 100, 42,
4594                         Arc::clone(&logger), &scorer
4595                 ).unwrap();
4596                 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4597
4598                 assert_eq!(route.get_total_fees(), 300);
4599                 assert_eq!(route.get_total_amount(), 100);
4600                 assert_eq!(path, vec![2, 4, 7, 10]);
4601
4602                 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4603                 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4604                 match get_route(
4605                         &our_id, &payee, &network_graph, None, 100, 42,
4606                         Arc::clone(&logger), &scorer
4607                 ) {
4608                         Err(LightningError { err, .. } ) => {
4609                                 assert_eq!(err, "Failed to find a path to the given destination");
4610                         },
4611                         Ok(_) => panic!("Expected error"),
4612                 }
4613         }
4614
4615         #[test]
4616         fn total_fees_single_path() {
4617                 let route = Route {
4618                         paths: vec![vec![
4619                                 RouteHop {
4620                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4621                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4622                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4623                                 },
4624                                 RouteHop {
4625                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4626                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4627                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4628                                 },
4629                                 RouteHop {
4630                                         pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4631                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4632                                         short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4633                                 },
4634                         ]],
4635                         payee: None,
4636                 };
4637
4638                 assert_eq!(route.get_total_fees(), 250);
4639                 assert_eq!(route.get_total_amount(), 225);
4640         }
4641
4642         #[test]
4643         fn total_fees_multi_path() {
4644                 let route = Route {
4645                         paths: vec![vec![
4646                                 RouteHop {
4647                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4648                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4649                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4650                                 },
4651                                 RouteHop {
4652                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4653                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4654                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4655                                 },
4656                         ],vec![
4657                                 RouteHop {
4658                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4659                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4660                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4661                                 },
4662                                 RouteHop {
4663                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4664                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4665                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4666                                 },
4667                         ]],
4668                         payee: None,
4669                 };
4670
4671                 assert_eq!(route.get_total_fees(), 200);
4672                 assert_eq!(route.get_total_amount(), 300);
4673         }
4674
4675         #[test]
4676         fn total_empty_route_no_panic() {
4677                 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4678                 // would both panic if the route was completely empty. We test to ensure they return 0
4679                 // here, even though its somewhat nonsensical as a route.
4680                 let route = Route { paths: Vec::new(), payee: None };
4681
4682                 assert_eq!(route.get_total_fees(), 0);
4683                 assert_eq!(route.get_total_amount(), 0);
4684         }
4685
4686         #[cfg(not(feature = "no-std"))]
4687         pub(super) fn random_init_seed() -> u64 {
4688                 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4689                 use core::hash::{BuildHasher, Hasher};
4690                 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4691                 println!("Using seed of {}", seed);
4692                 seed
4693         }
4694         #[cfg(not(feature = "no-std"))]
4695         use util::ser::Readable;
4696
4697         #[test]
4698         #[cfg(not(feature = "no-std"))]
4699         fn generate_routes() {
4700                 let mut d = match super::test_utils::get_route_file() {
4701                         Ok(f) => f,
4702                         Err(e) => {
4703                                 eprintln!("{}", e);
4704                                 return;
4705                         },
4706                 };
4707                 let graph = NetworkGraph::read(&mut d).unwrap();
4708                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4709
4710                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4711                 let mut seed = random_init_seed() as usize;
4712                 let nodes = graph.read_only().nodes().clone();
4713                 'load_endpoints: for _ in 0..10 {
4714                         loop {
4715                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4716                                 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4717                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4718                                 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4719                                 let payee = Payee::from_node_id(dst);
4720                                 let amt = seed as u64 % 200_000_000;
4721                                 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4722                                         continue 'load_endpoints;
4723                                 }
4724                         }
4725                 }
4726         }
4727
4728         #[test]
4729         #[cfg(not(feature = "no-std"))]
4730         fn generate_routes_mpp() {
4731                 let mut d = match super::test_utils::get_route_file() {
4732                         Ok(f) => f,
4733                         Err(e) => {
4734                                 eprintln!("{}", e);
4735                                 return;
4736                         },
4737                 };
4738                 let graph = NetworkGraph::read(&mut d).unwrap();
4739                 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4740
4741                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4742                 let mut seed = random_init_seed() as usize;
4743                 let nodes = graph.read_only().nodes().clone();
4744                 'load_endpoints: for _ in 0..10 {
4745                         loop {
4746                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4747                                 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4748                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4749                                 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4750                                 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4751                                 let amt = seed as u64 % 200_000_000;
4752                                 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4753                                         continue 'load_endpoints;
4754                                 }
4755                         }
4756                 }
4757         }
4758 }
4759
4760 #[cfg(all(test, not(feature = "no-std")))]
4761 pub(crate) mod test_utils {
4762         use std::fs::File;
4763         /// Tries to open a network graph file, or panics with a URL to fetch it.
4764         pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4765                 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4766                         .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4767                         .or_else(|_| { // Fall back to guessing based on the binary location
4768                                 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4769                                 let mut path = std::env::current_exe().unwrap();
4770                                 path.pop(); // lightning-...
4771                                 path.pop(); // deps
4772                                 path.pop(); // debug
4773                                 path.pop(); // target
4774                                 path.push("lightning");
4775                                 path.push("net_graph-2021-05-31.bin");
4776                                 eprintln!("{}", path.to_str().unwrap());
4777                                 File::open(path)
4778                         })
4779                 .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");
4780                 #[cfg(require_route_graph_test)]
4781                 return Ok(res.unwrap());
4782                 #[cfg(not(require_route_graph_test))]
4783                 return res;
4784         }
4785 }
4786
4787 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4788 mod benches {
4789         use super::*;
4790         use routing::scorer::Scorer;
4791         use util::logger::{Logger, Record};
4792
4793         use test::Bencher;
4794
4795         struct DummyLogger {}
4796         impl Logger for DummyLogger {
4797                 fn log(&self, _record: &Record) {}
4798         }
4799
4800         #[bench]
4801         fn generate_routes(bench: &mut Bencher) {
4802                 let mut d = test_utils::get_route_file().unwrap();
4803                 let graph = NetworkGraph::read(&mut d).unwrap();
4804                 let nodes = graph.read_only().nodes().clone();
4805                 let scorer = Scorer::with_fixed_penalty(0);
4806
4807                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4808                 let mut path_endpoints = Vec::new();
4809                 let mut seed: usize = 0xdeadbeef;
4810                 'load_endpoints: for _ in 0..100 {
4811                         loop {
4812                                 seed *= 0xdeadbeef;
4813                                 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4814                                 seed *= 0xdeadbeef;
4815                                 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4816                                 let payee = Payee::from_node_id(dst);
4817                                 let amt = seed as u64 % 1_000_000;
4818                                 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4819                                         path_endpoints.push((src, dst, amt));
4820                                         continue 'load_endpoints;
4821                                 }
4822                         }
4823                 }
4824
4825                 // ...then benchmark finding paths between the nodes we learned.
4826                 let mut idx = 0;
4827                 bench.iter(|| {
4828                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4829                         let payee = Payee::from_node_id(dst);
4830                         assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4831                         idx += 1;
4832                 });
4833         }
4834
4835         #[bench]
4836         fn generate_mpp_routes(bench: &mut Bencher) {
4837                 let mut d = test_utils::get_route_file().unwrap();
4838                 let graph = NetworkGraph::read(&mut d).unwrap();
4839                 let nodes = graph.read_only().nodes().clone();
4840                 let scorer = Scorer::with_fixed_penalty(0);
4841
4842                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4843                 let mut path_endpoints = Vec::new();
4844                 let mut seed: usize = 0xdeadbeef;
4845                 'load_endpoints: for _ in 0..100 {
4846                         loop {
4847                                 seed *= 0xdeadbeef;
4848                                 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4849                                 seed *= 0xdeadbeef;
4850                                 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4851                                 let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4852                                 let amt = seed as u64 % 1_000_000;
4853                                 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4854                                         path_endpoints.push((src, dst, amt));
4855                                         continue 'load_endpoints;
4856                                 }
4857                         }
4858                 }
4859
4860                 // ...then benchmark finding paths between the nodes we learned.
4861                 let mut idx = 0;
4862                 bench.iter(|| {
4863                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4864                         let payee = Payee::from_node_id(dst).with_features(InvoiceFeatures::known());
4865                         assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4866                         idx += 1;
4867                 });
4868         }
4869 }