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