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