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