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