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