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