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