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