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