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