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