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