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