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