2973878a4d4db239b0a6d8d9f96ff1fc71ba54d5
[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::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2687         use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2688         use crate::ln::channelmanager;
2689         use crate::offers::invoice::BlindedPayInfo;
2690         use crate::util::config::UserConfig;
2691         use crate::util::test_utils as ln_test_utils;
2692         use crate::util::chacha20::ChaCha20;
2693         use crate::util::ser::{Readable, Writeable};
2694         #[cfg(c_bindings)]
2695         use crate::util::ser::Writer;
2696
2697         use bitcoin::hashes::Hash;
2698         use bitcoin::network::constants::Network;
2699         use bitcoin::blockdata::constants::genesis_block;
2700         use bitcoin::blockdata::script::Builder;
2701         use bitcoin::blockdata::opcodes;
2702         use bitcoin::blockdata::transaction::TxOut;
2703
2704         use hex;
2705
2706         use bitcoin::secp256k1::{PublicKey,SecretKey};
2707         use bitcoin::secp256k1::Secp256k1;
2708
2709         use crate::io::Cursor;
2710         use crate::prelude::*;
2711         use crate::sync::Arc;
2712
2713         use core::convert::TryInto;
2714
2715         fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2716                         features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2717                 channelmanager::ChannelDetails {
2718                         channel_id: [0; 32],
2719                         counterparty: channelmanager::ChannelCounterparty {
2720                                 features,
2721                                 node_id,
2722                                 unspendable_punishment_reserve: 0,
2723                                 forwarding_info: None,
2724                                 outbound_htlc_minimum_msat: None,
2725                                 outbound_htlc_maximum_msat: None,
2726                         },
2727                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2728                         channel_type: None,
2729                         short_channel_id,
2730                         outbound_scid_alias: None,
2731                         inbound_scid_alias: None,
2732                         channel_value_satoshis: 0,
2733                         user_channel_id: 0,
2734                         outbound_capacity_msat,
2735                         next_outbound_htlc_limit_msat: outbound_capacity_msat,
2736                         next_outbound_htlc_minimum_msat: 0,
2737                         inbound_capacity_msat: 42,
2738                         unspendable_punishment_reserve: None,
2739                         confirmations_required: None,
2740                         confirmations: None,
2741                         force_close_spend_delay: None,
2742                         is_outbound: true, is_channel_ready: true,
2743                         is_usable: true, is_public: true,
2744                         inbound_htlc_minimum_msat: None,
2745                         inbound_htlc_maximum_msat: None,
2746                         config: None,
2747                         feerate_sat_per_1000_weight: None,
2748                         channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2749                 }
2750         }
2751
2752         #[test]
2753         fn simple_route_test() {
2754                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2755                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2756                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2757                 let scorer = ln_test_utils::TestScorer::new();
2758                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2759                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2760
2761                 // Simple route to 2 via 1
2762
2763                 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) {
2764                         assert_eq!(err, "Cannot send a payment of 0 msat");
2765                 } else { panic!(); }
2766
2767                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2768                 assert_eq!(route.paths[0].hops.len(), 2);
2769
2770                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2771                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2772                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2773                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2774                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2775                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2776
2777                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2778                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2779                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2780                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2781                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2782                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2783         }
2784
2785         #[test]
2786         fn invalid_first_hop_test() {
2787                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2788                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2789                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2790                 let scorer = ln_test_utils::TestScorer::new();
2791                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2792                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2793
2794                 // Simple route to 2 via 1
2795
2796                 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2797
2798                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2799                         get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2800                         assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2801                 } else { panic!(); }
2802
2803                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2804                 assert_eq!(route.paths[0].hops.len(), 2);
2805         }
2806
2807         #[test]
2808         fn htlc_minimum_test() {
2809                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2810                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2811                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2812                 let scorer = ln_test_utils::TestScorer::new();
2813                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2814                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2815
2816                 // Simple route to 2 via 1
2817
2818                 // Disable other paths
2819                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2820                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2821                         short_channel_id: 12,
2822                         timestamp: 2,
2823                         flags: 2, // to disable
2824                         cltv_expiry_delta: 0,
2825                         htlc_minimum_msat: 0,
2826                         htlc_maximum_msat: MAX_VALUE_MSAT,
2827                         fee_base_msat: 0,
2828                         fee_proportional_millionths: 0,
2829                         excess_data: Vec::new()
2830                 });
2831                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2832                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2833                         short_channel_id: 3,
2834                         timestamp: 2,
2835                         flags: 2, // to disable
2836                         cltv_expiry_delta: 0,
2837                         htlc_minimum_msat: 0,
2838                         htlc_maximum_msat: MAX_VALUE_MSAT,
2839                         fee_base_msat: 0,
2840                         fee_proportional_millionths: 0,
2841                         excess_data: Vec::new()
2842                 });
2843                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2844                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2845                         short_channel_id: 13,
2846                         timestamp: 2,
2847                         flags: 2, // to disable
2848                         cltv_expiry_delta: 0,
2849                         htlc_minimum_msat: 0,
2850                         htlc_maximum_msat: MAX_VALUE_MSAT,
2851                         fee_base_msat: 0,
2852                         fee_proportional_millionths: 0,
2853                         excess_data: Vec::new()
2854                 });
2855                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2856                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2857                         short_channel_id: 6,
2858                         timestamp: 2,
2859                         flags: 2, // to disable
2860                         cltv_expiry_delta: 0,
2861                         htlc_minimum_msat: 0,
2862                         htlc_maximum_msat: MAX_VALUE_MSAT,
2863                         fee_base_msat: 0,
2864                         fee_proportional_millionths: 0,
2865                         excess_data: Vec::new()
2866                 });
2867                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2868                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2869                         short_channel_id: 7,
2870                         timestamp: 2,
2871                         flags: 2, // to disable
2872                         cltv_expiry_delta: 0,
2873                         htlc_minimum_msat: 0,
2874                         htlc_maximum_msat: MAX_VALUE_MSAT,
2875                         fee_base_msat: 0,
2876                         fee_proportional_millionths: 0,
2877                         excess_data: Vec::new()
2878                 });
2879
2880                 // Check against amount_to_transfer_over_msat.
2881                 // Set minimal HTLC of 200_000_000 msat.
2882                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2883                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2884                         short_channel_id: 2,
2885                         timestamp: 3,
2886                         flags: 0,
2887                         cltv_expiry_delta: 0,
2888                         htlc_minimum_msat: 200_000_000,
2889                         htlc_maximum_msat: MAX_VALUE_MSAT,
2890                         fee_base_msat: 0,
2891                         fee_proportional_millionths: 0,
2892                         excess_data: Vec::new()
2893                 });
2894
2895                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2896                 // be used.
2897                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2898                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2899                         short_channel_id: 4,
2900                         timestamp: 3,
2901                         flags: 0,
2902                         cltv_expiry_delta: 0,
2903                         htlc_minimum_msat: 0,
2904                         htlc_maximum_msat: 199_999_999,
2905                         fee_base_msat: 0,
2906                         fee_proportional_millionths: 0,
2907                         excess_data: Vec::new()
2908                 });
2909
2910                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2911                 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) {
2912                         assert_eq!(err, "Failed to find a path to the given destination");
2913                 } else { panic!(); }
2914
2915                 // Lift the restriction on the first hop.
2916                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2917                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2918                         short_channel_id: 2,
2919                         timestamp: 4,
2920                         flags: 0,
2921                         cltv_expiry_delta: 0,
2922                         htlc_minimum_msat: 0,
2923                         htlc_maximum_msat: MAX_VALUE_MSAT,
2924                         fee_base_msat: 0,
2925                         fee_proportional_millionths: 0,
2926                         excess_data: Vec::new()
2927                 });
2928
2929                 // A payment above the minimum should pass
2930                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2931                 assert_eq!(route.paths[0].hops.len(), 2);
2932         }
2933
2934         #[test]
2935         fn htlc_minimum_overpay_test() {
2936                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2937                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2938                 let config = UserConfig::default();
2939                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2940                 let scorer = ln_test_utils::TestScorer::new();
2941                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2942                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2943
2944                 // A route to node#2 via two paths.
2945                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2946                 // Thus, they can't send 60 without overpaying.
2947                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2948                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2949                         short_channel_id: 2,
2950                         timestamp: 2,
2951                         flags: 0,
2952                         cltv_expiry_delta: 0,
2953                         htlc_minimum_msat: 35_000,
2954                         htlc_maximum_msat: 40_000,
2955                         fee_base_msat: 0,
2956                         fee_proportional_millionths: 0,
2957                         excess_data: Vec::new()
2958                 });
2959                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2960                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2961                         short_channel_id: 12,
2962                         timestamp: 3,
2963                         flags: 0,
2964                         cltv_expiry_delta: 0,
2965                         htlc_minimum_msat: 35_000,
2966                         htlc_maximum_msat: 40_000,
2967                         fee_base_msat: 0,
2968                         fee_proportional_millionths: 0,
2969                         excess_data: Vec::new()
2970                 });
2971
2972                 // Make 0 fee.
2973                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2974                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2975                         short_channel_id: 13,
2976                         timestamp: 2,
2977                         flags: 0,
2978                         cltv_expiry_delta: 0,
2979                         htlc_minimum_msat: 0,
2980                         htlc_maximum_msat: MAX_VALUE_MSAT,
2981                         fee_base_msat: 0,
2982                         fee_proportional_millionths: 0,
2983                         excess_data: Vec::new()
2984                 });
2985                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2986                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2987                         short_channel_id: 4,
2988                         timestamp: 2,
2989                         flags: 0,
2990                         cltv_expiry_delta: 0,
2991                         htlc_minimum_msat: 0,
2992                         htlc_maximum_msat: MAX_VALUE_MSAT,
2993                         fee_base_msat: 0,
2994                         fee_proportional_millionths: 0,
2995                         excess_data: Vec::new()
2996                 });
2997
2998                 // Disable other paths
2999                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3000                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3001                         short_channel_id: 1,
3002                         timestamp: 3,
3003                         flags: 2, // to disable
3004                         cltv_expiry_delta: 0,
3005                         htlc_minimum_msat: 0,
3006                         htlc_maximum_msat: MAX_VALUE_MSAT,
3007                         fee_base_msat: 0,
3008                         fee_proportional_millionths: 0,
3009                         excess_data: Vec::new()
3010                 });
3011
3012                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3013                 // Overpay fees to hit htlc_minimum_msat.
3014                 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3015                 // TODO: this could be better balanced to overpay 10k and not 15k.
3016                 assert_eq!(overpaid_fees, 15_000);
3017
3018                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3019                 // while taking even more fee to match htlc_minimum_msat.
3020                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3021                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3022                         short_channel_id: 12,
3023                         timestamp: 4,
3024                         flags: 0,
3025                         cltv_expiry_delta: 0,
3026                         htlc_minimum_msat: 65_000,
3027                         htlc_maximum_msat: 80_000,
3028                         fee_base_msat: 0,
3029                         fee_proportional_millionths: 0,
3030                         excess_data: Vec::new()
3031                 });
3032                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3033                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3034                         short_channel_id: 2,
3035                         timestamp: 3,
3036                         flags: 0,
3037                         cltv_expiry_delta: 0,
3038                         htlc_minimum_msat: 0,
3039                         htlc_maximum_msat: MAX_VALUE_MSAT,
3040                         fee_base_msat: 0,
3041                         fee_proportional_millionths: 0,
3042                         excess_data: Vec::new()
3043                 });
3044                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3045                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3046                         short_channel_id: 4,
3047                         timestamp: 4,
3048                         flags: 0,
3049                         cltv_expiry_delta: 0,
3050                         htlc_minimum_msat: 0,
3051                         htlc_maximum_msat: MAX_VALUE_MSAT,
3052                         fee_base_msat: 0,
3053                         fee_proportional_millionths: 100_000,
3054                         excess_data: Vec::new()
3055                 });
3056
3057                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3058                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3059                 assert_eq!(route.paths.len(), 1);
3060                 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3061                 let fees = route.paths[0].hops[0].fee_msat;
3062                 assert_eq!(fees, 5_000);
3063
3064                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3065                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3066                 // the other channel.
3067                 assert_eq!(route.paths.len(), 1);
3068                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3069                 let fees = route.paths[0].hops[0].fee_msat;
3070                 assert_eq!(fees, 5_000);
3071         }
3072
3073         #[test]
3074         fn disable_channels_test() {
3075                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3076                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3077                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3078                 let scorer = ln_test_utils::TestScorer::new();
3079                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3080                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3081
3082                 // // Disable channels 4 and 12 by flags=2
3083                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3084                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3085                         short_channel_id: 4,
3086                         timestamp: 2,
3087                         flags: 2, // to disable
3088                         cltv_expiry_delta: 0,
3089                         htlc_minimum_msat: 0,
3090                         htlc_maximum_msat: MAX_VALUE_MSAT,
3091                         fee_base_msat: 0,
3092                         fee_proportional_millionths: 0,
3093                         excess_data: Vec::new()
3094                 });
3095                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3096                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3097                         short_channel_id: 12,
3098                         timestamp: 2,
3099                         flags: 2, // to disable
3100                         cltv_expiry_delta: 0,
3101                         htlc_minimum_msat: 0,
3102                         htlc_maximum_msat: MAX_VALUE_MSAT,
3103                         fee_base_msat: 0,
3104                         fee_proportional_millionths: 0,
3105                         excess_data: Vec::new()
3106                 });
3107
3108                 // If all the channels require some features we don't understand, route should fail
3109                 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) {
3110                         assert_eq!(err, "Failed to find a path to the given destination");
3111                 } else { panic!(); }
3112
3113                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3114                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3115                 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();
3116                 assert_eq!(route.paths[0].hops.len(), 2);
3117
3118                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3119                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3120                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3121                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3122                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3123                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3124
3125                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3126                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3127                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3128                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3129                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3130                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3131         }
3132
3133         #[test]
3134         fn disable_node_test() {
3135                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3136                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3137                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3138                 let scorer = ln_test_utils::TestScorer::new();
3139                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3140                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3141
3142                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3143                 let mut unknown_features = NodeFeatures::empty();
3144                 unknown_features.set_unknown_feature_required();
3145                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3146                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3147                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3148
3149                 // If all nodes require some features we don't understand, route should fail
3150                 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) {
3151                         assert_eq!(err, "Failed to find a path to the given destination");
3152                 } else { panic!(); }
3153
3154                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3155                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3156                 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();
3157                 assert_eq!(route.paths[0].hops.len(), 2);
3158
3159                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3160                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3161                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3162                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3163                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3164                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3165
3166                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3167                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3168                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3169                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3170                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3171                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3172
3173                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3174                 // naively) assume that the user checked the feature bits on the invoice, which override
3175                 // the node_announcement.
3176         }
3177
3178         #[test]
3179         fn our_chans_test() {
3180                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3181                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3182                 let scorer = ln_test_utils::TestScorer::new();
3183                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3184                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3185
3186                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3187                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3188                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3189                 assert_eq!(route.paths[0].hops.len(), 3);
3190
3191                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3192                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3193                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3194                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3195                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3196                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3197
3198                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3199                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3200                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3201                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3202                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3203                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3204
3205                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3206                 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3207                 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3208                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3209                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3210                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3211
3212                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3213                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3214                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3215                 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();
3216                 assert_eq!(route.paths[0].hops.len(), 2);
3217
3218                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3219                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3220                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3221                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3222                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3223                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3224
3225                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3226                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3227                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3228                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3229                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3230                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3231         }
3232
3233         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3234                 let zero_fees = RoutingFees {
3235                         base_msat: 0,
3236                         proportional_millionths: 0,
3237                 };
3238                 vec![RouteHint(vec![RouteHintHop {
3239                         src_node_id: nodes[3],
3240                         short_channel_id: 8,
3241                         fees: zero_fees,
3242                         cltv_expiry_delta: (8 << 4) | 1,
3243                         htlc_minimum_msat: None,
3244                         htlc_maximum_msat: None,
3245                 }
3246                 ]), RouteHint(vec![RouteHintHop {
3247                         src_node_id: nodes[4],
3248                         short_channel_id: 9,
3249                         fees: RoutingFees {
3250                                 base_msat: 1001,
3251                                 proportional_millionths: 0,
3252                         },
3253                         cltv_expiry_delta: (9 << 4) | 1,
3254                         htlc_minimum_msat: None,
3255                         htlc_maximum_msat: None,
3256                 }]), RouteHint(vec![RouteHintHop {
3257                         src_node_id: nodes[5],
3258                         short_channel_id: 10,
3259                         fees: zero_fees,
3260                         cltv_expiry_delta: (10 << 4) | 1,
3261                         htlc_minimum_msat: None,
3262                         htlc_maximum_msat: None,
3263                 }])]
3264         }
3265
3266         fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3267                 let zero_fees = RoutingFees {
3268                         base_msat: 0,
3269                         proportional_millionths: 0,
3270                 };
3271                 vec![RouteHint(vec![RouteHintHop {
3272                         src_node_id: nodes[2],
3273                         short_channel_id: 5,
3274                         fees: RoutingFees {
3275                                 base_msat: 100,
3276                                 proportional_millionths: 0,
3277                         },
3278                         cltv_expiry_delta: (5 << 4) | 1,
3279                         htlc_minimum_msat: None,
3280                         htlc_maximum_msat: None,
3281                 }, RouteHintHop {
3282                         src_node_id: nodes[3],
3283                         short_channel_id: 8,
3284                         fees: zero_fees,
3285                         cltv_expiry_delta: (8 << 4) | 1,
3286                         htlc_minimum_msat: None,
3287                         htlc_maximum_msat: None,
3288                 }
3289                 ]), RouteHint(vec![RouteHintHop {
3290                         src_node_id: nodes[4],
3291                         short_channel_id: 9,
3292                         fees: RoutingFees {
3293                                 base_msat: 1001,
3294                                 proportional_millionths: 0,
3295                         },
3296                         cltv_expiry_delta: (9 << 4) | 1,
3297                         htlc_minimum_msat: None,
3298                         htlc_maximum_msat: None,
3299                 }]), RouteHint(vec![RouteHintHop {
3300                         src_node_id: nodes[5],
3301                         short_channel_id: 10,
3302                         fees: zero_fees,
3303                         cltv_expiry_delta: (10 << 4) | 1,
3304                         htlc_minimum_msat: None,
3305                         htlc_maximum_msat: None,
3306                 }])]
3307         }
3308
3309         #[test]
3310         fn partial_route_hint_test() {
3311                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3312                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3313                 let scorer = ln_test_utils::TestScorer::new();
3314                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3315                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3316
3317                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3318                 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3319                 // RouteHint may be partially used by the algo to build the best path.
3320
3321                 // First check that last hop can't have its source as the payee.
3322                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3323                         src_node_id: nodes[6],
3324                         short_channel_id: 8,
3325                         fees: RoutingFees {
3326                                 base_msat: 1000,
3327                                 proportional_millionths: 0,
3328                         },
3329                         cltv_expiry_delta: (8 << 4) | 1,
3330                         htlc_minimum_msat: None,
3331                         htlc_maximum_msat: None,
3332                 }]);
3333
3334                 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3335                 invalid_last_hops.push(invalid_last_hop);
3336                 {
3337                         let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3338                         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) {
3339                                 assert_eq!(err, "Route hint cannot have the payee as the source.");
3340                         } else { panic!(); }
3341                 }
3342
3343                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3344                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3345                 assert_eq!(route.paths[0].hops.len(), 5);
3346
3347                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3348                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3349                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3350                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3351                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3352                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3353
3354                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3355                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3356                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3357                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3358                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3359                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3360
3361                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3362                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3363                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3364                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3365                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3366                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3367
3368                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3369                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3370                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3371                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3372                 // If we have a peer in the node map, we'll use their features here since we don't have
3373                 // a way of figuring out their features from the invoice:
3374                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3375                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3376
3377                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3378                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3379                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3380                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3381                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3382                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3383         }
3384
3385         fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3386                 let zero_fees = RoutingFees {
3387                         base_msat: 0,
3388                         proportional_millionths: 0,
3389                 };
3390                 vec![RouteHint(vec![RouteHintHop {
3391                         src_node_id: nodes[3],
3392                         short_channel_id: 8,
3393                         fees: zero_fees,
3394                         cltv_expiry_delta: (8 << 4) | 1,
3395                         htlc_minimum_msat: None,
3396                         htlc_maximum_msat: None,
3397                 }]), RouteHint(vec![
3398
3399                 ]), RouteHint(vec![RouteHintHop {
3400                         src_node_id: nodes[5],
3401                         short_channel_id: 10,
3402                         fees: zero_fees,
3403                         cltv_expiry_delta: (10 << 4) | 1,
3404                         htlc_minimum_msat: None,
3405                         htlc_maximum_msat: None,
3406                 }])]
3407         }
3408
3409         #[test]
3410         fn ignores_empty_last_hops_test() {
3411                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3412                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3413                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3414                 let scorer = ln_test_utils::TestScorer::new();
3415                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3416                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3417
3418                 // Test handling of an empty RouteHint passed in Invoice.
3419
3420                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3421                 assert_eq!(route.paths[0].hops.len(), 5);
3422
3423                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3424                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3425                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3426                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3427                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3428                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3429
3430                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3431                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3432                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3433                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3434                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3435                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3436
3437                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3438                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3439                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3440                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3441                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3442                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3443
3444                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3445                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3446                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3447                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3448                 // If we have a peer in the node map, we'll use their features here since we don't have
3449                 // a way of figuring out their features from the invoice:
3450                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3451                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3452
3453                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3454                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3455                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3456                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3457                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3458                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3459         }
3460
3461         /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3462         /// and 0xff01.
3463         fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3464                 let zero_fees = RoutingFees {
3465                         base_msat: 0,
3466                         proportional_millionths: 0,
3467                 };
3468                 vec![RouteHint(vec![RouteHintHop {
3469                         src_node_id: hint_hops[0],
3470                         short_channel_id: 0xff00,
3471                         fees: RoutingFees {
3472                                 base_msat: 100,
3473                                 proportional_millionths: 0,
3474                         },
3475                         cltv_expiry_delta: (5 << 4) | 1,
3476                         htlc_minimum_msat: None,
3477                         htlc_maximum_msat: None,
3478                 }, RouteHintHop {
3479                         src_node_id: hint_hops[1],
3480                         short_channel_id: 0xff01,
3481                         fees: zero_fees,
3482                         cltv_expiry_delta: (8 << 4) | 1,
3483                         htlc_minimum_msat: None,
3484                         htlc_maximum_msat: None,
3485                 }])]
3486         }
3487
3488         #[test]
3489         fn multi_hint_last_hops_test() {
3490                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3491                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3492                 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3493                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3494                 let scorer = ln_test_utils::TestScorer::new();
3495                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3496                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3497                 // Test through channels 2, 3, 0xff00, 0xff01.
3498                 // Test shows that multiple hop hints are considered.
3499
3500                 // Disabling channels 6 & 7 by flags=2
3501                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3502                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3503                         short_channel_id: 6,
3504                         timestamp: 2,
3505                         flags: 2, // to disable
3506                         cltv_expiry_delta: 0,
3507                         htlc_minimum_msat: 0,
3508                         htlc_maximum_msat: MAX_VALUE_MSAT,
3509                         fee_base_msat: 0,
3510                         fee_proportional_millionths: 0,
3511                         excess_data: Vec::new()
3512                 });
3513                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3514                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3515                         short_channel_id: 7,
3516                         timestamp: 2,
3517                         flags: 2, // to disable
3518                         cltv_expiry_delta: 0,
3519                         htlc_minimum_msat: 0,
3520                         htlc_maximum_msat: MAX_VALUE_MSAT,
3521                         fee_base_msat: 0,
3522                         fee_proportional_millionths: 0,
3523                         excess_data: Vec::new()
3524                 });
3525
3526                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3527                 assert_eq!(route.paths[0].hops.len(), 4);
3528
3529                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3530                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3531                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3532                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3533                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3534                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3535
3536                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3537                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3538                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3539                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3540                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3541                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3542
3543                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3544                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3545                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3546                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3547                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3548                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3549
3550                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3551                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3552                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3553                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3554                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3555                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3556         }
3557
3558         #[test]
3559         fn private_multi_hint_last_hops_test() {
3560                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3561                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3562
3563                 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3564                 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3565
3566                 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3567                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3568                 let scorer = ln_test_utils::TestScorer::new();
3569                 // Test through channels 2, 3, 0xff00, 0xff01.
3570                 // Test shows that multiple hop hints are considered.
3571
3572                 // Disabling channels 6 & 7 by flags=2
3573                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3574                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3575                         short_channel_id: 6,
3576                         timestamp: 2,
3577                         flags: 2, // to disable
3578                         cltv_expiry_delta: 0,
3579                         htlc_minimum_msat: 0,
3580                         htlc_maximum_msat: MAX_VALUE_MSAT,
3581                         fee_base_msat: 0,
3582                         fee_proportional_millionths: 0,
3583                         excess_data: Vec::new()
3584                 });
3585                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3586                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3587                         short_channel_id: 7,
3588                         timestamp: 2,
3589                         flags: 2, // to disable
3590                         cltv_expiry_delta: 0,
3591                         htlc_minimum_msat: 0,
3592                         htlc_maximum_msat: MAX_VALUE_MSAT,
3593                         fee_base_msat: 0,
3594                         fee_proportional_millionths: 0,
3595                         excess_data: Vec::new()
3596                 });
3597
3598                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3599                 assert_eq!(route.paths[0].hops.len(), 4);
3600
3601                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3602                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3603                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3604                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3605                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3606                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3607
3608                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3609                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3610                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3611                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3612                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3613                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3614
3615                 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3616                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3617                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3618                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3619                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3620                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3621
3622                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3623                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3624                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3625                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3626                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3627                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3628         }
3629
3630         fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3631                 let zero_fees = RoutingFees {
3632                         base_msat: 0,
3633                         proportional_millionths: 0,
3634                 };
3635                 vec![RouteHint(vec![RouteHintHop {
3636                         src_node_id: nodes[4],
3637                         short_channel_id: 11,
3638                         fees: zero_fees,
3639                         cltv_expiry_delta: (11 << 4) | 1,
3640                         htlc_minimum_msat: None,
3641                         htlc_maximum_msat: None,
3642                 }, RouteHintHop {
3643                         src_node_id: nodes[3],
3644                         short_channel_id: 8,
3645                         fees: zero_fees,
3646                         cltv_expiry_delta: (8 << 4) | 1,
3647                         htlc_minimum_msat: None,
3648                         htlc_maximum_msat: None,
3649                 }]), RouteHint(vec![RouteHintHop {
3650                         src_node_id: nodes[4],
3651                         short_channel_id: 9,
3652                         fees: RoutingFees {
3653                                 base_msat: 1001,
3654                                 proportional_millionths: 0,
3655                         },
3656                         cltv_expiry_delta: (9 << 4) | 1,
3657                         htlc_minimum_msat: None,
3658                         htlc_maximum_msat: None,
3659                 }]), RouteHint(vec![RouteHintHop {
3660                         src_node_id: nodes[5],
3661                         short_channel_id: 10,
3662                         fees: zero_fees,
3663                         cltv_expiry_delta: (10 << 4) | 1,
3664                         htlc_minimum_msat: None,
3665                         htlc_maximum_msat: None,
3666                 }])]
3667         }
3668
3669         #[test]
3670         fn last_hops_with_public_channel_test() {
3671                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3672                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3673                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3674                 let scorer = ln_test_utils::TestScorer::new();
3675                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3676                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3677                 // This test shows that public routes can be present in the invoice
3678                 // which would be handled in the same manner.
3679
3680                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3681                 assert_eq!(route.paths[0].hops.len(), 5);
3682
3683                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3684                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3685                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3686                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3687                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3688                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3689
3690                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3691                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3692                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3693                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3694                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3695                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3696
3697                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3698                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3699                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3700                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3701                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3702                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3703
3704                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3705                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3706                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3707                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3708                 // If we have a peer in the node map, we'll use their features here since we don't have
3709                 // a way of figuring out their features from the invoice:
3710                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3711                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3712
3713                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3714                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3715                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3716                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3717                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3718                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3719         }
3720
3721         #[test]
3722         fn our_chans_last_hop_connect_test() {
3723                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3724                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3725                 let scorer = ln_test_utils::TestScorer::new();
3726                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3727                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3728
3729                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3730                 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3731                 let mut last_hops = last_hops(&nodes);
3732                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3733                 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();
3734                 assert_eq!(route.paths[0].hops.len(), 2);
3735
3736                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3737                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3738                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3739                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3740                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3741                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3742
3743                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3744                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3745                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3746                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3747                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3748                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3749
3750                 last_hops[0].0[0].fees.base_msat = 1000;
3751
3752                 // Revert to via 6 as the fee on 8 goes up
3753                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3754                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3755                 assert_eq!(route.paths[0].hops.len(), 4);
3756
3757                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3758                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3759                 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3760                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3761                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3762                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3763
3764                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3765                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3766                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3767                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3768                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3769                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3770
3771                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3772                 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3773                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3774                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3775                 // If we have a peer in the node map, we'll use their features here since we don't have
3776                 // a way of figuring out their features from the invoice:
3777                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3778                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3779
3780                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3781                 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3782                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3783                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3784                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3785                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3786
3787                 // ...but still use 8 for larger payments as 6 has a variable feerate
3788                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3789                 assert_eq!(route.paths[0].hops.len(), 5);
3790
3791                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3792                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3793                 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3794                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3795                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3796                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3797
3798                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3799                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3800                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3801                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3802                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3803                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3804
3805                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3806                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3807                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3808                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3809                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3810                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3811
3812                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3813                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3814                 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3815                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3816                 // If we have a peer in the node map, we'll use their features here since we don't have
3817                 // a way of figuring out their features from the invoice:
3818                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3819                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3820
3821                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3822                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3823                 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3824                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3825                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3826                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3827         }
3828
3829         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> {
3830                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3831                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3832                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3833
3834                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3835                 let last_hops = RouteHint(vec![RouteHintHop {
3836                         src_node_id: middle_node_id,
3837                         short_channel_id: 8,
3838                         fees: RoutingFees {
3839                                 base_msat: 1000,
3840                                 proportional_millionths: last_hop_fee_prop,
3841                         },
3842                         cltv_expiry_delta: (8 << 4) | 1,
3843                         htlc_minimum_msat: None,
3844                         htlc_maximum_msat: last_hop_htlc_max,
3845                 }]);
3846                 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3847                 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3848                 let scorer = ln_test_utils::TestScorer::new();
3849                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3850                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3851                 let logger = ln_test_utils::TestLogger::new();
3852                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3853                 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3854                                 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3855                 route
3856         }
3857
3858         #[test]
3859         fn unannounced_path_test() {
3860                 // We should be able to send a payment to a destination without any help of a routing graph
3861                 // if we have a channel with a common counterparty that appears in the first and last hop
3862                 // hints.
3863                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3864
3865                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3866                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3867                 assert_eq!(route.paths[0].hops.len(), 2);
3868
3869                 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3870                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3871                 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3872                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3873                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3874                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3875
3876                 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3877                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3878                 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3879                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3880                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3881                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3882         }
3883
3884         #[test]
3885         fn overflow_unannounced_path_test_liquidity_underflow() {
3886                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3887                 // the last-hop had a fee which overflowed a u64, we'd panic.
3888                 // This was due to us adding the first-hop from us unconditionally, causing us to think
3889                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3890                 // In this test, we previously hit a subtraction underflow due to having less available
3891                 // liquidity at the last hop than 0.
3892                 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());
3893         }
3894
3895         #[test]
3896         fn overflow_unannounced_path_test_feerate_overflow() {
3897                 // This tests for the same case as above, except instead of hitting a subtraction
3898                 // underflow, we hit a case where the fee charged at a hop overflowed.
3899                 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());
3900         }
3901
3902         #[test]
3903         fn available_amount_while_routing_test() {
3904                 // Tests whether we choose the correct available channel amount while routing.
3905
3906                 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3907                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3908                 let scorer = ln_test_utils::TestScorer::new();
3909                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3910                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3911                 let config = UserConfig::default();
3912                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3913
3914                 // We will use a simple single-path route from
3915                 // our node to node2 via node0: channels {1, 3}.
3916
3917                 // First disable all other paths.
3918                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3919                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3920                         short_channel_id: 2,
3921                         timestamp: 2,
3922                         flags: 2,
3923                         cltv_expiry_delta: 0,
3924                         htlc_minimum_msat: 0,
3925                         htlc_maximum_msat: 100_000,
3926                         fee_base_msat: 0,
3927                         fee_proportional_millionths: 0,
3928                         excess_data: Vec::new()
3929                 });
3930                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3931                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3932                         short_channel_id: 12,
3933                         timestamp: 2,
3934                         flags: 2,
3935                         cltv_expiry_delta: 0,
3936                         htlc_minimum_msat: 0,
3937                         htlc_maximum_msat: 100_000,
3938                         fee_base_msat: 0,
3939                         fee_proportional_millionths: 0,
3940                         excess_data: Vec::new()
3941                 });
3942
3943                 // Make the first channel (#1) very permissive,
3944                 // and we will be testing all limits on the second channel.
3945                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3946                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3947                         short_channel_id: 1,
3948                         timestamp: 2,
3949                         flags: 0,
3950                         cltv_expiry_delta: 0,
3951                         htlc_minimum_msat: 0,
3952                         htlc_maximum_msat: 1_000_000_000,
3953                         fee_base_msat: 0,
3954                         fee_proportional_millionths: 0,
3955                         excess_data: Vec::new()
3956                 });
3957
3958                 // First, let's see if routing works if we have absolutely no idea about the available amount.
3959                 // In this case, it should be set to 250_000 sats.
3960                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3961                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3962                         short_channel_id: 3,
3963                         timestamp: 2,
3964                         flags: 0,
3965                         cltv_expiry_delta: 0,
3966                         htlc_minimum_msat: 0,
3967                         htlc_maximum_msat: 250_000_000,
3968                         fee_base_msat: 0,
3969                         fee_proportional_millionths: 0,
3970                         excess_data: Vec::new()
3971                 });
3972
3973                 {
3974                         // Attempt to route more than available results in a failure.
3975                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3976                                         &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3977                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3978                         } else { panic!(); }
3979                 }
3980
3981                 {
3982                         // Now, attempt to route an exact amount we have should be fine.
3983                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3984                         assert_eq!(route.paths.len(), 1);
3985                         let path = route.paths.last().unwrap();
3986                         assert_eq!(path.hops.len(), 2);
3987                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3988                         assert_eq!(path.final_value_msat(), 250_000_000);
3989                 }
3990
3991                 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3992                 // Disable channel #1 and use another first hop.
3993                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3994                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3995                         short_channel_id: 1,
3996                         timestamp: 3,
3997                         flags: 2,
3998                         cltv_expiry_delta: 0,
3999                         htlc_minimum_msat: 0,
4000                         htlc_maximum_msat: 1_000_000_000,
4001                         fee_base_msat: 0,
4002                         fee_proportional_millionths: 0,
4003                         excess_data: Vec::new()
4004                 });
4005
4006                 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4007                 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4008
4009                 {
4010                         // Attempt to route more than available results in a failure.
4011                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4012                                         &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4013                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4014                         } else { panic!(); }
4015                 }
4016
4017                 {
4018                         // Now, attempt to route an exact amount we have should be fine.
4019                         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();
4020                         assert_eq!(route.paths.len(), 1);
4021                         let path = route.paths.last().unwrap();
4022                         assert_eq!(path.hops.len(), 2);
4023                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4024                         assert_eq!(path.final_value_msat(), 200_000_000);
4025                 }
4026
4027                 // Enable channel #1 back.
4028                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4029                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4030                         short_channel_id: 1,
4031                         timestamp: 4,
4032                         flags: 0,
4033                         cltv_expiry_delta: 0,
4034                         htlc_minimum_msat: 0,
4035                         htlc_maximum_msat: 1_000_000_000,
4036                         fee_base_msat: 0,
4037                         fee_proportional_millionths: 0,
4038                         excess_data: Vec::new()
4039                 });
4040
4041
4042                 // Now let's see if routing works if we know only htlc_maximum_msat.
4043                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4044                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4045                         short_channel_id: 3,
4046                         timestamp: 3,
4047                         flags: 0,
4048                         cltv_expiry_delta: 0,
4049                         htlc_minimum_msat: 0,
4050                         htlc_maximum_msat: 15_000,
4051                         fee_base_msat: 0,
4052                         fee_proportional_millionths: 0,
4053                         excess_data: Vec::new()
4054                 });
4055
4056                 {
4057                         // Attempt to route more than available results in a failure.
4058                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4059                                         &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4060                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4061                         } else { panic!(); }
4062                 }
4063
4064                 {
4065                         // Now, attempt to route an exact amount we have should be fine.
4066                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4067                         assert_eq!(route.paths.len(), 1);
4068                         let path = route.paths.last().unwrap();
4069                         assert_eq!(path.hops.len(), 2);
4070                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4071                         assert_eq!(path.final_value_msat(), 15_000);
4072                 }
4073
4074                 // Now let's see if routing works if we know only capacity from the UTXO.
4075
4076                 // We can't change UTXO capacity on the fly, so we'll disable
4077                 // the existing channel and add another one with the capacity we need.
4078                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4079                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080                         short_channel_id: 3,
4081                         timestamp: 4,
4082                         flags: 2,
4083                         cltv_expiry_delta: 0,
4084                         htlc_minimum_msat: 0,
4085                         htlc_maximum_msat: MAX_VALUE_MSAT,
4086                         fee_base_msat: 0,
4087                         fee_proportional_millionths: 0,
4088                         excess_data: Vec::new()
4089                 });
4090
4091                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4092                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4093                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4094                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4095                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4096
4097                 *chain_monitor.utxo_ret.lock().unwrap() =
4098                         UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4099                 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4100
4101                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4102                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4103                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4104                         short_channel_id: 333,
4105                         timestamp: 1,
4106                         flags: 0,
4107                         cltv_expiry_delta: (3 << 4) | 1,
4108                         htlc_minimum_msat: 0,
4109                         htlc_maximum_msat: 15_000,
4110                         fee_base_msat: 0,
4111                         fee_proportional_millionths: 0,
4112                         excess_data: Vec::new()
4113                 });
4114                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4115                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4116                         short_channel_id: 333,
4117                         timestamp: 1,
4118                         flags: 1,
4119                         cltv_expiry_delta: (3 << 4) | 2,
4120                         htlc_minimum_msat: 0,
4121                         htlc_maximum_msat: 15_000,
4122                         fee_base_msat: 100,
4123                         fee_proportional_millionths: 0,
4124                         excess_data: Vec::new()
4125                 });
4126
4127                 {
4128                         // Attempt to route more than available results in a failure.
4129                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4130                                         &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4131                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4132                         } else { panic!(); }
4133                 }
4134
4135                 {
4136                         // Now, attempt to route an exact amount we have should be fine.
4137                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4138                         assert_eq!(route.paths.len(), 1);
4139                         let path = route.paths.last().unwrap();
4140                         assert_eq!(path.hops.len(), 2);
4141                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4142                         assert_eq!(path.final_value_msat(), 15_000);
4143                 }
4144
4145                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4146                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4147                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4148                         short_channel_id: 333,
4149                         timestamp: 6,
4150                         flags: 0,
4151                         cltv_expiry_delta: 0,
4152                         htlc_minimum_msat: 0,
4153                         htlc_maximum_msat: 10_000,
4154                         fee_base_msat: 0,
4155                         fee_proportional_millionths: 0,
4156                         excess_data: Vec::new()
4157                 });
4158
4159                 {
4160                         // Attempt to route more than available results in a failure.
4161                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4162                                         &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4163                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4164                         } else { panic!(); }
4165                 }
4166
4167                 {
4168                         // Now, attempt to route an exact amount we have should be fine.
4169                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4170                         assert_eq!(route.paths.len(), 1);
4171                         let path = route.paths.last().unwrap();
4172                         assert_eq!(path.hops.len(), 2);
4173                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4174                         assert_eq!(path.final_value_msat(), 10_000);
4175                 }
4176         }
4177
4178         #[test]
4179         fn available_liquidity_last_hop_test() {
4180                 // Check that available liquidity properly limits the path even when only
4181                 // one of the latter hops is limited.
4182                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4183                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4184                 let scorer = ln_test_utils::TestScorer::new();
4185                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4186                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4187                 let config = UserConfig::default();
4188                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4189
4190                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4191                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4192                 // Total capacity: 50 sats.
4193
4194                 // Disable other potential paths.
4195                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4196                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4197                         short_channel_id: 2,
4198                         timestamp: 2,
4199                         flags: 2,
4200                         cltv_expiry_delta: 0,
4201                         htlc_minimum_msat: 0,
4202                         htlc_maximum_msat: 100_000,
4203                         fee_base_msat: 0,
4204                         fee_proportional_millionths: 0,
4205                         excess_data: Vec::new()
4206                 });
4207                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4208                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4209                         short_channel_id: 7,
4210                         timestamp: 2,
4211                         flags: 2,
4212                         cltv_expiry_delta: 0,
4213                         htlc_minimum_msat: 0,
4214                         htlc_maximum_msat: 100_000,
4215                         fee_base_msat: 0,
4216                         fee_proportional_millionths: 0,
4217                         excess_data: Vec::new()
4218                 });
4219
4220                 // Limit capacities
4221
4222                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4223                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4224                         short_channel_id: 12,
4225                         timestamp: 2,
4226                         flags: 0,
4227                         cltv_expiry_delta: 0,
4228                         htlc_minimum_msat: 0,
4229                         htlc_maximum_msat: 100_000,
4230                         fee_base_msat: 0,
4231                         fee_proportional_millionths: 0,
4232                         excess_data: Vec::new()
4233                 });
4234                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4235                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4236                         short_channel_id: 13,
4237                         timestamp: 2,
4238                         flags: 0,
4239                         cltv_expiry_delta: 0,
4240                         htlc_minimum_msat: 0,
4241                         htlc_maximum_msat: 100_000,
4242                         fee_base_msat: 0,
4243                         fee_proportional_millionths: 0,
4244                         excess_data: Vec::new()
4245                 });
4246
4247                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4248                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4249                         short_channel_id: 6,
4250                         timestamp: 2,
4251                         flags: 0,
4252                         cltv_expiry_delta: 0,
4253                         htlc_minimum_msat: 0,
4254                         htlc_maximum_msat: 50_000,
4255                         fee_base_msat: 0,
4256                         fee_proportional_millionths: 0,
4257                         excess_data: Vec::new()
4258                 });
4259                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4260                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4261                         short_channel_id: 11,
4262                         timestamp: 2,
4263                         flags: 0,
4264                         cltv_expiry_delta: 0,
4265                         htlc_minimum_msat: 0,
4266                         htlc_maximum_msat: 100_000,
4267                         fee_base_msat: 0,
4268                         fee_proportional_millionths: 0,
4269                         excess_data: Vec::new()
4270                 });
4271                 {
4272                         // Attempt to route more than available results in a failure.
4273                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4274                                         &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4275                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4276                         } else { panic!(); }
4277                 }
4278
4279                 {
4280                         // Now, attempt to route 49 sats (just a bit below the capacity).
4281                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4282                         assert_eq!(route.paths.len(), 1);
4283                         let mut total_amount_paid_msat = 0;
4284                         for path in &route.paths {
4285                                 assert_eq!(path.hops.len(), 4);
4286                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4287                                 total_amount_paid_msat += path.final_value_msat();
4288                         }
4289                         assert_eq!(total_amount_paid_msat, 49_000);
4290                 }
4291
4292                 {
4293                         // Attempt to route an exact amount is also fine
4294                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4295                         assert_eq!(route.paths.len(), 1);
4296                         let mut total_amount_paid_msat = 0;
4297                         for path in &route.paths {
4298                                 assert_eq!(path.hops.len(), 4);
4299                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4300                                 total_amount_paid_msat += path.final_value_msat();
4301                         }
4302                         assert_eq!(total_amount_paid_msat, 50_000);
4303                 }
4304         }
4305
4306         #[test]
4307         fn ignore_fee_first_hop_test() {
4308                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4309                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4310                 let scorer = ln_test_utils::TestScorer::new();
4311                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4312                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4313                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4314
4315                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4316                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4317                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4318                         short_channel_id: 1,
4319                         timestamp: 2,
4320                         flags: 0,
4321                         cltv_expiry_delta: 0,
4322                         htlc_minimum_msat: 0,
4323                         htlc_maximum_msat: 100_000,
4324                         fee_base_msat: 1_000_000,
4325                         fee_proportional_millionths: 0,
4326                         excess_data: Vec::new()
4327                 });
4328                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4329                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4330                         short_channel_id: 3,
4331                         timestamp: 2,
4332                         flags: 0,
4333                         cltv_expiry_delta: 0,
4334                         htlc_minimum_msat: 0,
4335                         htlc_maximum_msat: 50_000,
4336                         fee_base_msat: 0,
4337                         fee_proportional_millionths: 0,
4338                         excess_data: Vec::new()
4339                 });
4340
4341                 {
4342                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4343                         assert_eq!(route.paths.len(), 1);
4344                         let mut total_amount_paid_msat = 0;
4345                         for path in &route.paths {
4346                                 assert_eq!(path.hops.len(), 2);
4347                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4348                                 total_amount_paid_msat += path.final_value_msat();
4349                         }
4350                         assert_eq!(total_amount_paid_msat, 50_000);
4351                 }
4352         }
4353
4354         #[test]
4355         fn simple_mpp_route_test() {
4356                 let (secp_ctx, _, _, _, _) = build_graph();
4357                 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4358                 let config = UserConfig::default();
4359                 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4360                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4361                 do_simple_mpp_route_test(clear_payment_params);
4362
4363                 // MPP to a 1-hop blinded path for nodes[2]
4364                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4365                 let blinded_path = BlindedPath {
4366                         introduction_node_id: nodes[2],
4367                         blinding_point: ln_test_utils::pubkey(42),
4368                         blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4369                 };
4370                 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4371                         fee_base_msat: 0,
4372                         fee_proportional_millionths: 0,
4373                         htlc_minimum_msat: 0,
4374                         htlc_maximum_msat: 0,
4375                         cltv_expiry_delta: 0,
4376                         features: BlindedHopFeatures::empty(),
4377                 };
4378                 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4379                         .with_bolt12_features(bolt12_features.clone()).unwrap();
4380                 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4381
4382                 // MPP to 3 2-hop blinded paths
4383                 let mut blinded_path_node_0 = blinded_path.clone();
4384                 blinded_path_node_0.introduction_node_id = nodes[0];
4385                 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4386                 let mut node_0_payinfo = blinded_payinfo.clone();
4387                 node_0_payinfo.htlc_maximum_msat = 50_000;
4388
4389                 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4390                 blinded_path_node_7.introduction_node_id = nodes[7];
4391                 let mut node_7_payinfo = blinded_payinfo.clone();
4392                 node_7_payinfo.htlc_maximum_msat = 60_000;
4393
4394                 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4395                 blinded_path_node_1.introduction_node_id = nodes[1];
4396                 let mut node_1_payinfo = blinded_payinfo.clone();
4397                 node_1_payinfo.htlc_maximum_msat = 180_000;
4398
4399                 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4400                         vec![
4401                                 (node_0_payinfo, blinded_path_node_0),
4402                                 (node_7_payinfo, blinded_path_node_7),
4403                                 (node_1_payinfo, blinded_path_node_1)
4404                         ])
4405                         .with_bolt12_features(bolt12_features).unwrap();
4406                 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4407         }
4408
4409
4410         fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4411                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4412                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4413                 let scorer = ln_test_utils::TestScorer::new();
4414                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4415                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4416
4417                 // We need a route consisting of 3 paths:
4418                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4419                 // To achieve this, the amount being transferred should be around
4420                 // the total capacity of these 3 paths.
4421
4422                 // First, we set limits on these (previously unlimited) channels.
4423                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4424
4425                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4426                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4427                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4428                         short_channel_id: 1,
4429                         timestamp: 2,
4430                         flags: 0,
4431                         cltv_expiry_delta: 0,
4432                         htlc_minimum_msat: 0,
4433                         htlc_maximum_msat: 100_000,
4434                         fee_base_msat: 0,
4435                         fee_proportional_millionths: 0,
4436                         excess_data: Vec::new()
4437                 });
4438                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4439                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4440                         short_channel_id: 3,
4441                         timestamp: 2,
4442                         flags: 0,
4443                         cltv_expiry_delta: 0,
4444                         htlc_minimum_msat: 0,
4445                         htlc_maximum_msat: 50_000,
4446                         fee_base_msat: 0,
4447                         fee_proportional_millionths: 0,
4448                         excess_data: Vec::new()
4449                 });
4450
4451                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4452                 // (total limit 60).
4453                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4454                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4455                         short_channel_id: 12,
4456                         timestamp: 2,
4457                         flags: 0,
4458                         cltv_expiry_delta: 0,
4459                         htlc_minimum_msat: 0,
4460                         htlc_maximum_msat: 60_000,
4461                         fee_base_msat: 0,
4462                         fee_proportional_millionths: 0,
4463                         excess_data: Vec::new()
4464                 });
4465                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4466                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4467                         short_channel_id: 13,
4468                         timestamp: 2,
4469                         flags: 0,
4470                         cltv_expiry_delta: 0,
4471                         htlc_minimum_msat: 0,
4472                         htlc_maximum_msat: 60_000,
4473                         fee_base_msat: 0,
4474                         fee_proportional_millionths: 0,
4475                         excess_data: Vec::new()
4476                 });
4477
4478                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4479                 // (total capacity 180 sats).
4480                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4481                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4482                         short_channel_id: 2,
4483                         timestamp: 2,
4484                         flags: 0,
4485                         cltv_expiry_delta: 0,
4486                         htlc_minimum_msat: 0,
4487                         htlc_maximum_msat: 200_000,
4488                         fee_base_msat: 0,
4489                         fee_proportional_millionths: 0,
4490                         excess_data: Vec::new()
4491                 });
4492                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4493                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4494                         short_channel_id: 4,
4495                         timestamp: 2,
4496                         flags: 0,
4497                         cltv_expiry_delta: 0,
4498                         htlc_minimum_msat: 0,
4499                         htlc_maximum_msat: 180_000,
4500                         fee_base_msat: 0,
4501                         fee_proportional_millionths: 0,
4502                         excess_data: Vec::new()
4503                 });
4504
4505                 {
4506                         // Attempt to route more than available results in a failure.
4507                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4508                                 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4509                                 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4510                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
4511                         } else { panic!(); }
4512                 }
4513
4514                 {
4515                         // Attempt to route while setting max_path_count to 0 results in a failure.
4516                         let zero_payment_params = payment_params.clone().with_max_path_count(0);
4517                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4518                                 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4519                                 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4520                                         assert_eq!(err, "Can't find a route with no paths allowed.");
4521                         } else { panic!(); }
4522                 }
4523
4524                 {
4525                         // Attempt to route while setting max_path_count to 3 results in a failure.
4526                         // This is the case because the minimal_value_contribution_msat would require each path
4527                         // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4528                         let fail_payment_params = payment_params.clone().with_max_path_count(3);
4529                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4530                                 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4531                                 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4532                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
4533                         } else { panic!(); }
4534                 }
4535
4536                 {
4537                         // Now, attempt to route 250 sats (just a bit below the capacity).
4538                         // Our algorithm should provide us with these 3 paths.
4539                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4540                                 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4541                         assert_eq!(route.paths.len(), 3);
4542                         let mut total_amount_paid_msat = 0;
4543                         for path in &route.paths {
4544                                 if let Some(bt) = &path.blinded_tail {
4545                                         assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4546                                 } else {
4547                                         assert_eq!(path.hops.len(), 2);
4548                                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4549                                 }
4550                                 total_amount_paid_msat += path.final_value_msat();
4551                         }
4552                         assert_eq!(total_amount_paid_msat, 250_000);
4553                 }
4554
4555                 {
4556                         // Attempt to route an exact amount is also fine
4557                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4558                                 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4559                         assert_eq!(route.paths.len(), 3);
4560                         let mut total_amount_paid_msat = 0;
4561                         for path in &route.paths {
4562                                 if payment_params.payee.blinded_route_hints().len() != 0 {
4563                                         assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4564                                 if let Some(bt) = &path.blinded_tail {
4565                                         assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4566                                         if bt.hops.len() > 1 {
4567                                                 assert_eq!(path.hops.last().unwrap().pubkey,
4568                                                         payment_params.payee.blinded_route_hints().iter()
4569                                                                 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4570                                                                 .map(|(_, p)| p.introduction_node_id).unwrap());
4571                                         } else {
4572                                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4573                                         }
4574                                 } else {
4575                                         assert_eq!(path.hops.len(), 2);
4576                                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4577                                 }
4578                                 total_amount_paid_msat += path.final_value_msat();
4579                         }
4580                         assert_eq!(total_amount_paid_msat, 290_000);
4581                 }
4582         }
4583
4584         #[test]
4585         fn long_mpp_route_test() {
4586                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4587                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4588                 let scorer = ln_test_utils::TestScorer::new();
4589                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4590                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4591                 let config = UserConfig::default();
4592                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4593
4594                 // We need a route consisting of 3 paths:
4595                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4596                 // Note that these paths overlap (channels 5, 12, 13).
4597                 // We will route 300 sats.
4598                 // Each path will have 100 sats capacity, those channels which
4599                 // are used twice will have 200 sats capacity.
4600
4601                 // Disable other potential paths.
4602                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4603                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4604                         short_channel_id: 2,
4605                         timestamp: 2,
4606                         flags: 2,
4607                         cltv_expiry_delta: 0,
4608                         htlc_minimum_msat: 0,
4609                         htlc_maximum_msat: 100_000,
4610                         fee_base_msat: 0,
4611                         fee_proportional_millionths: 0,
4612                         excess_data: Vec::new()
4613                 });
4614                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4615                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4616                         short_channel_id: 7,
4617                         timestamp: 2,
4618                         flags: 2,
4619                         cltv_expiry_delta: 0,
4620                         htlc_minimum_msat: 0,
4621                         htlc_maximum_msat: 100_000,
4622                         fee_base_msat: 0,
4623                         fee_proportional_millionths: 0,
4624                         excess_data: Vec::new()
4625                 });
4626
4627                 // Path via {node0, node2} is channels {1, 3, 5}.
4628                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4629                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4630                         short_channel_id: 1,
4631                         timestamp: 2,
4632                         flags: 0,
4633                         cltv_expiry_delta: 0,
4634                         htlc_minimum_msat: 0,
4635                         htlc_maximum_msat: 100_000,
4636                         fee_base_msat: 0,
4637                         fee_proportional_millionths: 0,
4638                         excess_data: Vec::new()
4639                 });
4640                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4641                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4642                         short_channel_id: 3,
4643                         timestamp: 2,
4644                         flags: 0,
4645                         cltv_expiry_delta: 0,
4646                         htlc_minimum_msat: 0,
4647                         htlc_maximum_msat: 100_000,
4648                         fee_base_msat: 0,
4649                         fee_proportional_millionths: 0,
4650                         excess_data: Vec::new()
4651                 });
4652
4653                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4654                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4655                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4656                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4657                         short_channel_id: 5,
4658                         timestamp: 2,
4659                         flags: 0,
4660                         cltv_expiry_delta: 0,
4661                         htlc_minimum_msat: 0,
4662                         htlc_maximum_msat: 200_000,
4663                         fee_base_msat: 0,
4664                         fee_proportional_millionths: 0,
4665                         excess_data: Vec::new()
4666                 });
4667
4668                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4669                 // Add 100 sats to the capacities of {12, 13}, because these channels
4670                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4671                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4672                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4673                         short_channel_id: 12,
4674                         timestamp: 2,
4675                         flags: 0,
4676                         cltv_expiry_delta: 0,
4677                         htlc_minimum_msat: 0,
4678                         htlc_maximum_msat: 200_000,
4679                         fee_base_msat: 0,
4680                         fee_proportional_millionths: 0,
4681                         excess_data: Vec::new()
4682                 });
4683                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4684                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4685                         short_channel_id: 13,
4686                         timestamp: 2,
4687                         flags: 0,
4688                         cltv_expiry_delta: 0,
4689                         htlc_minimum_msat: 0,
4690                         htlc_maximum_msat: 200_000,
4691                         fee_base_msat: 0,
4692                         fee_proportional_millionths: 0,
4693                         excess_data: Vec::new()
4694                 });
4695
4696                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4697                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4698                         short_channel_id: 6,
4699                         timestamp: 2,
4700                         flags: 0,
4701                         cltv_expiry_delta: 0,
4702                         htlc_minimum_msat: 0,
4703                         htlc_maximum_msat: 100_000,
4704                         fee_base_msat: 0,
4705                         fee_proportional_millionths: 0,
4706                         excess_data: Vec::new()
4707                 });
4708                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4709                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4710                         short_channel_id: 11,
4711                         timestamp: 2,
4712                         flags: 0,
4713                         cltv_expiry_delta: 0,
4714                         htlc_minimum_msat: 0,
4715                         htlc_maximum_msat: 100_000,
4716                         fee_base_msat: 0,
4717                         fee_proportional_millionths: 0,
4718                         excess_data: Vec::new()
4719                 });
4720
4721                 // Path via {node7, node2} is channels {12, 13, 5}.
4722                 // We already limited them to 200 sats (they are used twice for 100 sats).
4723                 // Nothing to do here.
4724
4725                 {
4726                         // Attempt to route more than available results in a failure.
4727                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4728                                         &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4729                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4730                         } else { panic!(); }
4731                 }
4732
4733                 {
4734                         // Now, attempt to route 300 sats (exact amount we can route).
4735                         // Our algorithm should provide us with these 3 paths, 100 sats each.
4736                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4737                         assert_eq!(route.paths.len(), 3);
4738
4739                         let mut total_amount_paid_msat = 0;
4740                         for path in &route.paths {
4741                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4742                                 total_amount_paid_msat += path.final_value_msat();
4743                         }
4744                         assert_eq!(total_amount_paid_msat, 300_000);
4745                 }
4746
4747         }
4748
4749         #[test]
4750         fn mpp_cheaper_route_test() {
4751                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4752                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4753                 let scorer = ln_test_utils::TestScorer::new();
4754                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4755                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4756                 let config = UserConfig::default();
4757                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4758
4759                 // This test checks that if we have two cheaper paths and one more expensive path,
4760                 // so that liquidity-wise any 2 of 3 combination is sufficient,
4761                 // two cheaper paths will be taken.
4762                 // These paths have equal available liquidity.
4763
4764                 // We need a combination of 3 paths:
4765                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4766                 // Note that these paths overlap (channels 5, 12, 13).
4767                 // Each path will have 100 sats capacity, those channels which
4768                 // are used twice will have 200 sats capacity.
4769
4770                 // Disable other potential paths.
4771                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4772                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4773                         short_channel_id: 2,
4774                         timestamp: 2,
4775                         flags: 2,
4776                         cltv_expiry_delta: 0,
4777                         htlc_minimum_msat: 0,
4778                         htlc_maximum_msat: 100_000,
4779                         fee_base_msat: 0,
4780                         fee_proportional_millionths: 0,
4781                         excess_data: Vec::new()
4782                 });
4783                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4784                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4785                         short_channel_id: 7,
4786                         timestamp: 2,
4787                         flags: 2,
4788                         cltv_expiry_delta: 0,
4789                         htlc_minimum_msat: 0,
4790                         htlc_maximum_msat: 100_000,
4791                         fee_base_msat: 0,
4792                         fee_proportional_millionths: 0,
4793                         excess_data: Vec::new()
4794                 });
4795
4796                 // Path via {node0, node2} is channels {1, 3, 5}.
4797                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4798                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4799                         short_channel_id: 1,
4800                         timestamp: 2,
4801                         flags: 0,
4802                         cltv_expiry_delta: 0,
4803                         htlc_minimum_msat: 0,
4804                         htlc_maximum_msat: 100_000,
4805                         fee_base_msat: 0,
4806                         fee_proportional_millionths: 0,
4807                         excess_data: Vec::new()
4808                 });
4809                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4810                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4811                         short_channel_id: 3,
4812                         timestamp: 2,
4813                         flags: 0,
4814                         cltv_expiry_delta: 0,
4815                         htlc_minimum_msat: 0,
4816                         htlc_maximum_msat: 100_000,
4817                         fee_base_msat: 0,
4818                         fee_proportional_millionths: 0,
4819                         excess_data: Vec::new()
4820                 });
4821
4822                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4823                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4824                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4825                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4826                         short_channel_id: 5,
4827                         timestamp: 2,
4828                         flags: 0,
4829                         cltv_expiry_delta: 0,
4830                         htlc_minimum_msat: 0,
4831                         htlc_maximum_msat: 200_000,
4832                         fee_base_msat: 0,
4833                         fee_proportional_millionths: 0,
4834                         excess_data: Vec::new()
4835                 });
4836
4837                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4838                 // Add 100 sats to the capacities of {12, 13}, because these channels
4839                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4840                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4841                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4842                         short_channel_id: 12,
4843                         timestamp: 2,
4844                         flags: 0,
4845                         cltv_expiry_delta: 0,
4846                         htlc_minimum_msat: 0,
4847                         htlc_maximum_msat: 200_000,
4848                         fee_base_msat: 0,
4849                         fee_proportional_millionths: 0,
4850                         excess_data: Vec::new()
4851                 });
4852                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4853                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4854                         short_channel_id: 13,
4855                         timestamp: 2,
4856                         flags: 0,
4857                         cltv_expiry_delta: 0,
4858                         htlc_minimum_msat: 0,
4859                         htlc_maximum_msat: 200_000,
4860                         fee_base_msat: 0,
4861                         fee_proportional_millionths: 0,
4862                         excess_data: Vec::new()
4863                 });
4864
4865                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4866                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4867                         short_channel_id: 6,
4868                         timestamp: 2,
4869                         flags: 0,
4870                         cltv_expiry_delta: 0,
4871                         htlc_minimum_msat: 0,
4872                         htlc_maximum_msat: 100_000,
4873                         fee_base_msat: 1_000,
4874                         fee_proportional_millionths: 0,
4875                         excess_data: Vec::new()
4876                 });
4877                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4878                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4879                         short_channel_id: 11,
4880                         timestamp: 2,
4881                         flags: 0,
4882                         cltv_expiry_delta: 0,
4883                         htlc_minimum_msat: 0,
4884                         htlc_maximum_msat: 100_000,
4885                         fee_base_msat: 0,
4886                         fee_proportional_millionths: 0,
4887                         excess_data: Vec::new()
4888                 });
4889
4890                 // Path via {node7, node2} is channels {12, 13, 5}.
4891                 // We already limited them to 200 sats (they are used twice for 100 sats).
4892                 // Nothing to do here.
4893
4894                 {
4895                         // Now, attempt to route 180 sats.
4896                         // Our algorithm should provide us with these 2 paths.
4897                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4898                         assert_eq!(route.paths.len(), 2);
4899
4900                         let mut total_value_transferred_msat = 0;
4901                         let mut total_paid_msat = 0;
4902                         for path in &route.paths {
4903                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4904                                 total_value_transferred_msat += path.final_value_msat();
4905                                 for hop in &path.hops {
4906                                         total_paid_msat += hop.fee_msat;
4907                                 }
4908                         }
4909                         // If we paid fee, this would be higher.
4910                         assert_eq!(total_value_transferred_msat, 180_000);
4911                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4912                         assert_eq!(total_fees_paid, 0);
4913                 }
4914         }
4915
4916         #[test]
4917         fn fees_on_mpp_route_test() {
4918                 // This test makes sure that MPP algorithm properly takes into account
4919                 // fees charged on the channels, by making the fees impactful:
4920                 // if the fee is not properly accounted for, the behavior is different.
4921                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4922                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4923                 let scorer = ln_test_utils::TestScorer::new();
4924                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4925                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4926                 let config = UserConfig::default();
4927                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4928
4929                 // We need a route consisting of 2 paths:
4930                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4931                 // We will route 200 sats, Each path will have 100 sats capacity.
4932
4933                 // This test is not particularly stable: e.g.,
4934                 // there's a way to route via {node0, node2, node4}.
4935                 // It works while pathfinding is deterministic, but can be broken otherwise.
4936                 // It's fine to ignore this concern for now.
4937
4938                 // Disable other potential paths.
4939                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4940                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4941                         short_channel_id: 2,
4942                         timestamp: 2,
4943                         flags: 2,
4944                         cltv_expiry_delta: 0,
4945                         htlc_minimum_msat: 0,
4946                         htlc_maximum_msat: 100_000,
4947                         fee_base_msat: 0,
4948                         fee_proportional_millionths: 0,
4949                         excess_data: Vec::new()
4950                 });
4951
4952                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4953                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4954                         short_channel_id: 7,
4955                         timestamp: 2,
4956                         flags: 2,
4957                         cltv_expiry_delta: 0,
4958                         htlc_minimum_msat: 0,
4959                         htlc_maximum_msat: 100_000,
4960                         fee_base_msat: 0,
4961                         fee_proportional_millionths: 0,
4962                         excess_data: Vec::new()
4963                 });
4964
4965                 // Path via {node0, node2} is channels {1, 3, 5}.
4966                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4967                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4968                         short_channel_id: 1,
4969                         timestamp: 2,
4970                         flags: 0,
4971                         cltv_expiry_delta: 0,
4972                         htlc_minimum_msat: 0,
4973                         htlc_maximum_msat: 100_000,
4974                         fee_base_msat: 0,
4975                         fee_proportional_millionths: 0,
4976                         excess_data: Vec::new()
4977                 });
4978                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4979                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4980                         short_channel_id: 3,
4981                         timestamp: 2,
4982                         flags: 0,
4983                         cltv_expiry_delta: 0,
4984                         htlc_minimum_msat: 0,
4985                         htlc_maximum_msat: 100_000,
4986                         fee_base_msat: 0,
4987                         fee_proportional_millionths: 0,
4988                         excess_data: Vec::new()
4989                 });
4990
4991                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4992                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4993                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4994                         short_channel_id: 5,
4995                         timestamp: 2,
4996                         flags: 0,
4997                         cltv_expiry_delta: 0,
4998                         htlc_minimum_msat: 0,
4999                         htlc_maximum_msat: 100_000,
5000                         fee_base_msat: 0,
5001                         fee_proportional_millionths: 0,
5002                         excess_data: Vec::new()
5003                 });
5004
5005                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5006                 // All channels should be 100 sats capacity. But for the fee experiment,
5007                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5008                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5009                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5010                 // so no matter how large are other channels,
5011                 // the whole path will be limited by 100 sats with just these 2 conditions:
5012                 // - channel 12 capacity is 250 sats
5013                 // - fee for channel 6 is 150 sats
5014                 // Let's test this by enforcing these 2 conditions and removing other limits.
5015                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5016                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5017                         short_channel_id: 12,
5018                         timestamp: 2,
5019                         flags: 0,
5020                         cltv_expiry_delta: 0,
5021                         htlc_minimum_msat: 0,
5022                         htlc_maximum_msat: 250_000,
5023                         fee_base_msat: 0,
5024                         fee_proportional_millionths: 0,
5025                         excess_data: Vec::new()
5026                 });
5027                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5028                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5029                         short_channel_id: 13,
5030                         timestamp: 2,
5031                         flags: 0,
5032                         cltv_expiry_delta: 0,
5033                         htlc_minimum_msat: 0,
5034                         htlc_maximum_msat: MAX_VALUE_MSAT,
5035                         fee_base_msat: 0,
5036                         fee_proportional_millionths: 0,
5037                         excess_data: Vec::new()
5038                 });
5039
5040                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5041                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5042                         short_channel_id: 6,
5043                         timestamp: 2,
5044                         flags: 0,
5045                         cltv_expiry_delta: 0,
5046                         htlc_minimum_msat: 0,
5047                         htlc_maximum_msat: MAX_VALUE_MSAT,
5048                         fee_base_msat: 150_000,
5049                         fee_proportional_millionths: 0,
5050                         excess_data: Vec::new()
5051                 });
5052                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5053                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5054                         short_channel_id: 11,
5055                         timestamp: 2,
5056                         flags: 0,
5057                         cltv_expiry_delta: 0,
5058                         htlc_minimum_msat: 0,
5059                         htlc_maximum_msat: MAX_VALUE_MSAT,
5060                         fee_base_msat: 0,
5061                         fee_proportional_millionths: 0,
5062                         excess_data: Vec::new()
5063                 });
5064
5065                 {
5066                         // Attempt to route more than available results in a failure.
5067                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5068                                         &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5069                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5070                         } else { panic!(); }
5071                 }
5072
5073                 {
5074                         // Now, attempt to route 200 sats (exact amount we can route).
5075                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5076                         assert_eq!(route.paths.len(), 2);
5077
5078                         let mut total_amount_paid_msat = 0;
5079                         for path in &route.paths {
5080                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5081                                 total_amount_paid_msat += path.final_value_msat();
5082                         }
5083                         assert_eq!(total_amount_paid_msat, 200_000);
5084                         assert_eq!(route.get_total_fees(), 150_000);
5085                 }
5086         }
5087
5088         #[test]
5089         fn mpp_with_last_hops() {
5090                 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5091                 // via a single last-hop route hint, we'd fail to route if we first collected routes
5092                 // totaling close but not quite enough to fund the full payment.
5093                 //
5094                 // This was because we considered last-hop hints to have exactly the sought payment amount
5095                 // instead of the amount we were trying to collect, needlessly limiting our path searching
5096                 // at the very first hop.
5097                 //
5098                 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5099                 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5100                 // to only have the remaining to-collect amount in available liquidity.
5101                 //
5102                 // This bug appeared in production in some specific channel configurations.
5103                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5104                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5105                 let scorer = ln_test_utils::TestScorer::new();
5106                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5107                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5108                 let config = UserConfig::default();
5109                 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5110                         .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5111                                 src_node_id: nodes[2],
5112                                 short_channel_id: 42,
5113                                 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5114                                 cltv_expiry_delta: 42,
5115                                 htlc_minimum_msat: None,
5116                                 htlc_maximum_msat: None,
5117                         }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5118
5119                 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5120                 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5121                 // would first use the no-fee route and then fail to find a path along the second route as
5122                 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5123                 // under 5% of our payment amount.
5124                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5125                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5126                         short_channel_id: 1,
5127                         timestamp: 2,
5128                         flags: 0,
5129                         cltv_expiry_delta: (5 << 4) | 5,
5130                         htlc_minimum_msat: 0,
5131                         htlc_maximum_msat: 99_000,
5132                         fee_base_msat: u32::max_value(),
5133                         fee_proportional_millionths: u32::max_value(),
5134                         excess_data: Vec::new()
5135                 });
5136                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5137                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5138                         short_channel_id: 2,
5139                         timestamp: 2,
5140                         flags: 0,
5141                         cltv_expiry_delta: (5 << 4) | 3,
5142                         htlc_minimum_msat: 0,
5143                         htlc_maximum_msat: 99_000,
5144                         fee_base_msat: u32::max_value(),
5145                         fee_proportional_millionths: u32::max_value(),
5146                         excess_data: Vec::new()
5147                 });
5148                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5149                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5150                         short_channel_id: 4,
5151                         timestamp: 2,
5152                         flags: 0,
5153                         cltv_expiry_delta: (4 << 4) | 1,
5154                         htlc_minimum_msat: 0,
5155                         htlc_maximum_msat: MAX_VALUE_MSAT,
5156                         fee_base_msat: 1,
5157                         fee_proportional_millionths: 0,
5158                         excess_data: Vec::new()
5159                 });
5160                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5161                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5162                         short_channel_id: 13,
5163                         timestamp: 2,
5164                         flags: 0|2, // Channel disabled
5165                         cltv_expiry_delta: (13 << 4) | 1,
5166                         htlc_minimum_msat: 0,
5167                         htlc_maximum_msat: MAX_VALUE_MSAT,
5168                         fee_base_msat: 0,
5169                         fee_proportional_millionths: 2000000,
5170                         excess_data: Vec::new()
5171                 });
5172
5173                 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5174                 // overpay at all.
5175                 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5176                 assert_eq!(route.paths.len(), 2);
5177                 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5178                 // Paths are manually ordered ordered by SCID, so:
5179                 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5180                 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5181                 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5182                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5183                 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5184                 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5185                 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5186                 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5187                 assert_eq!(route.get_total_fees(), 1);
5188                 assert_eq!(route.get_total_amount(), 100_000);
5189         }
5190
5191         #[test]
5192         fn drop_lowest_channel_mpp_route_test() {
5193                 // This test checks that low-capacity channel is dropped when after
5194                 // path finding we realize that we found more capacity than we need.
5195                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5196                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5197                 let scorer = ln_test_utils::TestScorer::new();
5198                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5199                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5200                 let config = UserConfig::default();
5201                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5202                         .with_max_channel_saturation_power_of_half(0);
5203
5204                 // We need a route consisting of 3 paths:
5205                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5206
5207                 // The first and the second paths should be sufficient, but the third should be
5208                 // cheaper, so that we select it but drop later.
5209
5210                 // First, we set limits on these (previously unlimited) channels.
5211                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5212
5213                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5214                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5215                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5216                         short_channel_id: 1,
5217                         timestamp: 2,
5218                         flags: 0,
5219                         cltv_expiry_delta: 0,
5220                         htlc_minimum_msat: 0,
5221                         htlc_maximum_msat: 100_000,
5222                         fee_base_msat: 0,
5223                         fee_proportional_millionths: 0,
5224                         excess_data: Vec::new()
5225                 });
5226                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5227                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5228                         short_channel_id: 3,
5229                         timestamp: 2,
5230                         flags: 0,
5231                         cltv_expiry_delta: 0,
5232                         htlc_minimum_msat: 0,
5233                         htlc_maximum_msat: 50_000,
5234                         fee_base_msat: 100,
5235                         fee_proportional_millionths: 0,
5236                         excess_data: Vec::new()
5237                 });
5238
5239                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5240                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5241                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5242                         short_channel_id: 12,
5243                         timestamp: 2,
5244                         flags: 0,
5245                         cltv_expiry_delta: 0,
5246                         htlc_minimum_msat: 0,
5247                         htlc_maximum_msat: 60_000,
5248                         fee_base_msat: 100,
5249                         fee_proportional_millionths: 0,
5250                         excess_data: Vec::new()
5251                 });
5252                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5253                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5254                         short_channel_id: 13,
5255                         timestamp: 2,
5256                         flags: 0,
5257                         cltv_expiry_delta: 0,
5258                         htlc_minimum_msat: 0,
5259                         htlc_maximum_msat: 60_000,
5260                         fee_base_msat: 0,
5261                         fee_proportional_millionths: 0,
5262                         excess_data: Vec::new()
5263                 });
5264
5265                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5266                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5267                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5268                         short_channel_id: 2,
5269                         timestamp: 2,
5270                         flags: 0,
5271                         cltv_expiry_delta: 0,
5272                         htlc_minimum_msat: 0,
5273                         htlc_maximum_msat: 20_000,
5274                         fee_base_msat: 0,
5275                         fee_proportional_millionths: 0,
5276                         excess_data: Vec::new()
5277                 });
5278                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5279                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5280                         short_channel_id: 4,
5281                         timestamp: 2,
5282                         flags: 0,
5283                         cltv_expiry_delta: 0,
5284                         htlc_minimum_msat: 0,
5285                         htlc_maximum_msat: 20_000,
5286                         fee_base_msat: 0,
5287                         fee_proportional_millionths: 0,
5288                         excess_data: Vec::new()
5289                 });
5290
5291                 {
5292                         // Attempt to route more than available results in a failure.
5293                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5294                                         &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5295                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5296                         } else { panic!(); }
5297                 }
5298
5299                 {
5300                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5301                         // Our algorithm should provide us with these 3 paths.
5302                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5303                         assert_eq!(route.paths.len(), 3);
5304                         let mut total_amount_paid_msat = 0;
5305                         for path in &route.paths {
5306                                 assert_eq!(path.hops.len(), 2);
5307                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5308                                 total_amount_paid_msat += path.final_value_msat();
5309                         }
5310                         assert_eq!(total_amount_paid_msat, 125_000);
5311                 }
5312
5313                 {
5314                         // Attempt to route without the last small cheap channel
5315                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5316                         assert_eq!(route.paths.len(), 2);
5317                         let mut total_amount_paid_msat = 0;
5318                         for path in &route.paths {
5319                                 assert_eq!(path.hops.len(), 2);
5320                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5321                                 total_amount_paid_msat += path.final_value_msat();
5322                         }
5323                         assert_eq!(total_amount_paid_msat, 90_000);
5324                 }
5325         }
5326
5327         #[test]
5328         fn min_criteria_consistency() {
5329                 // Test that we don't use an inconsistent metric between updating and walking nodes during
5330                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5331                 // was updated with a different criterion from the heap sorting, resulting in loops in
5332                 // calculated paths. We test for that specific case here.
5333
5334                 // We construct a network that looks like this:
5335                 //
5336                 //            node2 -1(3)2- node3
5337                 //              2          2
5338                 //               (2)     (4)
5339                 //                  1   1
5340                 //    node1 -1(5)2- node4 -1(1)2- node6
5341                 //    2
5342                 //   (6)
5343                 //        1
5344                 // our_node
5345                 //
5346                 // We create a loop on the side of our real path - our destination is node 6, with a
5347                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5348                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5349                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5350                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5351                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5352                 // "previous hop" being set to node 3, creating a loop in the path.
5353                 let secp_ctx = Secp256k1::new();
5354                 let logger = Arc::new(ln_test_utils::TestLogger::new());
5355                 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5356                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5357                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5358                 let scorer = ln_test_utils::TestScorer::new();
5359                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5360                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5361                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5362
5363                 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5364                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5365                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5366                         short_channel_id: 6,
5367                         timestamp: 1,
5368                         flags: 0,
5369                         cltv_expiry_delta: (6 << 4) | 0,
5370                         htlc_minimum_msat: 0,
5371                         htlc_maximum_msat: MAX_VALUE_MSAT,
5372                         fee_base_msat: 0,
5373                         fee_proportional_millionths: 0,
5374                         excess_data: Vec::new()
5375                 });
5376                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5377
5378                 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5379                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5380                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5381                         short_channel_id: 5,
5382                         timestamp: 1,
5383                         flags: 0,
5384                         cltv_expiry_delta: (5 << 4) | 0,
5385                         htlc_minimum_msat: 0,
5386                         htlc_maximum_msat: MAX_VALUE_MSAT,
5387                         fee_base_msat: 100,
5388                         fee_proportional_millionths: 0,
5389                         excess_data: Vec::new()
5390                 });
5391                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5392
5393                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5394                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5395                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5396                         short_channel_id: 4,
5397                         timestamp: 1,
5398                         flags: 0,
5399                         cltv_expiry_delta: (4 << 4) | 0,
5400                         htlc_minimum_msat: 0,
5401                         htlc_maximum_msat: MAX_VALUE_MSAT,
5402                         fee_base_msat: 0,
5403                         fee_proportional_millionths: 0,
5404                         excess_data: Vec::new()
5405                 });
5406                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5407
5408                 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5409                 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5410                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5411                         short_channel_id: 3,
5412                         timestamp: 1,
5413                         flags: 0,
5414                         cltv_expiry_delta: (3 << 4) | 0,
5415                         htlc_minimum_msat: 0,
5416                         htlc_maximum_msat: MAX_VALUE_MSAT,
5417                         fee_base_msat: 0,
5418                         fee_proportional_millionths: 0,
5419                         excess_data: Vec::new()
5420                 });
5421                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5422
5423                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5424                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5425                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5426                         short_channel_id: 2,
5427                         timestamp: 1,
5428                         flags: 0,
5429                         cltv_expiry_delta: (2 << 4) | 0,
5430                         htlc_minimum_msat: 0,
5431                         htlc_maximum_msat: MAX_VALUE_MSAT,
5432                         fee_base_msat: 0,
5433                         fee_proportional_millionths: 0,
5434                         excess_data: Vec::new()
5435                 });
5436
5437                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5438                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5439                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5440                         short_channel_id: 1,
5441                         timestamp: 1,
5442                         flags: 0,
5443                         cltv_expiry_delta: (1 << 4) | 0,
5444                         htlc_minimum_msat: 100,
5445                         htlc_maximum_msat: MAX_VALUE_MSAT,
5446                         fee_base_msat: 0,
5447                         fee_proportional_millionths: 0,
5448                         excess_data: Vec::new()
5449                 });
5450                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5451
5452                 {
5453                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
5454                         let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5455                         assert_eq!(route.paths.len(), 1);
5456                         assert_eq!(route.paths[0].hops.len(), 3);
5457
5458                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5459                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5460                         assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5461                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5462                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5463                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5464
5465                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5466                         assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5467                         assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5468                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5469                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5470                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5471
5472                         assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5473                         assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5474                         assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5475                         assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5476                         assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5477                         assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5478                 }
5479         }
5480
5481
5482         #[test]
5483         fn exact_fee_liquidity_limit() {
5484                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5485                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5486                 // we calculated fees on a higher value, resulting in us ignoring such paths.
5487                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5488                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5489                 let scorer = ln_test_utils::TestScorer::new();
5490                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5491                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5492                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5493
5494                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5495                 // send.
5496                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5497                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5498                         short_channel_id: 2,
5499                         timestamp: 2,
5500                         flags: 0,
5501                         cltv_expiry_delta: 0,
5502                         htlc_minimum_msat: 0,
5503                         htlc_maximum_msat: 85_000,
5504                         fee_base_msat: 0,
5505                         fee_proportional_millionths: 0,
5506                         excess_data: Vec::new()
5507                 });
5508
5509                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5510                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5511                         short_channel_id: 12,
5512                         timestamp: 2,
5513                         flags: 0,
5514                         cltv_expiry_delta: (4 << 4) | 1,
5515                         htlc_minimum_msat: 0,
5516                         htlc_maximum_msat: 270_000,
5517                         fee_base_msat: 0,
5518                         fee_proportional_millionths: 1000000,
5519                         excess_data: Vec::new()
5520                 });
5521
5522                 {
5523                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5524                         // 200% fee charged channel 13 in the 1-to-2 direction.
5525                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5526                         assert_eq!(route.paths.len(), 1);
5527                         assert_eq!(route.paths[0].hops.len(), 2);
5528
5529                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5530                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5531                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5532                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5533                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5534                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5535
5536                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5537                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5538                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5539                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5540                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5541                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5542                 }
5543         }
5544
5545         #[test]
5546         fn htlc_max_reduction_below_min() {
5547                 // Test that if, while walking the graph, we reduce the value being sent to meet an
5548                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5549                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5550                 // resulting in us thinking there is no possible path, even if other paths exist.
5551                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5552                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5553                 let scorer = ln_test_utils::TestScorer::new();
5554                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5555                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5556                 let config = UserConfig::default();
5557                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5558
5559                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5560                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5561                 // then try to send 90_000.
5562                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5563                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5564                         short_channel_id: 2,
5565                         timestamp: 2,
5566                         flags: 0,
5567                         cltv_expiry_delta: 0,
5568                         htlc_minimum_msat: 0,
5569                         htlc_maximum_msat: 80_000,
5570                         fee_base_msat: 0,
5571                         fee_proportional_millionths: 0,
5572                         excess_data: Vec::new()
5573                 });
5574                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5575                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5576                         short_channel_id: 4,
5577                         timestamp: 2,
5578                         flags: 0,
5579                         cltv_expiry_delta: (4 << 4) | 1,
5580                         htlc_minimum_msat: 90_000,
5581                         htlc_maximum_msat: MAX_VALUE_MSAT,
5582                         fee_base_msat: 0,
5583                         fee_proportional_millionths: 0,
5584                         excess_data: Vec::new()
5585                 });
5586
5587                 {
5588                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5589                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5590                         // expensive) channels 12-13 path.
5591                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5592                         assert_eq!(route.paths.len(), 1);
5593                         assert_eq!(route.paths[0].hops.len(), 2);
5594
5595                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5596                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5597                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5598                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5599                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5600                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5601
5602                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5603                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5604                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5605                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5606                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5607                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5608                 }
5609         }
5610
5611         #[test]
5612         fn multiple_direct_first_hops() {
5613                 // Previously we'd only ever considered one first hop path per counterparty.
5614                 // However, as we don't restrict users to one channel per peer, we really need to support
5615                 // looking at all first hop paths.
5616                 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5617                 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5618                 // route over multiple channels with the same first hop.
5619                 let secp_ctx = Secp256k1::new();
5620                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5621                 let logger = Arc::new(ln_test_utils::TestLogger::new());
5622                 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5623                 let scorer = ln_test_utils::TestScorer::new();
5624                 let config = UserConfig::default();
5625                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5626                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5627                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5628
5629                 {
5630                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5631                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5632                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5633                         ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5634                         assert_eq!(route.paths.len(), 1);
5635                         assert_eq!(route.paths[0].hops.len(), 1);
5636
5637                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5638                         assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5639                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5640                 }
5641                 {
5642                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5643                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5644                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5645                         ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5646                         assert_eq!(route.paths.len(), 2);
5647                         assert_eq!(route.paths[0].hops.len(), 1);
5648                         assert_eq!(route.paths[1].hops.len(), 1);
5649
5650                         assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5651                                 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5652
5653                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5654                         assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5655
5656                         assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5657                         assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5658                 }
5659
5660                 {
5661                         // If we have a bunch of outbound channels to the same node, where most are not
5662                         // sufficient to pay the full payment, but one is, we should default to just using the
5663                         // one single channel that has sufficient balance, avoiding MPP.
5664                         //
5665                         // If we have several options above the 3xpayment value threshold, we should pick the
5666                         // smallest of them, avoiding further fragmenting our available outbound balance to
5667                         // this node.
5668                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5669                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5670                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5671                                 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5672                                 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5673                                 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5674                                 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5675                                 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5676                                 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5677                         ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5678                         assert_eq!(route.paths.len(), 1);
5679                         assert_eq!(route.paths[0].hops.len(), 1);
5680
5681                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5682                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5683                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5684                 }
5685         }
5686
5687         #[test]
5688         fn prefers_shorter_route_with_higher_fees() {
5689                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5690                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5691                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5692
5693                 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5694                 let scorer = ln_test_utils::TestScorer::new();
5695                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5696                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5697                 let route = get_route(
5698                         &our_id, &payment_params, &network_graph.read_only(), None, 100,
5699                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5700                 ).unwrap();
5701                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5702
5703                 assert_eq!(route.get_total_fees(), 100);
5704                 assert_eq!(route.get_total_amount(), 100);
5705                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5706
5707                 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5708                 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5709                 let scorer = FixedPenaltyScorer::with_penalty(100);
5710                 let route = get_route(
5711                         &our_id, &payment_params, &network_graph.read_only(), None, 100,
5712                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5713                 ).unwrap();
5714                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5715
5716                 assert_eq!(route.get_total_fees(), 300);
5717                 assert_eq!(route.get_total_amount(), 100);
5718                 assert_eq!(path, vec![2, 4, 7, 10]);
5719         }
5720
5721         struct BadChannelScorer {
5722                 short_channel_id: u64,
5723         }
5724
5725         #[cfg(c_bindings)]
5726         impl Writeable for BadChannelScorer {
5727                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5728         }
5729         impl Score for BadChannelScorer {
5730                 type ScoreParams = ();
5731                 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5732                         if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5733                 }
5734
5735                 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5736                 fn payment_path_successful(&mut self, _path: &Path) {}
5737                 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5738                 fn probe_successful(&mut self, _path: &Path) {}
5739         }
5740
5741         struct BadNodeScorer {
5742                 node_id: NodeId,
5743         }
5744
5745         #[cfg(c_bindings)]
5746         impl Writeable for BadNodeScorer {
5747                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5748         }
5749
5750         impl Score for BadNodeScorer {
5751                 type ScoreParams = ();
5752                 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5753                         if *target == self.node_id { u64::max_value() } else { 0 }
5754                 }
5755
5756                 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5757                 fn payment_path_successful(&mut self, _path: &Path) {}
5758                 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5759                 fn probe_successful(&mut self, _path: &Path) {}
5760         }
5761
5762         #[test]
5763         fn avoids_routing_through_bad_channels_and_nodes() {
5764                 let (secp_ctx, network, _, _, logger) = build_graph();
5765                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5766                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5767                 let network_graph = network.read_only();
5768
5769                 // A path to nodes[6] exists when no penalties are applied to any channel.
5770                 let scorer = ln_test_utils::TestScorer::new();
5771                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5772                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5773                 let route = get_route(
5774                         &our_id, &payment_params, &network_graph, None, 100,
5775                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5776                 ).unwrap();
5777                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5778
5779                 assert_eq!(route.get_total_fees(), 100);
5780                 assert_eq!(route.get_total_amount(), 100);
5781                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5782
5783                 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5784                 let scorer = BadChannelScorer { short_channel_id: 6 };
5785                 let route = get_route(
5786                         &our_id, &payment_params, &network_graph, None, 100,
5787                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5788                 ).unwrap();
5789                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5790
5791                 assert_eq!(route.get_total_fees(), 300);
5792                 assert_eq!(route.get_total_amount(), 100);
5793                 assert_eq!(path, vec![2, 4, 7, 10]);
5794
5795                 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5796                 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5797                 match get_route(
5798                         &our_id, &payment_params, &network_graph, None, 100,
5799                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5800                 ) {
5801                         Err(LightningError { err, .. } ) => {
5802                                 assert_eq!(err, "Failed to find a path to the given destination");
5803                         },
5804                         Ok(_) => panic!("Expected error"),
5805                 }
5806         }
5807
5808         #[test]
5809         fn total_fees_single_path() {
5810                 let route = Route {
5811                         paths: vec![Path { hops: vec![
5812                                 RouteHop {
5813                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5814                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5815                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5816                                 },
5817                                 RouteHop {
5818                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5819                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5820                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5821                                 },
5822                                 RouteHop {
5823                                         pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5824                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5825                                         short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5826                                 },
5827                         ], blinded_tail: None }],
5828                         payment_params: None,
5829                 };
5830
5831                 assert_eq!(route.get_total_fees(), 250);
5832                 assert_eq!(route.get_total_amount(), 225);
5833         }
5834
5835         #[test]
5836         fn total_fees_multi_path() {
5837                 let route = Route {
5838                         paths: vec![Path { hops: vec![
5839                                 RouteHop {
5840                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5841                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5842                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5843                                 },
5844                                 RouteHop {
5845                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5846                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5847                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5848                                 },
5849                         ], blinded_tail: None }, Path { hops: vec![
5850                                 RouteHop {
5851                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5852                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5853                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5854                                 },
5855                                 RouteHop {
5856                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5857                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5858                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5859                                 },
5860                         ], blinded_tail: None }],
5861                         payment_params: None,
5862                 };
5863
5864                 assert_eq!(route.get_total_fees(), 200);
5865                 assert_eq!(route.get_total_amount(), 300);
5866         }
5867
5868         #[test]
5869         fn total_empty_route_no_panic() {
5870                 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5871                 // would both panic if the route was completely empty. We test to ensure they return 0
5872                 // here, even though its somewhat nonsensical as a route.
5873                 let route = Route { paths: Vec::new(), payment_params: None };
5874
5875                 assert_eq!(route.get_total_fees(), 0);
5876                 assert_eq!(route.get_total_amount(), 0);
5877         }
5878
5879         #[test]
5880         fn limits_total_cltv_delta() {
5881                 let (secp_ctx, network, _, _, logger) = build_graph();
5882                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5883                 let network_graph = network.read_only();
5884
5885                 let scorer = ln_test_utils::TestScorer::new();
5886
5887                 // Make sure that generally there is at least one route available
5888                 let feasible_max_total_cltv_delta = 1008;
5889                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5890                         .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5891                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5892                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5893                 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5894                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5895                 assert_ne!(path.len(), 0);
5896
5897                 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5898                 let fail_max_total_cltv_delta = 23;
5899                 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5900                         .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5901                 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5902                 {
5903                         Err(LightningError { err, .. } ) => {
5904                                 assert_eq!(err, "Failed to find a path to the given destination");
5905                         },
5906                         Ok(_) => panic!("Expected error"),
5907                 }
5908         }
5909
5910         #[test]
5911         fn avoids_recently_failed_paths() {
5912                 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5913                 // randomly inserting channels into it until we can't find a route anymore.
5914                 let (secp_ctx, network, _, _, logger) = build_graph();
5915                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5916                 let network_graph = network.read_only();
5917
5918                 let scorer = ln_test_utils::TestScorer::new();
5919                 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5920                         .with_max_path_count(1);
5921                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5922                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5923
5924                 // We should be able to find a route initially, and then after we fail a few random
5925                 // channels eventually we won't be able to any longer.
5926                 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5927                 loop {
5928                         if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5929                                 for chan in route.paths[0].hops.iter() {
5930                                         assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5931                                 }
5932                                 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5933                                         % route.paths[0].hops.len();
5934                                 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5935                         } else { break; }
5936                 }
5937         }
5938
5939         #[test]
5940         fn limits_path_length() {
5941                 let (secp_ctx, network, _, _, logger) = build_line_graph();
5942                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5943                 let network_graph = network.read_only();
5944
5945                 let scorer = ln_test_utils::TestScorer::new();
5946                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5947                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5948
5949                 // First check we can actually create a long route on this graph.
5950                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5951                 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5952                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5953                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5954                 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5955
5956                 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5957                 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5958                 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5959                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5960                 {
5961                         Err(LightningError { err, .. } ) => {
5962                                 assert_eq!(err, "Failed to find a path to the given destination");
5963                         },
5964                         Ok(_) => panic!("Expected error"),
5965                 }
5966         }
5967
5968         #[test]
5969         fn adds_and_limits_cltv_offset() {
5970                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5971                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5972
5973                 let scorer = ln_test_utils::TestScorer::new();
5974
5975                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5976                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5977                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5978                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5979                 assert_eq!(route.paths.len(), 1);
5980
5981                 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5982
5983                 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5984                 let mut route_default = route.clone();
5985                 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5986                 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5987                 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5988                 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5989                 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5990
5991                 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5992                 let mut route_limited = route.clone();
5993                 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5994                 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5995                 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5996                 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5997                 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5998         }
5999
6000         #[test]
6001         fn adds_plausible_cltv_offset() {
6002                 let (secp_ctx, network, _, _, logger) = build_graph();
6003                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6004                 let network_graph = network.read_only();
6005                 let network_nodes = network_graph.nodes();
6006                 let network_channels = network_graph.channels();
6007                 let scorer = ln_test_utils::TestScorer::new();
6008                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6009                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6010                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6011
6012                 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
6013                                                                   Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6014                 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6015
6016                 let mut path_plausibility = vec![];
6017
6018                 for p in route.paths {
6019                         // 1. Select random observation point
6020                         let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6021                         let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6022
6023                         prng.process_in_place(&mut random_bytes);
6024                         let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6025                         let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6026
6027                         // 2. Calculate what CLTV expiry delta we would observe there
6028                         let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6029
6030                         // 3. Starting from the observation point, find candidate paths
6031                         let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6032                         candidates.push_back((observation_point, vec![]));
6033
6034                         let mut found_plausible_candidate = false;
6035
6036                         'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6037                                 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6038                                         if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6039                                                 found_plausible_candidate = true;
6040                                                 break 'candidate_loop;
6041                                         }
6042                                 }
6043
6044                                 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6045                                         for channel_id in &cur_node.channels {
6046                                                 if let Some(channel_info) = network_channels.get(&channel_id) {
6047                                                         if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6048                                                                 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6049                                                                 if cur_path_cltv_deltas.iter().sum::<u32>()
6050                                                                         .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6051                                                                         let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6052                                                                         new_path_cltv_deltas.push(next_cltv_expiry_delta);
6053                                                                         candidates.push_back((*next_id, new_path_cltv_deltas));
6054                                                                 }
6055                                                         }
6056                                                 }
6057                                         }
6058                                 }
6059                         }
6060
6061                         path_plausibility.push(found_plausible_candidate);
6062                 }
6063                 assert!(path_plausibility.iter().all(|x| *x));
6064         }
6065
6066         #[test]
6067         fn builds_correct_path_from_hops() {
6068                 let (secp_ctx, network, _, _, logger) = build_graph();
6069                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6070                 let network_graph = network.read_only();
6071
6072                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6073                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6074
6075                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6076                 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6077                 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
6078                          &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
6079                 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6080                 assert_eq!(hops.len(), route.paths[0].hops.len());
6081                 for (idx, hop_pubkey) in hops.iter().enumerate() {
6082                         assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6083                 }
6084         }
6085
6086         #[test]
6087         fn avoids_saturating_channels() {
6088                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6089                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6090                 let decay_params = ProbabilisticScoringDecayParameters::default();
6091                 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6092
6093                 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6094                 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6095                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6096                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6097                         short_channel_id: 4,
6098                         timestamp: 2,
6099                         flags: 0,
6100                         cltv_expiry_delta: (4 << 4) | 1,
6101                         htlc_minimum_msat: 0,
6102                         htlc_maximum_msat: 250_000_000,
6103                         fee_base_msat: 0,
6104                         fee_proportional_millionths: 0,
6105                         excess_data: Vec::new()
6106                 });
6107                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6108                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6109                         short_channel_id: 13,
6110                         timestamp: 2,
6111                         flags: 0,
6112                         cltv_expiry_delta: (13 << 4) | 1,
6113                         htlc_minimum_msat: 0,
6114                         htlc_maximum_msat: 250_000_000,
6115                         fee_base_msat: 0,
6116                         fee_proportional_millionths: 0,
6117                         excess_data: Vec::new()
6118                 });
6119
6120                 let config = UserConfig::default();
6121                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6122                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6123                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6124                 // 100,000 sats is less than the available liquidity on each channel, set above.
6125                 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();
6126                 assert_eq!(route.paths.len(), 2);
6127                 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6128                         (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6129         }
6130
6131         #[cfg(not(feature = "no-std"))]
6132         pub(super) fn random_init_seed() -> u64 {
6133                 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6134                 use core::hash::{BuildHasher, Hasher};
6135                 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6136                 println!("Using seed of {}", seed);
6137                 seed
6138         }
6139
6140         #[test]
6141         #[cfg(not(feature = "no-std"))]
6142         fn generate_routes() {
6143                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6144
6145                 let logger = ln_test_utils::TestLogger::new();
6146                 let graph = match super::bench_utils::read_network_graph(&logger) {
6147                         Ok(f) => f,
6148                         Err(e) => {
6149                                 eprintln!("{}", e);
6150                                 return;
6151                         },
6152                 };
6153
6154                 let params = ProbabilisticScoringFeeParameters::default();
6155                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6156                 let features = super::Bolt11InvoiceFeatures::empty();
6157
6158                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
6159         }
6160
6161         #[test]
6162         #[cfg(not(feature = "no-std"))]
6163         fn generate_routes_mpp() {
6164                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6165
6166                 let logger = ln_test_utils::TestLogger::new();
6167                 let graph = match super::bench_utils::read_network_graph(&logger) {
6168                         Ok(f) => f,
6169                         Err(e) => {
6170                                 eprintln!("{}", e);
6171                                 return;
6172                         },
6173                 };
6174
6175                 let params = ProbabilisticScoringFeeParameters::default();
6176                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6177                 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6178
6179                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
6180         }
6181
6182         #[test]
6183         #[cfg(not(feature = "no-std"))]
6184         fn generate_large_mpp_routes() {
6185                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6186
6187                 let logger = ln_test_utils::TestLogger::new();
6188                 let graph = match super::bench_utils::read_network_graph(&logger) {
6189                         Ok(f) => f,
6190                         Err(e) => {
6191                                 eprintln!("{}", e);
6192                                 return;
6193                         },
6194                 };
6195
6196                 let params = ProbabilisticScoringFeeParameters::default();
6197                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6198                 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6199
6200                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 1_000_000, 2);
6201         }
6202
6203         #[test]
6204         fn honors_manual_penalties() {
6205                 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6206                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6207
6208                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6209                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6210
6211                 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6212                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6213
6214                 // First check set manual penalties are returned by the scorer.
6215                 let usage = ChannelUsage {
6216                         amount_msat: 0,
6217                         inflight_htlc_msat: 0,
6218                         effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6219                 };
6220                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6221                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6222                 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6223
6224                 // Then check we can get a normal route
6225                 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6226                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6227                 assert!(route.is_ok());
6228
6229                 // Then check that we can't get a route if we ban an intermediate node.
6230                 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6231                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6232                 assert!(route.is_err());
6233
6234                 // Finally make sure we can route again, when we remove the ban.
6235                 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6236                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6237                 assert!(route.is_ok());
6238         }
6239
6240         #[test]
6241         fn abide_by_route_hint_max_htlc() {
6242                 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6243                 // params in the final route.
6244                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6245                 let netgraph = network_graph.read_only();
6246                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6247                 let scorer = ln_test_utils::TestScorer::new();
6248                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6249                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6250                 let config = UserConfig::default();
6251
6252                 let max_htlc_msat = 50_000;
6253                 let route_hint_1 = RouteHint(vec![RouteHintHop {
6254                         src_node_id: nodes[2],
6255                         short_channel_id: 42,
6256                         fees: RoutingFees {
6257                                 base_msat: 100,
6258                                 proportional_millionths: 0,
6259                         },
6260                         cltv_expiry_delta: 10,
6261                         htlc_minimum_msat: None,
6262                         htlc_maximum_msat: Some(max_htlc_msat),
6263                 }]);
6264                 let dest_node_id = ln_test_utils::pubkey(42);
6265                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6266                         .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6267                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6268
6269                 // Make sure we'll error if our route hints don't have enough liquidity according to their
6270                 // htlc_maximum_msat.
6271                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6272                         &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6273                         &random_seed_bytes)
6274                 {
6275                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
6276                 } else { panic!(); }
6277
6278                 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6279                 let mut route_hint_2 = route_hint_1.clone();
6280                 route_hint_2.0[0].short_channel_id = 43;
6281                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6282                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6283                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6284                 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6285                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6286                 assert_eq!(route.paths.len(), 2);
6287                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6288                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6289         }
6290
6291         #[test]
6292         fn direct_channel_to_hints_with_max_htlc() {
6293                 // Check that if we have a first hop channel peer that's connected to multiple provided route
6294                 // hints, that we properly split the payment between the route hints if needed.
6295                 let logger = Arc::new(ln_test_utils::TestLogger::new());
6296                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6297                 let scorer = ln_test_utils::TestScorer::new();
6298                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6299                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6300                 let config = UserConfig::default();
6301
6302                 let our_node_id = ln_test_utils::pubkey(42);
6303                 let intermed_node_id = ln_test_utils::pubkey(43);
6304                 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6305
6306                 let amt_msat = 900_000;
6307                 let max_htlc_msat = 500_000;
6308                 let route_hint_1 = RouteHint(vec![RouteHintHop {
6309                         src_node_id: intermed_node_id,
6310                         short_channel_id: 44,
6311                         fees: RoutingFees {
6312                                 base_msat: 100,
6313                                 proportional_millionths: 0,
6314                         },
6315                         cltv_expiry_delta: 10,
6316                         htlc_minimum_msat: None,
6317                         htlc_maximum_msat: Some(max_htlc_msat),
6318                 }, RouteHintHop {
6319                         src_node_id: intermed_node_id,
6320                         short_channel_id: 45,
6321                         fees: RoutingFees {
6322                                 base_msat: 100,
6323                                 proportional_millionths: 0,
6324                         },
6325                         cltv_expiry_delta: 10,
6326                         htlc_minimum_msat: None,
6327                         // Check that later route hint max htlcs don't override earlier ones
6328                         htlc_maximum_msat: Some(max_htlc_msat - 50),
6329                 }]);
6330                 let mut route_hint_2 = route_hint_1.clone();
6331                 route_hint_2.0[0].short_channel_id = 46;
6332                 route_hint_2.0[1].short_channel_id = 47;
6333                 let dest_node_id = ln_test_utils::pubkey(44);
6334                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6335                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6336                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6337
6338                 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6339                         Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6340                         &random_seed_bytes).unwrap();
6341                 assert_eq!(route.paths.len(), 2);
6342                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6343                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6344                 assert_eq!(route.get_total_amount(), amt_msat);
6345
6346                 // Re-run but with two first hop channels connected to the same route hint peers that must be
6347                 // split between.
6348                 let first_hops = vec![
6349                         get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6350                         get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6351                 ];
6352                 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6353                         Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6354                         &random_seed_bytes).unwrap();
6355                 assert_eq!(route.paths.len(), 2);
6356                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6357                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6358                 assert_eq!(route.get_total_amount(), amt_msat);
6359
6360                 // Make sure this works for blinded route hints.
6361                 let blinded_path = BlindedPath {
6362                         introduction_node_id: intermed_node_id,
6363                         blinding_point: ln_test_utils::pubkey(42),
6364                         blinded_hops: vec![
6365                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6366                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6367                         ],
6368                 };
6369                 let blinded_payinfo = BlindedPayInfo {
6370                         fee_base_msat: 100,
6371                         fee_proportional_millionths: 0,
6372                         htlc_minimum_msat: 1,
6373                         htlc_maximum_msat: max_htlc_msat,
6374                         cltv_expiry_delta: 10,
6375                         features: BlindedHopFeatures::empty(),
6376                 };
6377                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6378                 let payment_params = PaymentParameters::blinded(vec![
6379                         (blinded_payinfo.clone(), blinded_path.clone()),
6380                         (blinded_payinfo.clone(), blinded_path.clone())])
6381                         .with_bolt12_features(bolt12_features).unwrap();
6382                 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6383                         Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6384                         &random_seed_bytes).unwrap();
6385                 assert_eq!(route.paths.len(), 2);
6386                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6387                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6388                 assert_eq!(route.get_total_amount(), amt_msat);
6389         }
6390
6391         #[test]
6392         fn blinded_route_ser() {
6393                 let blinded_path_1 = BlindedPath {
6394                         introduction_node_id: ln_test_utils::pubkey(42),
6395                         blinding_point: ln_test_utils::pubkey(43),
6396                         blinded_hops: vec![
6397                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6398                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6399                         ],
6400                 };
6401                 let blinded_path_2 = BlindedPath {
6402                         introduction_node_id: ln_test_utils::pubkey(46),
6403                         blinding_point: ln_test_utils::pubkey(47),
6404                         blinded_hops: vec![
6405                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6406                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6407                         ],
6408                 };
6409                 // (De)serialize a Route with 1 blinded path out of two total paths.
6410                 let mut route = Route { paths: vec![Path {
6411                         hops: vec![RouteHop {
6412                                 pubkey: ln_test_utils::pubkey(50),
6413                                 node_features: NodeFeatures::empty(),
6414                                 short_channel_id: 42,
6415                                 channel_features: ChannelFeatures::empty(),
6416                                 fee_msat: 100,
6417                                 cltv_expiry_delta: 0,
6418                         }],
6419                         blinded_tail: Some(BlindedTail {
6420                                 hops: blinded_path_1.blinded_hops,
6421                                 blinding_point: blinded_path_1.blinding_point,
6422                                 excess_final_cltv_expiry_delta: 40,
6423                                 final_value_msat: 100,
6424                         })}, Path {
6425                         hops: vec![RouteHop {
6426                                 pubkey: ln_test_utils::pubkey(51),
6427                                 node_features: NodeFeatures::empty(),
6428                                 short_channel_id: 43,
6429                                 channel_features: ChannelFeatures::empty(),
6430                                 fee_msat: 100,
6431                                 cltv_expiry_delta: 0,
6432                         }], blinded_tail: None }],
6433                         payment_params: None,
6434                 };
6435                 let encoded_route = route.encode();
6436                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6437                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6438                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6439
6440                 // (De)serialize a Route with two paths, each containing a blinded tail.
6441                 route.paths[1].blinded_tail = Some(BlindedTail {
6442                         hops: blinded_path_2.blinded_hops,
6443                         blinding_point: blinded_path_2.blinding_point,
6444                         excess_final_cltv_expiry_delta: 41,
6445                         final_value_msat: 101,
6446                 });
6447                 let encoded_route = route.encode();
6448                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6449                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6450                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6451         }
6452
6453         #[test]
6454         fn blinded_path_inflight_processing() {
6455                 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6456                 // account for the blinded tail's final amount_msat.
6457                 let mut inflight_htlcs = InFlightHtlcs::new();
6458                 let blinded_path = BlindedPath {
6459                         introduction_node_id: ln_test_utils::pubkey(43),
6460                         blinding_point: ln_test_utils::pubkey(48),
6461                         blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6462                 };
6463                 let path = Path {
6464                         hops: vec![RouteHop {
6465                                 pubkey: ln_test_utils::pubkey(42),
6466                                 node_features: NodeFeatures::empty(),
6467                                 short_channel_id: 42,
6468                                 channel_features: ChannelFeatures::empty(),
6469                                 fee_msat: 100,
6470                                 cltv_expiry_delta: 0,
6471                         },
6472                         RouteHop {
6473                                 pubkey: blinded_path.introduction_node_id,
6474                                 node_features: NodeFeatures::empty(),
6475                                 short_channel_id: 43,
6476                                 channel_features: ChannelFeatures::empty(),
6477                                 fee_msat: 1,
6478                                 cltv_expiry_delta: 0,
6479                         }],
6480                         blinded_tail: Some(BlindedTail {
6481                                 hops: blinded_path.blinded_hops,
6482                                 blinding_point: blinded_path.blinding_point,
6483                                 excess_final_cltv_expiry_delta: 0,
6484                                 final_value_msat: 200,
6485                         }),
6486                 };
6487                 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6488                 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6489                 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6490         }
6491
6492         #[test]
6493         fn blinded_path_cltv_shadow_offset() {
6494                 // Make sure we add a shadow offset when sending to blinded paths.
6495                 let blinded_path = BlindedPath {
6496                         introduction_node_id: ln_test_utils::pubkey(43),
6497                         blinding_point: ln_test_utils::pubkey(44),
6498                         blinded_hops: vec![
6499                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6500                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6501                         ],
6502                 };
6503                 let mut route = Route { paths: vec![Path {
6504                         hops: vec![RouteHop {
6505                                 pubkey: ln_test_utils::pubkey(42),
6506                                 node_features: NodeFeatures::empty(),
6507                                 short_channel_id: 42,
6508                                 channel_features: ChannelFeatures::empty(),
6509                                 fee_msat: 100,
6510                                 cltv_expiry_delta: 0,
6511                         },
6512                         RouteHop {
6513                                 pubkey: blinded_path.introduction_node_id,
6514                                 node_features: NodeFeatures::empty(),
6515                                 short_channel_id: 43,
6516                                 channel_features: ChannelFeatures::empty(),
6517                                 fee_msat: 1,
6518                                 cltv_expiry_delta: 0,
6519                         }
6520                         ],
6521                         blinded_tail: Some(BlindedTail {
6522                                 hops: blinded_path.blinded_hops,
6523                                 blinding_point: blinded_path.blinding_point,
6524                                 excess_final_cltv_expiry_delta: 0,
6525                                 final_value_msat: 200,
6526                         }),
6527                 }], payment_params: None};
6528
6529                 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6530                 let (_, network_graph, _, _, _) = build_line_graph();
6531                 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6532                 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6533                 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6534         }
6535
6536         #[test]
6537         fn simple_blinded_route_hints() {
6538                 do_simple_blinded_route_hints(1);
6539                 do_simple_blinded_route_hints(2);
6540                 do_simple_blinded_route_hints(3);
6541         }
6542
6543         fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6544                 // Check that we can generate a route to a blinded path with the expected hops.
6545                 let (secp_ctx, network, _, _, logger) = build_graph();
6546                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6547                 let network_graph = network.read_only();
6548
6549                 let scorer = ln_test_utils::TestScorer::new();
6550                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6551                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6552
6553                 let mut blinded_path = BlindedPath {
6554                         introduction_node_id: nodes[2],
6555                         blinding_point: ln_test_utils::pubkey(42),
6556                         blinded_hops: Vec::with_capacity(num_blinded_hops),
6557                 };
6558                 for i in 0..num_blinded_hops {
6559                         blinded_path.blinded_hops.push(
6560                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6561                         );
6562                 }
6563                 let blinded_payinfo = BlindedPayInfo {
6564                         fee_base_msat: 100,
6565                         fee_proportional_millionths: 500,
6566                         htlc_minimum_msat: 1000,
6567                         htlc_maximum_msat: 100_000_000,
6568                         cltv_expiry_delta: 15,
6569                         features: BlindedHopFeatures::empty(),
6570                 };
6571
6572                 let final_amt_msat = 1001;
6573                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6574                 let route = get_route(&our_id, &payment_params, &network_graph, None, final_amt_msat , Arc::clone(&logger),
6575                         &scorer, &(), &random_seed_bytes).unwrap();
6576                 assert_eq!(route.paths.len(), 1);
6577                 assert_eq!(route.paths[0].hops.len(), 2);
6578
6579                 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6580                 assert_eq!(tail.hops, blinded_path.blinded_hops);
6581                 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6582                 assert_eq!(tail.final_value_msat, 1001);
6583
6584                 let final_hop = route.paths[0].hops.last().unwrap();
6585                 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6586                 if tail.hops.len() > 1 {
6587                         assert_eq!(final_hop.fee_msat,
6588                                 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6589                         assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6590                 } else {
6591                         assert_eq!(final_hop.fee_msat, 0);
6592                         assert_eq!(final_hop.cltv_expiry_delta, 0);
6593                 }
6594         }
6595
6596         #[test]
6597         fn blinded_path_routing_errors() {
6598                 // Check that we can generate a route to a blinded path with the expected hops.
6599                 let (secp_ctx, network, _, _, logger) = build_graph();
6600                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6601                 let network_graph = network.read_only();
6602
6603                 let scorer = ln_test_utils::TestScorer::new();
6604                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6605                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6606
6607                 let mut invalid_blinded_path = BlindedPath {
6608                         introduction_node_id: nodes[2],
6609                         blinding_point: ln_test_utils::pubkey(42),
6610                         blinded_hops: vec![
6611                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
6612                         ],
6613                 };
6614                 let blinded_payinfo = BlindedPayInfo {
6615                         fee_base_msat: 100,
6616                         fee_proportional_millionths: 500,
6617                         htlc_minimum_msat: 1000,
6618                         htlc_maximum_msat: 100_000_000,
6619                         cltv_expiry_delta: 15,
6620                         features: BlindedHopFeatures::empty(),
6621                 };
6622
6623                 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
6624                 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
6625                 let payment_params = PaymentParameters::blinded(vec![
6626                         (blinded_payinfo.clone(), invalid_blinded_path.clone()),
6627                         (blinded_payinfo.clone(), invalid_blinded_path_2)]);
6628                 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6629                         &scorer, &(), &random_seed_bytes)
6630                 {
6631                         Err(LightningError { err, .. }) => {
6632                                 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
6633                         },
6634                         _ => panic!("Expected error")
6635                 }
6636
6637                 invalid_blinded_path.introduction_node_id = our_id;
6638                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
6639                 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6640                         &scorer, &(), &random_seed_bytes)
6641                 {
6642                         Err(LightningError { err, .. }) => {
6643                                 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
6644                         },
6645                         _ => panic!("Expected error")
6646                 }
6647
6648                 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
6649                 invalid_blinded_path.blinded_hops.clear();
6650                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
6651                 match get_route(&our_id, &payment_params, &network_graph, None, 1001, Arc::clone(&logger),
6652                         &scorer, &(), &random_seed_bytes)
6653                 {
6654                         Err(LightningError { err, .. }) => {
6655                                 assert_eq!(err, "0-hop blinded path provided");
6656                         },
6657                         _ => panic!("Expected error")
6658                 }
6659         }
6660
6661         #[test]
6662         fn matching_intro_node_paths_provided() {
6663                 // Check that if multiple blinded paths with the same intro node are provided in payment
6664                 // parameters, we'll return the correct paths in the resulting MPP route.
6665                 let (secp_ctx, network, _, _, logger) = build_graph();
6666                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6667                 let network_graph = network.read_only();
6668
6669                 let scorer = ln_test_utils::TestScorer::new();
6670                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6671                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6672                 let config = UserConfig::default();
6673
6674                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6675                 let blinded_path_1 = BlindedPath {
6676                         introduction_node_id: nodes[2],
6677                         blinding_point: ln_test_utils::pubkey(42),
6678                         blinded_hops: vec![
6679                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6680                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6681                         ],
6682                 };
6683                 let blinded_payinfo_1 = BlindedPayInfo {
6684                         fee_base_msat: 0,
6685                         fee_proportional_millionths: 0,
6686                         htlc_minimum_msat: 0,
6687                         htlc_maximum_msat: 30_000,
6688                         cltv_expiry_delta: 0,
6689                         features: BlindedHopFeatures::empty(),
6690                 };
6691
6692                 let mut blinded_path_2 = blinded_path_1.clone();
6693                 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
6694                 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
6695                 blinded_payinfo_2.htlc_maximum_msat = 70_000;
6696
6697                 let blinded_hints = vec![
6698                         (blinded_payinfo_1.clone(), blinded_path_1.clone()),
6699                         (blinded_payinfo_2.clone(), blinded_path_2.clone()),
6700                 ];
6701                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6702                         .with_bolt12_features(bolt12_features.clone()).unwrap();
6703
6704                 let route = get_route(&our_id, &payment_params, &network_graph, None,
6705                         100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6706                 assert_eq!(route.paths.len(), 2);
6707                 let mut total_amount_paid_msat = 0;
6708                 for path in route.paths.into_iter() {
6709                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6710                         if let Some(bt) = &path.blinded_tail {
6711                                 assert_eq!(bt.blinding_point,
6712                                         blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
6713                                                 .map(|(_, bp)| bp.blinding_point).unwrap());
6714                         } else { panic!(); }
6715                         total_amount_paid_msat += path.final_value_msat();
6716                 }
6717                 assert_eq!(total_amount_paid_msat, 100_000);
6718         }
6719
6720         #[test]
6721         fn direct_to_intro_node() {
6722                 // This previously caused a debug panic in the router when asserting
6723                 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
6724                 // direct channels we failed to account for the fee charged for use of the blinded path.
6725
6726                 // Build a graph:
6727                 // node0 -1(1)2 - node1
6728                 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
6729                 // doesn't account for the blinded path fee.
6730
6731                 let secp_ctx = Secp256k1::new();
6732                 let logger = Arc::new(ln_test_utils::TestLogger::new());
6733                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6734                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
6735                 let scorer = ln_test_utils::TestScorer::new();
6736                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6737                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6738
6739                 let amt_msat = 10_000_000;
6740                 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
6741                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
6742                         ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6743                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6744                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6745                         short_channel_id: 1,
6746                         timestamp: 1,
6747                         flags: 0,
6748                         cltv_expiry_delta: 42,
6749                         htlc_minimum_msat: 1_000,
6750                         htlc_maximum_msat: 10_000_000,
6751                         fee_base_msat: 800,
6752                         fee_proportional_millionths: 0,
6753                         excess_data: Vec::new()
6754                 });
6755                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6756                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6757                         short_channel_id: 1,
6758                         timestamp: 1,
6759                         flags: 1,
6760                         cltv_expiry_delta: 42,
6761                         htlc_minimum_msat: 1_000,
6762                         htlc_maximum_msat: 10_000_000,
6763                         fee_base_msat: 800,
6764                         fee_proportional_millionths: 0,
6765                         excess_data: Vec::new()
6766                 });
6767                 let first_hops = vec![
6768                         get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6769
6770                 let blinded_path = BlindedPath {
6771                         introduction_node_id: nodes[1],
6772                         blinding_point: ln_test_utils::pubkey(42),
6773                         blinded_hops: vec![
6774                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6775                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6776                         ],
6777                 };
6778                 let blinded_payinfo = BlindedPayInfo {
6779                         fee_base_msat: 1000,
6780                         fee_proportional_millionths: 0,
6781                         htlc_minimum_msat: 1000,
6782                         htlc_maximum_msat: MAX_VALUE_MSAT,
6783                         cltv_expiry_delta: 0,
6784                         features: BlindedHopFeatures::empty(),
6785                 };
6786                 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
6787
6788                 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
6789
6790                 let netgraph = network_graph.read_only();
6791                 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &payment_params, &netgraph,
6792                         Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6793                         &random_seed_bytes) {
6794                         assert_eq!(err, "Failed to find a path to the given destination");
6795                 } else { panic!("Expected error") }
6796
6797                 // Sending an exact amount accounting for the blinded path fee works.
6798                 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
6799                 let route = get_route(&nodes[0], &payment_params, &netgraph,
6800                         Some(&first_hops.iter().collect::<Vec<_>>()), amt_minus_blinded_path_fee,
6801                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6802                 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
6803                 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
6804         }
6805
6806         #[test]
6807         fn direct_to_matching_intro_nodes() {
6808                 // This previously caused us to enter `unreachable` code in the following situation:
6809                 // 1. We add a route candidate for intro_node contributing a high amount
6810                 // 2. We add a first_hop<>intro_node route candidate for the same high amount
6811                 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
6812                 //    amount, and update our route candidate for intro_node for the lower amount
6813                 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
6814                 //    lower contribution amount, but fail (this was previously caused by failure to account for
6815                 //    blinded path fees when adding first_hop<>intro_node candidates)
6816                 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
6817                 //    candidate still thinks its path is contributing the original higher amount. This caused us
6818                 //    to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
6819                 //    larger amount
6820                 let secp_ctx = Secp256k1::new();
6821                 let logger = Arc::new(ln_test_utils::TestLogger::new());
6822                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6823                 let scorer = ln_test_utils::TestScorer::new();
6824                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6825                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6826                 let config = UserConfig::default();
6827
6828                 // Values are taken from the fuzz input that uncovered this panic.
6829                 let amt_msat = 21_7020_5185_1403_2640;
6830                 let (_, _, _, nodes) = get_nodes(&secp_ctx);
6831                 let first_hops = vec![
6832                         get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
6833                                 18446744073709551615)];
6834
6835                 let blinded_path = BlindedPath {
6836                         introduction_node_id: nodes[1],
6837                         blinding_point: ln_test_utils::pubkey(42),
6838                         blinded_hops: vec![
6839                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
6840                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
6841                         ],
6842                 };
6843                 let blinded_payinfo = BlindedPayInfo {
6844                         fee_base_msat: 5046_2720,
6845                         fee_proportional_millionths: 0,
6846                         htlc_minimum_msat: 4503_5996_2737_0496,
6847                         htlc_maximum_msat: 45_0359_9627_3704_9600,
6848                         cltv_expiry_delta: 0,
6849                         features: BlindedHopFeatures::empty(),
6850                 };
6851                 let mut blinded_hints = vec![
6852                         (blinded_payinfo.clone(), blinded_path.clone()),
6853                         (blinded_payinfo.clone(), blinded_path.clone()),
6854                 ];
6855                 blinded_hints[1].0.fee_base_msat = 419_4304;
6856                 blinded_hints[1].0.fee_proportional_millionths = 257;
6857                 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
6858                 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
6859                 blinded_hints[1].0.cltv_expiry_delta = 0;
6860
6861                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6862                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
6863                         .with_bolt12_features(bolt12_features.clone()).unwrap();
6864
6865                 let netgraph = network_graph.read_only();
6866                 let route = get_route(&nodes[0], &payment_params, &netgraph,
6867                         Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat,
6868                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6869                 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
6870                 assert_eq!(route.get_total_amount(), amt_msat);
6871         }
6872 }
6873
6874 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6875 pub(crate) mod bench_utils {
6876         use super::*;
6877         use std::fs::File;
6878
6879         use bitcoin::hashes::Hash;
6880         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6881
6882         use crate::chain::transaction::OutPoint;
6883         use crate::sign::{EntropySource, KeysManager};
6884         use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6885         use crate::ln::features::Bolt11InvoiceFeatures;
6886         use crate::routing::gossip::NetworkGraph;
6887         use crate::util::config::UserConfig;
6888         use crate::util::ser::ReadableArgs;
6889         use crate::util::test_utils::TestLogger;
6890
6891         /// Tries to open a network graph file, or panics with a URL to fetch it.
6892         pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6893                 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6894                         .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6895                         .or_else(|_| { // Fall back to guessing based on the binary location
6896                                 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6897                                 let mut path = std::env::current_exe().unwrap();
6898                                 path.pop(); // lightning-...
6899                                 path.pop(); // deps
6900                                 path.pop(); // debug
6901                                 path.pop(); // target
6902                                 path.push("lightning");
6903                                 path.push("net_graph-2023-01-18.bin");
6904                                 File::open(path)
6905                         })
6906                         .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6907                                 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6908                                 let mut path = std::env::current_exe().unwrap();
6909                                 path.pop(); // bench...
6910                                 path.pop(); // deps
6911                                 path.pop(); // debug
6912                                 path.pop(); // target
6913                                 path.pop(); // bench
6914                                 path.push("lightning");
6915                                 path.push("net_graph-2023-01-18.bin");
6916                                 File::open(path)
6917                         })
6918                 .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");
6919                 #[cfg(require_route_graph_test)]
6920                 return Ok(res.unwrap());
6921                 #[cfg(not(require_route_graph_test))]
6922                 return res;
6923         }
6924
6925         pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6926                 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6927         }
6928
6929         pub(crate) fn payer_pubkey() -> PublicKey {
6930                 let secp_ctx = Secp256k1::new();
6931                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6932         }
6933
6934         #[inline]
6935         pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6936                 ChannelDetails {
6937                         channel_id: [0; 32],
6938                         counterparty: ChannelCounterparty {
6939                                 features: channelmanager::provided_init_features(&UserConfig::default()),
6940                                 node_id,
6941                                 unspendable_punishment_reserve: 0,
6942                                 forwarding_info: None,
6943                                 outbound_htlc_minimum_msat: None,
6944                                 outbound_htlc_maximum_msat: None,
6945                         },
6946                         funding_txo: Some(OutPoint {
6947                                 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6948                         }),
6949                         channel_type: None,
6950                         short_channel_id: Some(1),
6951                         inbound_scid_alias: None,
6952                         outbound_scid_alias: None,
6953                         channel_value_satoshis: 10_000_000_000,
6954                         user_channel_id: 0,
6955                         outbound_capacity_msat: 10_000_000_000,
6956                         next_outbound_htlc_minimum_msat: 0,
6957                         next_outbound_htlc_limit_msat: 10_000_000_000,
6958                         inbound_capacity_msat: 0,
6959                         unspendable_punishment_reserve: None,
6960                         confirmations_required: None,
6961                         confirmations: None,
6962                         force_close_spend_delay: None,
6963                         is_outbound: true,
6964                         is_channel_ready: true,
6965                         is_usable: true,
6966                         is_public: true,
6967                         inbound_htlc_minimum_msat: None,
6968                         inbound_htlc_maximum_msat: None,
6969                         config: None,
6970                         feerate_sat_per_1000_weight: None,
6971                         channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
6972                 }
6973         }
6974
6975         pub(crate) fn generate_test_routes<S: Score>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6976                 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
6977                 starting_amount: u64, route_count: usize,
6978         ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6979                 let payer = payer_pubkey();
6980                 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6981                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6982
6983                 let nodes = graph.read_only().nodes().clone();
6984                 let mut route_endpoints = Vec::new();
6985                 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6986                 // with some routes we picked being un-routable.
6987                 for _ in 0..route_count * 3 / 2 {
6988                         loop {
6989                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6990                                 let src = PublicKey::from_slice(nodes.unordered_keys()
6991                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6992                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6993                                 let dst = PublicKey::from_slice(nodes.unordered_keys()
6994                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6995                                 let params = PaymentParameters::from_node_id(dst, 42)
6996                                         .with_bolt11_features(features.clone()).unwrap();
6997                                 let first_hop = first_hop(src);
6998                                 let amt = starting_amount + seed % 1_000_000;
6999                                 let path_exists =
7000                                         get_route(&payer, &params, &graph.read_only(), Some(&[&first_hop]),
7001                                                 amt, &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok();
7002                                 if path_exists {
7003                                         // ...and seed the scorer with success and failure data...
7004                                         seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7005                                         let mut score_amt = seed % 1_000_000_000;
7006                                         loop {
7007                                                 // Generate fail/success paths for a wider range of potential amounts with
7008                                                 // MPP enabled to give us a chance to apply penalties for more potential
7009                                                 // routes.
7010                                                 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7011                                                 let params = PaymentParameters::from_node_id(dst, 42)
7012                                                         .with_bolt11_features(mpp_features).unwrap();
7013
7014                                                 let route_res = get_route(&payer, &params, &graph.read_only(),
7015                                                         Some(&[&first_hop]), score_amt, &TestLogger::new(), &scorer,
7016                                                         score_params, &random_seed_bytes);
7017                                                 if let Ok(route) = route_res {
7018                                                         for path in route.paths {
7019                                                                 if seed & 0x80 == 0 {
7020                                                                         scorer.payment_path_successful(&path);
7021                                                                 } else {
7022                                                                         let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7023                                                                         scorer.payment_path_failed(&path, short_channel_id);
7024                                                                 }
7025                                                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7026                                                         }
7027                                                         break;
7028                                                 }
7029                                                 // If we couldn't find a path with a higer amount, reduce and try again.
7030                                                 score_amt /= 100;
7031                                         }
7032
7033                                         route_endpoints.push((first_hop, params, amt));
7034                                         break;
7035                                 }
7036                         }
7037                 }
7038
7039                 // Because we've changed channel scores, it's possible we'll take different routes to the
7040                 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7041                 // requires a too-high CLTV delta.
7042                 route_endpoints.retain(|(first_hop, params, amt)| {
7043                         get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
7044                                 &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok()
7045                 });
7046                 route_endpoints.truncate(route_count);
7047                 assert_eq!(route_endpoints.len(), route_count);
7048                 route_endpoints
7049         }
7050 }
7051
7052 #[cfg(ldk_bench)]
7053 pub mod benches {
7054         use super::*;
7055         use crate::sign::{EntropySource, KeysManager};
7056         use crate::ln::channelmanager;
7057         use crate::ln::features::Bolt11InvoiceFeatures;
7058         use crate::routing::gossip::NetworkGraph;
7059         use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7060         use crate::util::config::UserConfig;
7061         use crate::util::logger::{Logger, Record};
7062         use crate::util::test_utils::TestLogger;
7063
7064         use criterion::Criterion;
7065
7066         struct DummyLogger {}
7067         impl Logger for DummyLogger {
7068                 fn log(&self, _record: &Record) {}
7069         }
7070
7071         pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7072                 let logger = TestLogger::new();
7073                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7074                 let scorer = FixedPenaltyScorer::with_penalty(0);
7075                 generate_routes(bench, &network_graph, scorer, &(), Bolt11InvoiceFeatures::empty(), 0,
7076                         "generate_routes_with_zero_penalty_scorer");
7077         }
7078
7079         pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7080                 let logger = TestLogger::new();
7081                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7082                 let scorer = FixedPenaltyScorer::with_penalty(0);
7083                 generate_routes(bench, &network_graph, scorer, &(),
7084                         channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7085                         "generate_mpp_routes_with_zero_penalty_scorer");
7086         }
7087
7088         pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7089                 let logger = TestLogger::new();
7090                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7091                 let params = ProbabilisticScoringFeeParameters::default();
7092                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7093                 generate_routes(bench, &network_graph, scorer, &params, Bolt11InvoiceFeatures::empty(), 0,
7094                         "generate_routes_with_probabilistic_scorer");
7095         }
7096
7097         pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7098                 let logger = TestLogger::new();
7099                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7100                 let params = ProbabilisticScoringFeeParameters::default();
7101                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7102                 generate_routes(bench, &network_graph, scorer, &params,
7103                         channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7104                         "generate_mpp_routes_with_probabilistic_scorer");
7105         }
7106
7107         pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7108                 let logger = TestLogger::new();
7109                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7110                 let params = ProbabilisticScoringFeeParameters::default();
7111                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7112                 generate_routes(bench, &network_graph, scorer, &params,
7113                         channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7114                         "generate_large_mpp_routes_with_probabilistic_scorer");
7115         }
7116
7117         fn generate_routes<S: Score>(
7118                 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7119                 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7120                 bench_name: &'static str,
7121         ) {
7122                 let payer = bench_utils::payer_pubkey();
7123                 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7124                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7125
7126                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7127                 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7128
7129                 // ...then benchmark finding paths between the nodes we learned.
7130                 let mut idx = 0;
7131                 bench.bench_function(bench_name, |b| b.iter(|| {
7132                         let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
7133                         assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
7134                                 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());
7135                         idx += 1;
7136                 }));
7137         }
7138 }