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