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