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