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