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