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