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