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