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