Individually lock NetworkGraph fields
[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 top-level routing/network map tracking logic lives here.
11 //!
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
14
15 use bitcoin::secp256k1::key::PublicKey;
16
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
20 use routing::network_graph::{NetworkGraph, RoutingFees};
21 use util::ser::{Writeable, Readable};
22 use util::logger::Logger;
23
24 use io;
25 use prelude::*;
26 use alloc::collections::BinaryHeap;
27 use core::cmp;
28 use core::ops::Deref;
29
30 /// A hop in a route
31 #[derive(Clone, Hash, PartialEq, Eq)]
32 pub struct RouteHop {
33         /// The node_id of the node at this hop.
34         pub pubkey: PublicKey,
35         /// The node_announcement features of the node at this hop. For the last hop, these may be
36         /// amended to match the features present in the invoice this node generated.
37         pub node_features: NodeFeatures,
38         /// The channel that should be used from the previous hop to reach this node.
39         pub short_channel_id: u64,
40         /// The channel_announcement features of the channel that should be used from the previous hop
41         /// to reach this node.
42         pub channel_features: ChannelFeatures,
43         /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
44         /// For the last hop, this should be the full value of the payment (might be more than
45         /// requested if we had to match htlc_minimum_msat).
46         pub fee_msat: u64,
47         /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
48         /// expected at the destination, in excess of the current block height.
49         pub cltv_expiry_delta: u32,
50 }
51
52 impl_writeable_tlv_based!(RouteHop, {
53         (0, pubkey, required),
54         (2, node_features, required),
55         (4, short_channel_id, required),
56         (6, channel_features, required),
57         (8, fee_msat, required),
58         (10, cltv_expiry_delta, required),
59 });
60
61 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
62 /// it can take multiple paths. Each path is composed of one or more hops through the network.
63 #[derive(Clone, Hash, PartialEq, Eq)]
64 pub struct Route {
65         /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
66         /// last RouteHop in each path must be the same.
67         /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
68         /// destination. Thus, this must always be at least length one. While the maximum length of any
69         /// given path is variable, keeping the length of any path to less than 20 should currently
70         /// ensure it is viable.
71         pub paths: Vec<Vec<RouteHop>>,
72 }
73
74 const SERIALIZATION_VERSION: u8 = 1;
75 const MIN_SERIALIZATION_VERSION: u8 = 1;
76
77 impl Writeable for Route {
78         fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
79                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
80                 (self.paths.len() as u64).write(writer)?;
81                 for hops in self.paths.iter() {
82                         (hops.len() as u8).write(writer)?;
83                         for hop in hops.iter() {
84                                 hop.write(writer)?;
85                         }
86                 }
87                 write_tlv_fields!(writer, {});
88                 Ok(())
89         }
90 }
91
92 impl Readable for Route {
93         fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
94                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
95                 let path_count: u64 = Readable::read(reader)?;
96                 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
97                 for _ in 0..path_count {
98                         let hop_count: u8 = Readable::read(reader)?;
99                         let mut hops = Vec::with_capacity(hop_count as usize);
100                         for _ in 0..hop_count {
101                                 hops.push(Readable::read(reader)?);
102                         }
103                         paths.push(hops);
104                 }
105                 read_tlv_fields!(reader, {});
106                 Ok(Route { paths })
107         }
108 }
109
110 /// A list of hops along a payment path terminating with a channel to the recipient.
111 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
112 pub struct RouteHint(pub Vec<RouteHintHop>);
113
114 /// A channel descriptor for a hop along a payment path.
115 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
116 pub struct RouteHintHop {
117         /// The node_id of the non-target end of the route
118         pub src_node_id: PublicKey,
119         /// The short_channel_id of this channel
120         pub short_channel_id: u64,
121         /// The fees which must be paid to use this channel
122         pub fees: RoutingFees,
123         /// The difference in CLTV values between this node and the next node.
124         pub cltv_expiry_delta: u16,
125         /// The minimum value, in msat, which must be relayed to the next hop.
126         pub htlc_minimum_msat: Option<u64>,
127         /// The maximum value in msat available for routing with a single HTLC.
128         pub htlc_maximum_msat: Option<u64>,
129 }
130
131 #[derive(Eq, PartialEq)]
132 struct RouteGraphNode {
133         pubkey: PublicKey,
134         lowest_fee_to_peer_through_node: u64,
135         lowest_fee_to_node: u64,
136         // The maximum value a yet-to-be-constructed payment path might flow through this node.
137         // This value is upper-bounded by us by:
138         // - how much is needed for a path being constructed
139         // - how much value can channels following this node (up to the destination) can contribute,
140         //   considering their capacity and fees
141         value_contribution_msat: u64,
142         /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
143         /// minimum, we use it, plus the fees required at each earlier hop to meet it.
144         path_htlc_minimum_msat: u64,
145 }
146
147 impl cmp::Ord for RouteGraphNode {
148         fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
149                 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
150                 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
151                 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
152         }
153 }
154
155 impl cmp::PartialOrd for RouteGraphNode {
156         fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
157                 Some(self.cmp(other))
158         }
159 }
160
161 struct DummyDirectionalChannelInfo {
162         cltv_expiry_delta: u32,
163         htlc_minimum_msat: u64,
164         htlc_maximum_msat: Option<u64>,
165         fees: RoutingFees,
166 }
167
168 /// It's useful to keep track of the hops associated with the fees required to use them,
169 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
170 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
171 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
172 #[derive(Clone, Debug)]
173 struct PathBuildingHop<'a> {
174         // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
175         // Note that node_features is calculated separately after our initial graph walk.
176         pubkey: PublicKey,
177         short_channel_id: u64,
178         channel_features: &'a ChannelFeatures,
179         fee_msat: u64,
180         cltv_expiry_delta: u32,
181
182         /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
183         src_lowest_inbound_fees: RoutingFees,
184         /// Fees of the channel used in this hop.
185         channel_fees: RoutingFees,
186         /// All the fees paid *after* this channel on the way to the destination
187         next_hops_fee_msat: u64,
188         /// Fee paid for the use of the current channel (see channel_fees).
189         /// The value will be actually deducted from the counterparty balance on the previous link.
190         hop_use_fee_msat: u64,
191         /// Used to compare channels when choosing the for routing.
192         /// Includes paying for the use of a hop and the following hops, as well as
193         /// an estimated cost of reaching this hop.
194         /// Might get stale when fees are recomputed. Primarily for internal use.
195         total_fee_msat: u64,
196         /// This is useful for update_value_and_recompute_fees to make sure
197         /// we don't fall below the minimum. Should not be updated manually and
198         /// generally should not be accessed.
199         htlc_minimum_msat: u64,
200         /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
201         /// walk and may be invalid thereafter.
202         path_htlc_minimum_msat: u64,
203         /// If we've already processed a node as the best node, we shouldn't process it again. Normally
204         /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
205         /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
206         /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
207         /// avoid processing them again.
208         was_processed: bool,
209         #[cfg(any(test, feature = "fuzztarget"))]
210         // In tests, we apply further sanity checks on cases where we skip nodes we already processed
211         // to ensure it is specifically in cases where the fee has gone down because of a decrease in
212         // value_contribution_msat, which requires tracking it here. See comments below where it is
213         // used for more info.
214         value_contribution_msat: u64,
215 }
216
217 // Instantiated with a list of hops with correct data in them collected during path finding,
218 // an instance of this struct should be further modified only via given methods.
219 #[derive(Clone)]
220 struct PaymentPath<'a> {
221         hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
222 }
223
224 impl<'a> PaymentPath<'a> {
225         // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
226         fn get_value_msat(&self) -> u64 {
227                 self.hops.last().unwrap().0.fee_msat
228         }
229
230         fn get_total_fee_paid_msat(&self) -> u64 {
231                 if self.hops.len() < 1 {
232                         return 0;
233                 }
234                 let mut result = 0;
235                 // Can't use next_hops_fee_msat because it gets outdated.
236                 for (i, (hop, _)) in self.hops.iter().enumerate() {
237                         if i != self.hops.len() - 1 {
238                                 result += hop.fee_msat;
239                         }
240                 }
241                 return result;
242         }
243
244         // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
245         // to change fees may result in an inconsistency.
246         //
247         // Sometimes we call this function right after constructing a path which is inconsistent in
248         // that it the value being transferred has decreased while we were doing path finding, leading
249         // to the fees being paid not lining up with the actual limits.
250         //
251         // Note that this function is not aware of the available_liquidity limit, and thus does not
252         // support increasing the value being transferred.
253         fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
254                 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
255
256                 let mut total_fee_paid_msat = 0 as u64;
257                 for i in (0..self.hops.len()).rev() {
258                         let last_hop = i == self.hops.len() - 1;
259
260                         // For non-last-hop, this value will represent the fees paid on the current hop. It
261                         // will consist of the fees for the use of the next hop, and extra fees to match
262                         // htlc_minimum_msat of the current channel. Last hop is handled separately.
263                         let mut cur_hop_fees_msat = 0;
264                         if !last_hop {
265                                 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
266                         }
267
268                         let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
269                         cur_hop.next_hops_fee_msat = total_fee_paid_msat;
270                         // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
271                         // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
272                         // set it too high just to maliciously take more fees by exploiting this
273                         // match htlc_minimum_msat logic.
274                         let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
275                         if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
276                                 // Note that there is a risk that *previous hops* (those closer to us, as we go
277                                 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
278                                 //
279                                 // This might make us end up with a broken route, although this should be super-rare
280                                 // in practice, both because of how healthy channels look like, and how we pick
281                                 // channels in add_entry.
282                                 // Also, this can't be exploited more heavily than *announce a free path and fail
283                                 // all payments*.
284                                 cur_hop_transferred_amount_msat += extra_fees_msat;
285                                 total_fee_paid_msat += extra_fees_msat;
286                                 cur_hop_fees_msat += extra_fees_msat;
287                         }
288
289                         if last_hop {
290                                 // Final hop is a special case: it usually has just value_msat (by design), but also
291                                 // it still could overpay for the htlc_minimum_msat.
292                                 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
293                         } else {
294                                 // Propagate updated fees for the use of the channels to one hop back, where they
295                                 // will be actually paid (fee_msat). The last hop is handled above separately.
296                                 cur_hop.fee_msat = cur_hop_fees_msat;
297                         }
298
299                         // Fee for the use of the current hop which will be deducted on the previous hop.
300                         // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
301                         // this channel is free for us.
302                         if i != 0 {
303                                 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
304                                         cur_hop.hop_use_fee_msat = new_fee;
305                                         total_fee_paid_msat += new_fee;
306                                 } else {
307                                         // It should not be possible because this function is called only to reduce the
308                                         // value. In that case, compute_fee was already called with the same fees for
309                                         // larger amount and there was no overflow.
310                                         unreachable!();
311                                 }
312                         }
313                 }
314         }
315 }
316
317 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
318         let proportional_fee_millions =
319                 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
320         if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
321                         (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
322
323                 Some(new_fee)
324         } else {
325                 // This function may be (indirectly) called without any verification,
326                 // with channel_fees provided by a caller. We should handle it gracefully.
327                 None
328         }
329 }
330
331 /// Gets a keysend route from us (payer) to the given target node (payee). This is needed because
332 /// keysend payments do not have an invoice from which to pull the payee's supported features, which
333 /// makes it tricky to otherwise supply the `payee_features` parameter of `get_route`.
334 pub fn get_keysend_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee:
335                        &PublicKey, first_hops: Option<&[&ChannelDetails]>, last_hops: &[&RouteHint],
336                        final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route,
337                        LightningError> where L::Target: Logger {
338         let invoice_features = InvoiceFeatures::for_keysend();
339         get_route(our_node_id, network, payee, Some(invoice_features), first_hops, last_hops,
340             final_value_msat, final_cltv, logger)
341 }
342
343 /// Gets a route from us (payer) to the given target node (payee).
344 ///
345 /// If the payee provided features in their invoice, they should be provided via payee_features.
346 /// Without this, MPP will only be used if the payee's features are available in the network graph.
347 ///
348 /// Private routing paths between a public node and the target may be included in `last_hops`.
349 /// Currently, only the last hop in each path is considered.
350 ///
351 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
352 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
353 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
354 /// in first_hops will be used.
355 ///
356 /// Panics if first_hops contains channels without short_channel_ids
357 /// (ChannelManager::list_usable_channels will never include such channels).
358 ///
359 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
360 /// equal), however the enabled/disabled bit on such channels as well as the
361 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
362 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
363         last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
364         // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
365         // uptime/success in using a node in the past.
366         if *payee == *our_node_id {
367                 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
368         }
369
370         if final_value_msat > MAX_VALUE_MSAT {
371                 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
372         }
373
374         if final_value_msat == 0 {
375                 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
376         }
377
378         for route in last_hops.iter() {
379                 for hop in &route.0 {
380                         if hop.src_node_id == *payee {
381                                 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
382                         }
383                 }
384         }
385
386         // The general routing idea is the following:
387         // 1. Fill first/last hops communicated by the caller.
388         // 2. Attempt to construct a path from payer to payee for transferring
389         //    any ~sufficient (described later) value.
390         //    If succeed, remember which channels were used and how much liquidity they have available,
391         //    so that future paths don't rely on the same liquidity.
392         // 3. Prooceed to the next step if:
393         //    - we hit the recommended target value;
394         //    - OR if we could not construct a new path. Any next attempt will fail too.
395         //    Otherwise, repeat step 2.
396         // 4. See if we managed to collect paths which aggregately are able to transfer target value
397         //    (not recommended value). If yes, proceed. If not, fail routing.
398         // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
399         // 6. Of all the found paths, select only those with the lowest total fee.
400         // 7. The last path in every selected route is likely to be more than we need.
401         //    Reduce its value-to-transfer and recompute fees.
402         // 8. Choose the best route by the lowest total fee.
403
404         // As for the actual search algorithm,
405         // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
406         // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
407         //
408         // We are not a faithful Dijkstra's implementation because we can change values which impact
409         // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
410         // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
411         // the value we are currently attempting to send over a path, we simply reduce the value being
412         // sent along the path for any hops after that channel. This may imply that later fees (which
413         // we've already tabulated) are lower because a smaller value is passing through the channels
414         // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
415         // channels which were selected earlier (and which may still be used for other paths without a
416         // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
417         // de-preferenced.
418         //
419         // One potentially problematic case for this algorithm would be if there are many
420         // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
421         // graph walking), we may never find a path which is not liquidity-limited and has lower
422         // proportional fee (and only lower absolute fee when considering the ultimate value sent).
423         // Because we only consider paths with at least 5% of the total value being sent, the damage
424         // from such a case should be limited, however this could be further reduced in the future by
425         // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
426         // limits for the purposes of fee calculation.
427         //
428         // Alternatively, we could store more detailed path information in the heap (targets, below)
429         // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
430         // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
431         // and practically (as we would need to store dynamically-allocated path information in heap
432         // objects, increasing malloc traffic and indirect memory access significantly). Further, the
433         // results of such an algorithm would likely be biased towards lower-value paths.
434         //
435         // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
436         // outside of our current search value, running a path search more times to gather candidate
437         // paths at different values. While this may be acceptable, further path searches may increase
438         // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
439         // graph for candidate paths, calculating the maximum value which can realistically be sent at
440         // the same time, remaining generic across different payment values.
441         //
442         // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
443         // to use as the A* heuristic beyond just the cost to get one node further than the current
444         // one.
445
446         let network_channels = network.get_channels();
447         let network_nodes = network.get_nodes();
448         let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
449                 cltv_expiry_delta: 0,
450                 htlc_minimum_msat: 0,
451                 htlc_maximum_msat: None,
452                 fees: RoutingFees {
453                         base_msat: 0,
454                         proportional_millionths: 0,
455                 }
456         };
457
458         // Allow MPP only if we have a features set from somewhere that indicates the payee supports
459         // it. If the payee supports it they're supposed to include it in the invoice, so that should
460         // work reliably.
461         let allow_mpp = if let Some(features) = &payee_features {
462                 features.supports_basic_mpp()
463         } else if let Some(node) = network_nodes.get(&payee) {
464                 if let Some(node_info) = node.announcement_info.as_ref() {
465                         node_info.features.supports_basic_mpp()
466                 } else { false }
467         } else { false };
468
469         // Step (1).
470         // Prepare the data we'll use for payee-to-payer search by
471         // inserting first hops suggested by the caller as targets.
472         // Our search will then attempt to reach them while traversing from the payee node.
473         let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
474                 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
475         if let Some(hops) = first_hops {
476                 for chan in hops {
477                         let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
478                         if chan.counterparty.node_id == *our_node_id {
479                                 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
480                         }
481                         first_hop_targets.insert(chan.counterparty.node_id, (short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
482                 }
483                 if first_hop_targets.is_empty() {
484                         return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
485                 }
486         }
487
488         let empty_channel_features = ChannelFeatures::empty();
489
490         // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
491         // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
492         // adding duplicate entries when we find a better path to a given node.
493         let mut targets = BinaryHeap::new();
494
495         // Map from node_id to information about the best current path to that node, including feerate
496         // information.
497         let mut dist = HashMap::with_capacity(network_nodes.len());
498
499         // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
500         // indicating that we may wish to try again with a higher value, potentially paying to meet an
501         // htlc_minimum with extra fees while still finding a cheaper path.
502         let mut hit_minimum_limit;
503
504         // When arranging a route, we select multiple paths so that we can make a multi-path payment.
505         // We start with a path_value of the exact amount we want, and if that generates a route we may
506         // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
507         // amount we want in total across paths, selecting the best subset at the end.
508         const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
509         let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
510         let mut path_value_msat = final_value_msat;
511
512         // We don't want multiple paths (as per MPP) share liquidity of the same channels.
513         // This map allows paths to be aware of the channel use by other paths in the same call.
514         // This would help to make a better path finding decisions and not "overbook" channels.
515         // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
516         let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
517
518         // Keeping track of how much value we already collected across other paths. Helps to decide:
519         // - how much a new path should be transferring (upper bound);
520         // - whether a channel should be disregarded because
521         //   it's available liquidity is too small comparing to how much more we need to collect;
522         // - when we want to stop looking for new paths.
523         let mut already_collected_value_msat = 0;
524
525         log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee, our_node_id, final_value_msat);
526
527         macro_rules! add_entry {
528                 // Adds entry which goes from $src_node_id to $dest_node_id
529                 // over the channel with id $chan_id with fees described in
530                 // $directional_info.
531                 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
532                 // since that value has to be transferred over this channel.
533                 // Returns whether this channel caused an update to `targets`.
534                 ( $chan_id: expr, $src_node_id: expr, $dest_node_id: expr, $directional_info: expr, $capacity_sats: expr, $chan_features: expr, $next_hops_fee_msat: expr,
535                    $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
536                         // We "return" whether we updated the path at the end, via this:
537                         let mut did_add_update_path_to_src_node = false;
538                         // Channels to self should not be used. This is more of belt-and-suspenders, because in
539                         // practice these cases should be caught earlier:
540                         // - for regular channels at channel announcement (TODO)
541                         // - for first and last hops early in get_route
542                         if $src_node_id != $dest_node_id.clone() {
543                                 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
544                                         let mut initial_liquidity_available_msat = None;
545                                         if let Some(capacity_sats) = $capacity_sats {
546                                                 initial_liquidity_available_msat = Some(capacity_sats * 1000);
547                                         }
548
549                                         if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
550                                                 if let Some(available_msat) = initial_liquidity_available_msat {
551                                                         initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
552                                                 } else {
553                                                         initial_liquidity_available_msat = Some(htlc_maximum_msat);
554                                                 }
555                                         }
556
557                                         match initial_liquidity_available_msat {
558                                                 Some(available_msat) => available_msat,
559                                                 // We assume channels with unknown balance have
560                                                 // a capacity of 0.0025 BTC (or 250_000 sats).
561                                                 None => 250_000 * 1000
562                                         }
563                                 });
564
565                                 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
566                                 // It may be misleading because we might later choose to reduce the value transferred
567                                 // over these channels, and the channel which was insufficient might become sufficient.
568                                 // Worst case: we drop a good channel here because it can't cover the high following
569                                 // fees caused by one expensive channel, but then this channel could have been used
570                                 // if the amount being transferred over this path is lower.
571                                 // We do this for now, but this is a subject for removal.
572                                 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
573
574                                         // Routing Fragmentation Mitigation heuristic:
575                                         //
576                                         // Routing fragmentation across many payment paths increases the overall routing
577                                         // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
578                                         // Taking too many smaller paths also increases the chance of payment failure.
579                                         // Thus to avoid this effect, we require from our collected links to provide
580                                         // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
581                                         //
582                                         // This requirement is currently 5% of the remaining-to-be-collected value.
583                                         // This means as we successfully advance in our collection,
584                                         // the absolute liquidity contribution is lowered,
585                                         // thus increasing the number of potential channels to be selected.
586
587                                         // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
588                                         // or 100% if we're not allowed to do multipath payments.
589                                         let minimal_value_contribution_msat: u64 = if allow_mpp {
590                                                 (recommended_value_msat - already_collected_value_msat + 19) / 20
591                                         } else {
592                                                 final_value_msat
593                                         };
594                                         // Verify the liquidity offered by this channel complies to the minimal contribution.
595                                         let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
596
597                                         let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
598                                         // Includes paying fees for the use of the following channels.
599                                         let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
600                                                 Some(result) => result,
601                                                 // Can't overflow due to how the values were computed right above.
602                                                 None => unreachable!(),
603                                         };
604                                         #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
605                                         let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
606                                                 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
607
608                                         // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
609                                         // bother considering this channel.
610                                         // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
611                                         // be only reduced later (not increased), so this channel should just be skipped
612                                         // as not sufficient.
613                                         if !over_path_minimum_msat {
614                                                 hit_minimum_limit = true;
615                                         } else if contributes_sufficient_value {
616                                                 // Note that low contribution here (limited by available_liquidity_msat)
617                                                 // might violate htlc_minimum_msat on the hops which are next along the
618                                                 // payment path (upstream to the payee). To avoid that, we recompute path
619                                                 // path fees knowing the final path contribution after constructing it.
620                                                 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
621                                                                 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
622                                                         Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
623                                                         _ => u64::max_value()
624                                                 };
625                                                 let hm_entry = dist.entry(&$src_node_id);
626                                                 let old_entry = hm_entry.or_insert_with(|| {
627                                                         // If there was previously no known way to access
628                                                         // the source node (recall it goes payee-to-payer) of $chan_id, first add
629                                                         // a semi-dummy record just to compute the fees to reach the source node.
630                                                         // This will affect our decision on selecting $chan_id
631                                                         // as a way to reach the $dest_node_id.
632                                                         let mut fee_base_msat = u32::max_value();
633                                                         let mut fee_proportional_millionths = u32::max_value();
634                                                         if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
635                                                                 fee_base_msat = fees.base_msat;
636                                                                 fee_proportional_millionths = fees.proportional_millionths;
637                                                         }
638                                                         PathBuildingHop {
639                                                                 pubkey: $dest_node_id.clone(),
640                                                                 short_channel_id: 0,
641                                                                 channel_features: $chan_features,
642                                                                 fee_msat: 0,
643                                                                 cltv_expiry_delta: 0,
644                                                                 src_lowest_inbound_fees: RoutingFees {
645                                                                         base_msat: fee_base_msat,
646                                                                         proportional_millionths: fee_proportional_millionths,
647                                                                 },
648                                                                 channel_fees: $directional_info.fees,
649                                                                 next_hops_fee_msat: u64::max_value(),
650                                                                 hop_use_fee_msat: u64::max_value(),
651                                                                 total_fee_msat: u64::max_value(),
652                                                                 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
653                                                                 path_htlc_minimum_msat,
654                                                                 was_processed: false,
655                                                                 #[cfg(any(test, feature = "fuzztarget"))]
656                                                                 value_contribution_msat,
657                                                         }
658                                                 });
659
660                                                 #[allow(unused_mut)] // We only use the mut in cfg(test)
661                                                 let mut should_process = !old_entry.was_processed;
662                                                 #[cfg(any(test, feature = "fuzztarget"))]
663                                                 {
664                                                         // In test/fuzzing builds, we do extra checks to make sure the skipping
665                                                         // of already-seen nodes only happens in cases we expect (see below).
666                                                         if !should_process { should_process = true; }
667                                                 }
668
669                                                 if should_process {
670                                                         let mut hop_use_fee_msat = 0;
671                                                         let mut total_fee_msat = $next_hops_fee_msat;
672
673                                                         // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
674                                                         // will have the same effective-fee
675                                                         if $src_node_id != *our_node_id {
676                                                                 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
677                                                                         // max_value means we'll always fail
678                                                                         // the old_entry.total_fee_msat > total_fee_msat check
679                                                                         None => total_fee_msat = u64::max_value(),
680                                                                         Some(fee_msat) => {
681                                                                                 hop_use_fee_msat = fee_msat;
682                                                                                 total_fee_msat += hop_use_fee_msat;
683                                                                                 // When calculating the lowest inbound fees to a node, we
684                                                                                 // calculate fees here not based on the actual value we think
685                                                                                 // will flow over this channel, but on the minimum value that
686                                                                                 // we'll accept flowing over it. The minimum accepted value
687                                                                                 // is a constant through each path collection run, ensuring
688                                                                                 // consistent basis. Otherwise we may later find a
689                                                                                 // different path to the source node that is more expensive,
690                                                                                 // but which we consider to be cheaper because we are capacity
691                                                                                 // constrained and the relative fee becomes lower.
692                                                                                 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
693                                                                                                 .map(|a| a.checked_add(total_fee_msat)) {
694                                                                                         Some(Some(v)) => {
695                                                                                                 total_fee_msat = v;
696                                                                                         },
697                                                                                         _ => {
698                                                                                                 total_fee_msat = u64::max_value();
699                                                                                         }
700                                                                                 };
701                                                                         }
702                                                                 }
703                                                         }
704
705                                                         let new_graph_node = RouteGraphNode {
706                                                                 pubkey: $src_node_id,
707                                                                 lowest_fee_to_peer_through_node: total_fee_msat,
708                                                                 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
709                                                                 value_contribution_msat: value_contribution_msat,
710                                                                 path_htlc_minimum_msat,
711                                                         };
712
713                                                         // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
714                                                         // if this way is cheaper than the already known
715                                                         // (considering the cost to "reach" this channel from the route destination,
716                                                         // the cost of using this channel,
717                                                         // and the cost of routing to the source node of this channel).
718                                                         // Also, consider that htlc_minimum_msat_difference, because we might end up
719                                                         // paying it. Consider the following exploit:
720                                                         // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
721                                                         // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
722                                                         // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
723                                                         // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
724                                                         // to this channel.
725                                                         // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
726                                                         // but it may require additional tracking - we don't want to double-count
727                                                         // the fees included in $next_hops_path_htlc_minimum_msat, but also
728                                                         // can't use something that may decrease on future hops.
729                                                         let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
730                                                         let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
731
732                                                         if !old_entry.was_processed && new_cost < old_cost {
733                                                                 targets.push(new_graph_node);
734                                                                 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
735                                                                 old_entry.hop_use_fee_msat = hop_use_fee_msat;
736                                                                 old_entry.total_fee_msat = total_fee_msat;
737                                                                 old_entry.pubkey = $dest_node_id.clone();
738                                                                 old_entry.short_channel_id = $chan_id.clone();
739                                                                 old_entry.channel_features = $chan_features;
740                                                                 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
741                                                                 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
742                                                                 old_entry.channel_fees = $directional_info.fees;
743                                                                 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
744                                                                 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
745                                                                 #[cfg(any(test, feature = "fuzztarget"))]
746                                                                 {
747                                                                         old_entry.value_contribution_msat = value_contribution_msat;
748                                                                 }
749                                                                 did_add_update_path_to_src_node = true;
750                                                         } else if old_entry.was_processed && new_cost < old_cost {
751                                                                 #[cfg(any(test, feature = "fuzztarget"))]
752                                                                 {
753                                                                         // If we're skipping processing a node which was previously
754                                                                         // processed even though we found another path to it with a
755                                                                         // cheaper fee, check that it was because the second path we
756                                                                         // found (which we are processing now) has a lower value
757                                                                         // contribution due to an HTLC minimum limit.
758                                                                         //
759                                                                         // e.g. take a graph with two paths from node 1 to node 2, one
760                                                                         // through channel A, and one through channel B. Channel A and
761                                                                         // B are both in the to-process heap, with their scores set by
762                                                                         // a higher htlc_minimum than fee.
763                                                                         // Channel A is processed first, and the channels onwards from
764                                                                         // node 1 are added to the to-process heap. Thereafter, we pop
765                                                                         // Channel B off of the heap, note that it has a much more
766                                                                         // restrictive htlc_maximum_msat, and recalculate the fees for
767                                                                         // all of node 1's channels using the new, reduced, amount.
768                                                                         //
769                                                                         // This would be bogus - we'd be selecting a higher-fee path
770                                                                         // with a lower htlc_maximum_msat instead of the one we'd
771                                                                         // already decided to use.
772                                                                         debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
773                                                                         debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
774                                                                 }
775                                                         }
776                                                 }
777                                         }
778                                 }
779                         }
780                         did_add_update_path_to_src_node
781                 } }
782         }
783
784         let empty_node_features = NodeFeatures::empty();
785         // Find ways (channels with destination) to reach a given node and store them
786         // in the corresponding data structures (routing graph etc).
787         // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
788         // meaning how much will be paid in fees after this node (to the best of our knowledge).
789         // This data can later be helpful to optimize routing (pay lower fees).
790         macro_rules! add_entries_to_cheapest_to_target_node {
791                 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
792                         let skip_node = if let Some(elem) = dist.get_mut($node_id) {
793                                 let was_processed = elem.was_processed;
794                                 elem.was_processed = true;
795                                 was_processed
796                         } else {
797                                 // Entries are added to dist in add_entry!() when there is a channel from a node.
798                                 // Because there are no channels from payee, it will not have a dist entry at this point.
799                                 // If we're processing any other node, it is always be the result of a channel from it.
800                                 assert_eq!($node_id, payee);
801                                 false
802                         };
803
804                         if !skip_node {
805                                 if first_hops.is_some() {
806                                         if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
807                                                 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
808                                         }
809                                 }
810
811                                 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
812                                         &node_info.features
813                                 } else {
814                                         &empty_node_features
815                                 };
816
817                                 if !features.requires_unknown_bits() {
818                                         for chan_id in $node.channels.iter() {
819                                                 let chan = network_channels.get(chan_id).unwrap();
820                                                 if !chan.features.requires_unknown_bits() {
821                                                         if chan.node_one == *$node_id {
822                                                                 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
823                                                                 if first_hops.is_none() || chan.node_two != *our_node_id {
824                                                                         if let Some(two_to_one) = chan.two_to_one.as_ref() {
825                                                                                 if two_to_one.enabled {
826                                                                                         add_entry!(chan_id, chan.node_two, chan.node_one, two_to_one, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
827                                                                                 }
828                                                                         }
829                                                                 }
830                                                         } else {
831                                                                 if first_hops.is_none() || chan.node_one != *our_node_id {
832                                                                         if let Some(one_to_two) = chan.one_to_two.as_ref() {
833                                                                                 if one_to_two.enabled {
834                                                                                         add_entry!(chan_id, chan.node_one, chan.node_two, one_to_two, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat);
835                                                                                 }
836                                                                         }
837                                                                 }
838                                                         }
839                                                 }
840                                         }
841                                 }
842                         }
843                 };
844         }
845
846         let mut payment_paths = Vec::<PaymentPath>::new();
847
848         // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
849         'paths_collection: loop {
850                 // For every new path, start from scratch, except
851                 // bookkeeped_channels_liquidity_available_msat, which will improve
852                 // the further iterations of path finding. Also don't erase first_hop_targets.
853                 targets.clear();
854                 dist.clear();
855                 hit_minimum_limit = false;
856
857                 // If first hop is a private channel and the only way to reach the payee, this is the only
858                 // place where it could be added.
859                 if first_hops.is_some() {
860                         if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
861                                 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
862                         }
863                 }
864
865                 // Add the payee as a target, so that the payee-to-payer
866                 // search algorithm knows what to start with.
867                 match network_nodes.get(payee) {
868                         // The payee is not in our network graph, so nothing to add here.
869                         // There is still a chance of reaching them via last_hops though,
870                         // so don't yet fail the payment here.
871                         // If not, targets.pop() will not even let us enter the loop in step 2.
872                         None => {},
873                         Some(node) => {
874                                 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
875                         },
876                 }
877
878                 // Step (1).
879                 // If a caller provided us with last hops, add them to routing targets. Since this happens
880                 // earlier than general path finding, they will be somewhat prioritized, although currently
881                 // it matters only if the fees are exactly the same.
882                 for route in last_hops.iter().filter(|route| !route.0.is_empty()) {
883                         let first_hop_in_route = &(route.0)[0];
884                         let have_hop_src_in_graph =
885                                 // Only add the hops in this route to our candidate set if either
886                                 // we have a direct channel to the first hop or the first hop is
887                                 // in the regular network graph.
888                                 first_hop_targets.get(&first_hop_in_route.src_node_id).is_some() ||
889                                 network_nodes.get(&first_hop_in_route.src_node_id).is_some();
890                         if have_hop_src_in_graph {
891                                 // We start building the path from reverse, i.e., from payee
892                                 // to the first RouteHintHop in the path.
893                                 let hop_iter = route.0.iter().rev();
894                                 let prev_hop_iter = core::iter::once(payee).chain(
895                                         route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
896                                 let mut hop_used = true;
897                                 let mut aggregate_next_hops_fee_msat: u64 = 0;
898                                 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
899
900                                 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
901                                         // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
902                                         // really sucks, cause we're gonna need that eventually.
903                                         let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
904
905                                         let directional_info = DummyDirectionalChannelInfo {
906                                                 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
907                                                 htlc_minimum_msat: hop_htlc_minimum_msat,
908                                                 htlc_maximum_msat: hop.htlc_maximum_msat,
909                                                 fees: hop.fees,
910                                         };
911
912                                         let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
913                                                 0 => 999,
914                                                 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
915                                         }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
916
917
918                                         // We assume that the recipient only included route hints for routes which had
919                                         // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
920                                         // invoices where the invoice does not specify value this may not be the case, but
921                                         // better to include the hints than not.
922                                         if !add_entry!(hop.short_channel_id, hop.src_node_id, prev_hop_id, directional_info, reqd_channel_cap, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat) {
923                                                 // If this hop was not used then there is no use checking the preceding hops
924                                                 // in the RouteHint. We can break by just searching for a direct channel between
925                                                 // last checked hop and first_hop_targets
926                                                 hop_used = false;
927                                         }
928
929                                         // Searching for a direct channel between last checked hop and first_hop_targets
930                                         if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&prev_hop_id) {
931                                                 add_entry!(first_hop, *our_node_id , prev_hop_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat);
932                                         }
933
934                                         if !hop_used {
935                                                 break;
936                                         }
937
938                                         // In the next values of the iterator, the aggregate fees already reflects
939                                         // the sum of value sent from payer (final_value_msat) and routing fees
940                                         // for the last node in the RouteHint. We need to just add the fees to
941                                         // route through the current node so that the preceeding node (next iteration)
942                                         // can use it.
943                                         let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
944                                                 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
945                                         aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
946
947                                         let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
948                                         let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
949                                                 .checked_add(hop_htlc_minimum_msat_inc);
950                                         aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
951
952                                         if idx == route.0.len() - 1 {
953                                                 // The last hop in this iterator is the first hop in
954                                                 // overall RouteHint.
955                                                 // If this hop connects to a node with which we have a direct channel,
956                                                 // ignore the network graph and, if the last hop was added, add our
957                                                 // direct channel to the candidate set.
958                                                 //
959                                                 // Note that we *must* check if the last hop was added as `add_entry`
960                                                 // always assumes that the third argument is a node to which we have a
961                                                 // path.
962                                                 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
963                                                         add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat);
964                                                 }
965                                         }
966                                 }
967                         }
968                 }
969
970                 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
971
972                 // At this point, targets are filled with the data from first and
973                 // last hops communicated by the caller, and the payment receiver.
974                 let mut found_new_path = false;
975
976                 // Step (2).
977                 // If this loop terminates due the exhaustion of targets, two situations are possible:
978                 // - not enough outgoing liquidity:
979                 //   0 < already_collected_value_msat < final_value_msat
980                 // - enough outgoing liquidity:
981                 //   final_value_msat <= already_collected_value_msat < recommended_value_msat
982                 // Both these cases (and other cases except reaching recommended_value_msat) mean that
983                 // paths_collection will be stopped because found_new_path==false.
984                 // This is not necessarily a routing failure.
985                 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
986
987                         // Since we're going payee-to-payer, hitting our node as a target means we should stop
988                         // traversing the graph and arrange the path out of what we found.
989                         if pubkey == *our_node_id {
990                                 let mut new_entry = dist.remove(&our_node_id).unwrap();
991                                 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
992
993                                 'path_walk: loop {
994                                         if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
995                                                 ordered_hops.last_mut().unwrap().1 = features.clone();
996                                         } else if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.pubkey) {
997                                                 if let Some(node_info) = node.announcement_info.as_ref() {
998                                                         ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
999                                                 } else {
1000                                                         ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1001                                                 }
1002                                         } else {
1003                                                 // We should be able to fill in features for everything except the last
1004                                                 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1005                                                 // should be able to extend it further as BOLT 11 does have feature
1006                                                 // flags for the last hop node itself).
1007                                                 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
1008                                         }
1009
1010                                         // Means we succesfully traversed from the payer to the payee, now
1011                                         // save this path for the payment route. Also, update the liquidity
1012                                         // remaining on the used hops, so that we take them into account
1013                                         // while looking for more paths.
1014                                         if ordered_hops.last().unwrap().0.pubkey == *payee {
1015                                                 break 'path_walk;
1016                                         }
1017
1018                                         new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
1019                                                 Some(payment_hop) => payment_hop,
1020                                                 // We can't arrive at None because, if we ever add an entry to targets,
1021                                                 // we also fill in the entry in dist (see add_entry!).
1022                                                 None => unreachable!(),
1023                                         };
1024                                         // We "propagate" the fees one hop backward (topologically) here,
1025                                         // so that fees paid for a HTLC forwarding on the current channel are
1026                                         // associated with the previous channel (where they will be subtracted).
1027                                         ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1028                                         ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1029                                         ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1030                                 }
1031                                 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1032                                 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1033                                 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
1034
1035                                 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1036                                         ordered_hops.len(), value_contribution_msat, ordered_hops);
1037
1038                                 let mut payment_path = PaymentPath {hops: ordered_hops};
1039
1040                                 // We could have possibly constructed a slightly inconsistent path: since we reduce
1041                                 // value being transferred along the way, we could have violated htlc_minimum_msat
1042                                 // on some channels we already passed (assuming dest->source direction). Here, we
1043                                 // recompute the fees again, so that if that's the case, we match the currently
1044                                 // underpaid htlc_minimum_msat with fees.
1045                                 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1046
1047                                 // Since a path allows to transfer as much value as
1048                                 // the smallest channel it has ("bottleneck"), we should recompute
1049                                 // the fees so sender HTLC don't overpay fees when traversing
1050                                 // larger channels than the bottleneck. This may happen because
1051                                 // when we were selecting those channels we were not aware how much value
1052                                 // this path will transfer, and the relative fee for them
1053                                 // might have been computed considering a larger value.
1054                                 // Remember that we used these channels so that we don't rely
1055                                 // on the same liquidity in future paths.
1056                                 let mut prevented_redundant_path_selection = false;
1057                                 for (payment_hop, _) in payment_path.hops.iter() {
1058                                         let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1059                                         let mut spent_on_hop_msat = value_contribution_msat;
1060                                         let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1061                                         spent_on_hop_msat += next_hops_fee_msat;
1062                                         if spent_on_hop_msat == *channel_liquidity_available_msat {
1063                                                 // If this path used all of this channel's available liquidity, we know
1064                                                 // this path will not be selected again in the next loop iteration.
1065                                                 prevented_redundant_path_selection = true;
1066                                         }
1067                                         *channel_liquidity_available_msat -= spent_on_hop_msat;
1068                                 }
1069                                 if !prevented_redundant_path_selection {
1070                                         // If we weren't capped by hitting a liquidity limit on a channel in the path,
1071                                         // we'll probably end up picking the same path again on the next iteration.
1072                                         // Decrease the available liquidity of a hop in the middle of the path.
1073                                         let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1074                                         log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1075                                         let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1076                                         *victim_liquidity = 0;
1077                                 }
1078
1079                                 // Track the total amount all our collected paths allow to send so that we:
1080                                 // - know when to stop looking for more paths
1081                                 // - know which of the hops are useless considering how much more sats we need
1082                                 //   (contributes_sufficient_value)
1083                                 already_collected_value_msat += value_contribution_msat;
1084
1085                                 payment_paths.push(payment_path);
1086                                 found_new_path = true;
1087                                 break 'path_construction;
1088                         }
1089
1090                         // If we found a path back to the payee, we shouldn't try to process it again. This is
1091                         // the equivalent of the `elem.was_processed` check in
1092                         // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1093                         if pubkey == *payee { continue 'path_construction; }
1094
1095                         // Otherwise, since the current target node is not us,
1096                         // keep "unrolling" the payment graph from payee to payer by
1097                         // finding a way to reach the current target from the payer side.
1098                         match network_nodes.get(&pubkey) {
1099                                 None => {},
1100                                 Some(node) => {
1101                                         add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1102                                 },
1103                         }
1104                 }
1105
1106                 if !allow_mpp {
1107                         // If we don't support MPP, no use trying to gather more value ever.
1108                         break 'paths_collection;
1109                 }
1110
1111                 // Step (3).
1112                 // Stop either when the recommended value is reached or if no new path was found in this
1113                 // iteration.
1114                 // In the latter case, making another path finding attempt won't help,
1115                 // because we deterministically terminated the search due to low liquidity.
1116                 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1117                         log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1118                                 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1119                         break 'paths_collection;
1120                 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1121                         // Further, if this was our first walk of the graph, and we weren't limited by an
1122                         // htlc_minimum_msat, return immediately because this path should suffice. If we were
1123                         // limited by an htlc_minimum_msat value, find another path with a higher value,
1124                         // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1125                         // still keeping a lower total fee than this path.
1126                         if !hit_minimum_limit {
1127                                 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1128                                 break 'paths_collection;
1129                         }
1130                         log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1131                         path_value_msat = recommended_value_msat;
1132                 }
1133         }
1134
1135         // Step (4).
1136         if payment_paths.len() == 0 {
1137                 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1138         }
1139
1140         if already_collected_value_msat < final_value_msat {
1141                 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1142         }
1143
1144         // Sort by total fees and take the best paths.
1145         payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1146         if payment_paths.len() > 50 {
1147                 payment_paths.truncate(50);
1148         }
1149
1150         // Draw multiple sufficient routes by randomly combining the selected paths.
1151         let mut drawn_routes = Vec::new();
1152         for i in 0..payment_paths.len() {
1153                 let mut cur_route = Vec::<PaymentPath>::new();
1154                 let mut aggregate_route_value_msat = 0;
1155
1156                 // Step (5).
1157                 // TODO: real random shuffle
1158                 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1159                 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1160
1161                 // Step (6).
1162                 for payment_path in cur_payment_paths {
1163                         cur_route.push(payment_path.clone());
1164                         aggregate_route_value_msat += payment_path.get_value_msat();
1165                         if aggregate_route_value_msat > final_value_msat {
1166                                 // Last path likely overpaid. Substract it from the most expensive
1167                                 // (in terms of proportional fee) path in this route and recompute fees.
1168                                 // This might be not the most economically efficient way, but fewer paths
1169                                 // also makes routing more reliable.
1170                                 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1171
1172                                 // First, drop some expensive low-value paths entirely if possible.
1173                                 // Sort by value so that we drop many really-low values first, since
1174                                 // fewer paths is better: the payment is less likely to fail.
1175                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1176                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1177                                 cur_route.sort_by_key(|path| path.get_value_msat());
1178                                 // We should make sure that at least 1 path left.
1179                                 let mut paths_left = cur_route.len();
1180                                 cur_route.retain(|path| {
1181                                         if paths_left == 1 {
1182                                                 return true
1183                                         }
1184                                         let mut keep = true;
1185                                         let path_value_msat = path.get_value_msat();
1186                                         if path_value_msat <= overpaid_value_msat {
1187                                                 keep = false;
1188                                                 overpaid_value_msat -= path_value_msat;
1189                                                 paths_left -= 1;
1190                                         }
1191                                         keep
1192                                 });
1193
1194                                 if overpaid_value_msat == 0 {
1195                                         break;
1196                                 }
1197
1198                                 assert!(cur_route.len() > 0);
1199
1200                                 // Step (7).
1201                                 // Now, substract the overpaid value from the most-expensive path.
1202                                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1203                                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1204                                 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1205                                 let expensive_payment_path = cur_route.first_mut().unwrap();
1206                                 // We already dropped all the small channels above, meaning all the
1207                                 // remaining channels are larger than remaining overpaid_value_msat.
1208                                 // Thus, this can't be negative.
1209                                 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1210                                 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1211                                 break;
1212                         }
1213                 }
1214                 drawn_routes.push(cur_route);
1215         }
1216
1217         // Step (8).
1218         // Select the best route by lowest total fee.
1219         drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1220         let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1221         for payment_path in drawn_routes.first().unwrap() {
1222                 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1223                         RouteHop {
1224                                 pubkey: payment_hop.pubkey,
1225                                 node_features: node_features.clone(),
1226                                 short_channel_id: payment_hop.short_channel_id,
1227                                 channel_features: payment_hop.channel_features.clone(),
1228                                 fee_msat: payment_hop.fee_msat,
1229                                 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1230                         }
1231                 }).collect());
1232         }
1233
1234         if let Some(features) = &payee_features {
1235                 for path in selected_paths.iter_mut() {
1236                         path.last_mut().unwrap().node_features = features.to_context();
1237                 }
1238         }
1239
1240         let route = Route { paths: selected_paths };
1241         log_info!(logger, "Got route to {}: {}", payee, log_route!(route));
1242         Ok(route)
1243 }
1244
1245 #[cfg(test)]
1246 mod tests {
1247         use routing::router::{get_route, Route, RouteHint, RouteHintHop, RoutingFees};
1248         use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1249         use chain::transaction::OutPoint;
1250         use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1251         use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1252            NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1253         use ln::channelmanager;
1254         use util::test_utils;
1255         use util::ser::Writeable;
1256
1257         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1258         use bitcoin::hashes::Hash;
1259         use bitcoin::network::constants::Network;
1260         use bitcoin::blockdata::constants::genesis_block;
1261         use bitcoin::blockdata::script::Builder;
1262         use bitcoin::blockdata::opcodes;
1263         use bitcoin::blockdata::transaction::TxOut;
1264
1265         use hex;
1266
1267         use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1268         use bitcoin::secp256k1::{Secp256k1, All};
1269
1270         use prelude::*;
1271         use sync::{self, Arc};
1272
1273         fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1274                         features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1275                 channelmanager::ChannelDetails {
1276                         channel_id: [0; 32],
1277                         counterparty: channelmanager::ChannelCounterparty {
1278                                 features,
1279                                 node_id,
1280                                 unspendable_punishment_reserve: 0,
1281                                 forwarding_info: None,
1282                         },
1283                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1284                         short_channel_id,
1285                         channel_value_satoshis: 0,
1286                         user_id: 0,
1287                         outbound_capacity_msat,
1288                         inbound_capacity_msat: 42,
1289                         unspendable_punishment_reserve: None,
1290                         confirmations_required: None,
1291                         force_close_spend_delay: None,
1292                         is_outbound: true, is_funding_locked: true,
1293                         is_usable: true, is_public: true,
1294                 }
1295         }
1296
1297         // Using the same keys for LN and BTC ids
1298         fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1299            node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1300                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1301                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1302
1303                 let unsigned_announcement = UnsignedChannelAnnouncement {
1304                         features,
1305                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1306                         short_channel_id,
1307                         node_id_1,
1308                         node_id_2,
1309                         bitcoin_key_1: node_id_1,
1310                         bitcoin_key_2: node_id_2,
1311                         excess_data: Vec::new(),
1312                 };
1313
1314                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1315                 let valid_announcement = ChannelAnnouncement {
1316                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1317                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1318                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1319                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1320                         contents: unsigned_announcement.clone(),
1321                 };
1322                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1323                         Ok(res) => assert!(res),
1324                         _ => panic!()
1325                 };
1326         }
1327
1328         fn update_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate) {
1329                 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1330                 let valid_channel_update = ChannelUpdate {
1331                         signature: secp_ctx.sign(&msghash, node_privkey),
1332                         contents: update.clone()
1333                 };
1334
1335                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1336                         Ok(res) => assert!(res),
1337                         Err(_) => panic!()
1338                 };
1339         }
1340
1341         fn add_or_update_node(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey,
1342            features: NodeFeatures, timestamp: u32) {
1343                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1344                 let unsigned_announcement = UnsignedNodeAnnouncement {
1345                         features,
1346                         timestamp,
1347                         node_id,
1348                         rgb: [0; 3],
1349                         alias: [0; 32],
1350                         addresses: Vec::new(),
1351                         excess_address_data: Vec::new(),
1352                         excess_data: Vec::new(),
1353                 };
1354                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1355                 let valid_announcement = NodeAnnouncement {
1356                         signature: secp_ctx.sign(&msghash, node_privkey),
1357                         contents: unsigned_announcement.clone()
1358                 };
1359
1360                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1361                         Ok(_) => (),
1362                         Err(_) => panic!()
1363                 };
1364         }
1365
1366         fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1367                 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1368                         SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1369                 }).collect();
1370
1371                 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1372
1373                 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1374                 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1375
1376                 (our_privkey, our_id, privkeys, pubkeys)
1377         }
1378
1379         fn id_to_feature_flags(id: u8) -> Vec<u8> {
1380                 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1381                 // test for it later.
1382                 let idx = (id - 1) * 2 + 1;
1383                 if idx > 8*3 {
1384                         vec![1 << (idx - 8*3), 0, 0, 0]
1385                 } else if idx > 8*2 {
1386                         vec![1 << (idx - 8*2), 0, 0]
1387                 } else if idx > 8*1 {
1388                         vec![1 << (idx - 8*1), 0]
1389                 } else {
1390                         vec![1 << idx]
1391                 }
1392         }
1393
1394         fn build_graph() -> (Secp256k1<All>, NetGraphMsgHandler<sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>, sync::Arc<test_utils::TestChainSource>, sync::Arc<test_utils::TestLogger>) {
1395                 let secp_ctx = Secp256k1::new();
1396                 let logger = Arc::new(test_utils::TestLogger::new());
1397                 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1398                 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1399                 // Build network from our_id to node6:
1400                 //
1401                 //        -1(1)2-  node0  -1(3)2-
1402                 //       /                       \
1403                 // our_id -1(12)2- node7 -1(13)2--- node2
1404                 //       \                       /
1405                 //        -1(2)2-  node1  -1(4)2-
1406                 //
1407                 //
1408                 // chan1  1-to-2: disabled
1409                 // chan1  2-to-1: enabled, 0 fee
1410                 //
1411                 // chan2  1-to-2: enabled, ignored fee
1412                 // chan2  2-to-1: enabled, 0 fee
1413                 //
1414                 // chan3  1-to-2: enabled, 0 fee
1415                 // chan3  2-to-1: enabled, 100 msat fee
1416                 //
1417                 // chan4  1-to-2: enabled, 100% fee
1418                 // chan4  2-to-1: enabled, 0 fee
1419                 //
1420                 // chan12 1-to-2: enabled, ignored fee
1421                 // chan12 2-to-1: enabled, 0 fee
1422                 //
1423                 // chan13 1-to-2: enabled, 200% fee
1424                 // chan13 2-to-1: enabled, 0 fee
1425                 //
1426                 //
1427                 //       -1(5)2- node3 -1(8)2--
1428                 //       |         2          |
1429                 //       |       (11)         |
1430                 //      /          1           \
1431                 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1432                 //      \                      /
1433                 //       -1(7)2- node5 -1(10)2-
1434                 //
1435                 // Channels 5, 8, 9 and 10 are private channels.
1436                 //
1437                 // chan5  1-to-2: enabled, 100 msat fee
1438                 // chan5  2-to-1: enabled, 0 fee
1439                 //
1440                 // chan6  1-to-2: enabled, 0 fee
1441                 // chan6  2-to-1: enabled, 0 fee
1442                 //
1443                 // chan7  1-to-2: enabled, 100% fee
1444                 // chan7  2-to-1: enabled, 0 fee
1445                 //
1446                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
1447                 // chan8  2-to-1: enabled, 0 fee
1448                 //
1449                 // chan9  1-to-2: enabled, 1001 msat fee
1450                 // chan9  2-to-1: enabled, 0 fee
1451                 //
1452                 // chan10 1-to-2: enabled, 0 fee
1453                 // chan10 2-to-1: enabled, 0 fee
1454                 //
1455                 // chan11 1-to-2: enabled, 0 fee
1456                 // chan11 2-to-1: enabled, 0 fee
1457
1458                 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1459
1460                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1461                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1462                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1463                         short_channel_id: 1,
1464                         timestamp: 1,
1465                         flags: 1,
1466                         cltv_expiry_delta: 0,
1467                         htlc_minimum_msat: 0,
1468                         htlc_maximum_msat: OptionalField::Absent,
1469                         fee_base_msat: 0,
1470                         fee_proportional_millionths: 0,
1471                         excess_data: Vec::new()
1472                 });
1473
1474                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1475
1476                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1477                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1478                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1479                         short_channel_id: 2,
1480                         timestamp: 1,
1481                         flags: 0,
1482                         cltv_expiry_delta: u16::max_value(),
1483                         htlc_minimum_msat: 0,
1484                         htlc_maximum_msat: OptionalField::Absent,
1485                         fee_base_msat: u32::max_value(),
1486                         fee_proportional_millionths: u32::max_value(),
1487                         excess_data: Vec::new()
1488                 });
1489                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1490                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1491                         short_channel_id: 2,
1492                         timestamp: 1,
1493                         flags: 1,
1494                         cltv_expiry_delta: 0,
1495                         htlc_minimum_msat: 0,
1496                         htlc_maximum_msat: OptionalField::Absent,
1497                         fee_base_msat: 0,
1498                         fee_proportional_millionths: 0,
1499                         excess_data: Vec::new()
1500                 });
1501
1502                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1503
1504                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1505                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1506                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1507                         short_channel_id: 12,
1508                         timestamp: 1,
1509                         flags: 0,
1510                         cltv_expiry_delta: u16::max_value(),
1511                         htlc_minimum_msat: 0,
1512                         htlc_maximum_msat: OptionalField::Absent,
1513                         fee_base_msat: u32::max_value(),
1514                         fee_proportional_millionths: u32::max_value(),
1515                         excess_data: Vec::new()
1516                 });
1517                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1518                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1519                         short_channel_id: 12,
1520                         timestamp: 1,
1521                         flags: 1,
1522                         cltv_expiry_delta: 0,
1523                         htlc_minimum_msat: 0,
1524                         htlc_maximum_msat: OptionalField::Absent,
1525                         fee_base_msat: 0,
1526                         fee_proportional_millionths: 0,
1527                         excess_data: Vec::new()
1528                 });
1529
1530                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1531
1532                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1533                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1534                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1535                         short_channel_id: 3,
1536                         timestamp: 1,
1537                         flags: 0,
1538                         cltv_expiry_delta: (3 << 8) | 1,
1539                         htlc_minimum_msat: 0,
1540                         htlc_maximum_msat: OptionalField::Absent,
1541                         fee_base_msat: 0,
1542                         fee_proportional_millionths: 0,
1543                         excess_data: Vec::new()
1544                 });
1545                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1546                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1547                         short_channel_id: 3,
1548                         timestamp: 1,
1549                         flags: 1,
1550                         cltv_expiry_delta: (3 << 8) | 2,
1551                         htlc_minimum_msat: 0,
1552                         htlc_maximum_msat: OptionalField::Absent,
1553                         fee_base_msat: 100,
1554                         fee_proportional_millionths: 0,
1555                         excess_data: Vec::new()
1556                 });
1557
1558                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1559                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1560                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1561                         short_channel_id: 4,
1562                         timestamp: 1,
1563                         flags: 0,
1564                         cltv_expiry_delta: (4 << 8) | 1,
1565                         htlc_minimum_msat: 0,
1566                         htlc_maximum_msat: OptionalField::Absent,
1567                         fee_base_msat: 0,
1568                         fee_proportional_millionths: 1000000,
1569                         excess_data: Vec::new()
1570                 });
1571                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1572                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1573                         short_channel_id: 4,
1574                         timestamp: 1,
1575                         flags: 1,
1576                         cltv_expiry_delta: (4 << 8) | 2,
1577                         htlc_minimum_msat: 0,
1578                         htlc_maximum_msat: OptionalField::Absent,
1579                         fee_base_msat: 0,
1580                         fee_proportional_millionths: 0,
1581                         excess_data: Vec::new()
1582                 });
1583
1584                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1585                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1586                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1587                         short_channel_id: 13,
1588                         timestamp: 1,
1589                         flags: 0,
1590                         cltv_expiry_delta: (13 << 8) | 1,
1591                         htlc_minimum_msat: 0,
1592                         htlc_maximum_msat: OptionalField::Absent,
1593                         fee_base_msat: 0,
1594                         fee_proportional_millionths: 2000000,
1595                         excess_data: Vec::new()
1596                 });
1597                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1598                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1599                         short_channel_id: 13,
1600                         timestamp: 1,
1601                         flags: 1,
1602                         cltv_expiry_delta: (13 << 8) | 2,
1603                         htlc_minimum_msat: 0,
1604                         htlc_maximum_msat: OptionalField::Absent,
1605                         fee_base_msat: 0,
1606                         fee_proportional_millionths: 0,
1607                         excess_data: Vec::new()
1608                 });
1609
1610                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1611
1612                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1613                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1614                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1615                         short_channel_id: 6,
1616                         timestamp: 1,
1617                         flags: 0,
1618                         cltv_expiry_delta: (6 << 8) | 1,
1619                         htlc_minimum_msat: 0,
1620                         htlc_maximum_msat: OptionalField::Absent,
1621                         fee_base_msat: 0,
1622                         fee_proportional_millionths: 0,
1623                         excess_data: Vec::new()
1624                 });
1625                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1626                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1627                         short_channel_id: 6,
1628                         timestamp: 1,
1629                         flags: 1,
1630                         cltv_expiry_delta: (6 << 8) | 2,
1631                         htlc_minimum_msat: 0,
1632                         htlc_maximum_msat: OptionalField::Absent,
1633                         fee_base_msat: 0,
1634                         fee_proportional_millionths: 0,
1635                         excess_data: Vec::new(),
1636                 });
1637
1638                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1639                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1640                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1641                         short_channel_id: 11,
1642                         timestamp: 1,
1643                         flags: 0,
1644                         cltv_expiry_delta: (11 << 8) | 1,
1645                         htlc_minimum_msat: 0,
1646                         htlc_maximum_msat: OptionalField::Absent,
1647                         fee_base_msat: 0,
1648                         fee_proportional_millionths: 0,
1649                         excess_data: Vec::new()
1650                 });
1651                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1652                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1653                         short_channel_id: 11,
1654                         timestamp: 1,
1655                         flags: 1,
1656                         cltv_expiry_delta: (11 << 8) | 2,
1657                         htlc_minimum_msat: 0,
1658                         htlc_maximum_msat: OptionalField::Absent,
1659                         fee_base_msat: 0,
1660                         fee_proportional_millionths: 0,
1661                         excess_data: Vec::new()
1662                 });
1663
1664                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1665
1666                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1667
1668                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1669                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1670                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1671                         short_channel_id: 7,
1672                         timestamp: 1,
1673                         flags: 0,
1674                         cltv_expiry_delta: (7 << 8) | 1,
1675                         htlc_minimum_msat: 0,
1676                         htlc_maximum_msat: OptionalField::Absent,
1677                         fee_base_msat: 0,
1678                         fee_proportional_millionths: 1000000,
1679                         excess_data: Vec::new()
1680                 });
1681                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1682                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1683                         short_channel_id: 7,
1684                         timestamp: 1,
1685                         flags: 1,
1686                         cltv_expiry_delta: (7 << 8) | 2,
1687                         htlc_minimum_msat: 0,
1688                         htlc_maximum_msat: OptionalField::Absent,
1689                         fee_base_msat: 0,
1690                         fee_proportional_millionths: 0,
1691                         excess_data: Vec::new()
1692                 });
1693
1694                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1695
1696                 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1697         }
1698
1699         #[test]
1700         fn simple_route_test() {
1701                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1702                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1703
1704                 // Simple route to 2 via 1
1705
1706                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 0, 42, Arc::clone(&logger)) {
1707                         assert_eq!(err, "Cannot send a payment of 0 msat");
1708                 } else { panic!(); }
1709
1710                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1711                 assert_eq!(route.paths[0].len(), 2);
1712
1713                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1714                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1715                 assert_eq!(route.paths[0][0].fee_msat, 100);
1716                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1717                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1718                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1719
1720                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1721                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1722                 assert_eq!(route.paths[0][1].fee_msat, 100);
1723                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1724                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1725                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1726         }
1727
1728         #[test]
1729         fn invalid_first_hop_test() {
1730                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1731                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1732
1733                 // Simple route to 2 via 1
1734
1735                 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1736
1737                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)) {
1738                         assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1739                 } else { panic!(); }
1740
1741                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1742                 assert_eq!(route.paths[0].len(), 2);
1743         }
1744
1745         #[test]
1746         fn htlc_minimum_test() {
1747                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1748                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1749
1750                 // Simple route to 2 via 1
1751
1752                 // Disable other paths
1753                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1754                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1755                         short_channel_id: 12,
1756                         timestamp: 2,
1757                         flags: 2, // to disable
1758                         cltv_expiry_delta: 0,
1759                         htlc_minimum_msat: 0,
1760                         htlc_maximum_msat: OptionalField::Absent,
1761                         fee_base_msat: 0,
1762                         fee_proportional_millionths: 0,
1763                         excess_data: Vec::new()
1764                 });
1765                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1766                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1767                         short_channel_id: 3,
1768                         timestamp: 2,
1769                         flags: 2, // to disable
1770                         cltv_expiry_delta: 0,
1771                         htlc_minimum_msat: 0,
1772                         htlc_maximum_msat: OptionalField::Absent,
1773                         fee_base_msat: 0,
1774                         fee_proportional_millionths: 0,
1775                         excess_data: Vec::new()
1776                 });
1777                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1778                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1779                         short_channel_id: 13,
1780                         timestamp: 2,
1781                         flags: 2, // to disable
1782                         cltv_expiry_delta: 0,
1783                         htlc_minimum_msat: 0,
1784                         htlc_maximum_msat: OptionalField::Absent,
1785                         fee_base_msat: 0,
1786                         fee_proportional_millionths: 0,
1787                         excess_data: Vec::new()
1788                 });
1789                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1790                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1791                         short_channel_id: 6,
1792                         timestamp: 2,
1793                         flags: 2, // to disable
1794                         cltv_expiry_delta: 0,
1795                         htlc_minimum_msat: 0,
1796                         htlc_maximum_msat: OptionalField::Absent,
1797                         fee_base_msat: 0,
1798                         fee_proportional_millionths: 0,
1799                         excess_data: Vec::new()
1800                 });
1801                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1802                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1803                         short_channel_id: 7,
1804                         timestamp: 2,
1805                         flags: 2, // to disable
1806                         cltv_expiry_delta: 0,
1807                         htlc_minimum_msat: 0,
1808                         htlc_maximum_msat: OptionalField::Absent,
1809                         fee_base_msat: 0,
1810                         fee_proportional_millionths: 0,
1811                         excess_data: Vec::new()
1812                 });
1813
1814                 // Check against amount_to_transfer_over_msat.
1815                 // Set minimal HTLC of 200_000_000 msat.
1816                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1817                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1818                         short_channel_id: 2,
1819                         timestamp: 3,
1820                         flags: 0,
1821                         cltv_expiry_delta: 0,
1822                         htlc_minimum_msat: 200_000_000,
1823                         htlc_maximum_msat: OptionalField::Absent,
1824                         fee_base_msat: 0,
1825                         fee_proportional_millionths: 0,
1826                         excess_data: Vec::new()
1827                 });
1828
1829                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1830                 // be used.
1831                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1832                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1833                         short_channel_id: 4,
1834                         timestamp: 3,
1835                         flags: 0,
1836                         cltv_expiry_delta: 0,
1837                         htlc_minimum_msat: 0,
1838                         htlc_maximum_msat: OptionalField::Present(199_999_999),
1839                         fee_base_msat: 0,
1840                         fee_proportional_millionths: 0,
1841                         excess_data: Vec::new()
1842                 });
1843
1844                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1845                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)) {
1846                         assert_eq!(err, "Failed to find a path to the given destination");
1847                 } else { panic!(); }
1848
1849                 // Lift the restriction on the first hop.
1850                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1851                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1852                         short_channel_id: 2,
1853                         timestamp: 4,
1854                         flags: 0,
1855                         cltv_expiry_delta: 0,
1856                         htlc_minimum_msat: 0,
1857                         htlc_maximum_msat: OptionalField::Absent,
1858                         fee_base_msat: 0,
1859                         fee_proportional_millionths: 0,
1860                         excess_data: Vec::new()
1861                 });
1862
1863                 // A payment above the minimum should pass
1864                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)).unwrap();
1865                 assert_eq!(route.paths[0].len(), 2);
1866         }
1867
1868         #[test]
1869         fn htlc_minimum_overpay_test() {
1870                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1871                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1872
1873                 // A route to node#2 via two paths.
1874                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1875                 // Thus, they can't send 60 without overpaying.
1876                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1877                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1878                         short_channel_id: 2,
1879                         timestamp: 2,
1880                         flags: 0,
1881                         cltv_expiry_delta: 0,
1882                         htlc_minimum_msat: 35_000,
1883                         htlc_maximum_msat: OptionalField::Present(40_000),
1884                         fee_base_msat: 0,
1885                         fee_proportional_millionths: 0,
1886                         excess_data: Vec::new()
1887                 });
1888                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1889                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1890                         short_channel_id: 12,
1891                         timestamp: 3,
1892                         flags: 0,
1893                         cltv_expiry_delta: 0,
1894                         htlc_minimum_msat: 35_000,
1895                         htlc_maximum_msat: OptionalField::Present(40_000),
1896                         fee_base_msat: 0,
1897                         fee_proportional_millionths: 0,
1898                         excess_data: Vec::new()
1899                 });
1900
1901                 // Make 0 fee.
1902                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1903                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1904                         short_channel_id: 13,
1905                         timestamp: 2,
1906                         flags: 0,
1907                         cltv_expiry_delta: 0,
1908                         htlc_minimum_msat: 0,
1909                         htlc_maximum_msat: OptionalField::Absent,
1910                         fee_base_msat: 0,
1911                         fee_proportional_millionths: 0,
1912                         excess_data: Vec::new()
1913                 });
1914                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1915                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1916                         short_channel_id: 4,
1917                         timestamp: 2,
1918                         flags: 0,
1919                         cltv_expiry_delta: 0,
1920                         htlc_minimum_msat: 0,
1921                         htlc_maximum_msat: OptionalField::Absent,
1922                         fee_base_msat: 0,
1923                         fee_proportional_millionths: 0,
1924                         excess_data: Vec::new()
1925                 });
1926
1927                 // Disable other paths
1928                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1929                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1930                         short_channel_id: 1,
1931                         timestamp: 3,
1932                         flags: 2, // to disable
1933                         cltv_expiry_delta: 0,
1934                         htlc_minimum_msat: 0,
1935                         htlc_maximum_msat: OptionalField::Absent,
1936                         fee_base_msat: 0,
1937                         fee_proportional_millionths: 0,
1938                         excess_data: Vec::new()
1939                 });
1940
1941                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1942                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1943                 // Overpay fees to hit htlc_minimum_msat.
1944                 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1945                 // TODO: this could be better balanced to overpay 10k and not 15k.
1946                 assert_eq!(overpaid_fees, 15_000);
1947
1948                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1949                 // while taking even more fee to match htlc_minimum_msat.
1950                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1951                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1952                         short_channel_id: 12,
1953                         timestamp: 4,
1954                         flags: 0,
1955                         cltv_expiry_delta: 0,
1956                         htlc_minimum_msat: 65_000,
1957                         htlc_maximum_msat: OptionalField::Present(80_000),
1958                         fee_base_msat: 0,
1959                         fee_proportional_millionths: 0,
1960                         excess_data: Vec::new()
1961                 });
1962                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1963                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1964                         short_channel_id: 2,
1965                         timestamp: 3,
1966                         flags: 0,
1967                         cltv_expiry_delta: 0,
1968                         htlc_minimum_msat: 0,
1969                         htlc_maximum_msat: OptionalField::Absent,
1970                         fee_base_msat: 0,
1971                         fee_proportional_millionths: 0,
1972                         excess_data: Vec::new()
1973                 });
1974                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1975                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1976                         short_channel_id: 4,
1977                         timestamp: 4,
1978                         flags: 0,
1979                         cltv_expiry_delta: 0,
1980                         htlc_minimum_msat: 0,
1981                         htlc_maximum_msat: OptionalField::Absent,
1982                         fee_base_msat: 0,
1983                         fee_proportional_millionths: 100_000,
1984                         excess_data: Vec::new()
1985                 });
1986
1987                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1988                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1989                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1990                 assert_eq!(route.paths.len(), 1);
1991                 assert_eq!(route.paths[0][0].short_channel_id, 12);
1992                 let fees = route.paths[0][0].fee_msat;
1993                 assert_eq!(fees, 5_000);
1994
1995                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1996                         Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1997                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1998                 // the other channel.
1999                 assert_eq!(route.paths.len(), 1);
2000                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2001                 let fees = route.paths[0][0].fee_msat;
2002                 assert_eq!(fees, 5_000);
2003         }
2004
2005         #[test]
2006         fn disable_channels_test() {
2007                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2008                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2009
2010                 // // Disable channels 4 and 12 by flags=2
2011                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2012                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2013                         short_channel_id: 4,
2014                         timestamp: 2,
2015                         flags: 2, // to disable
2016                         cltv_expiry_delta: 0,
2017                         htlc_minimum_msat: 0,
2018                         htlc_maximum_msat: OptionalField::Absent,
2019                         fee_base_msat: 0,
2020                         fee_proportional_millionths: 0,
2021                         excess_data: Vec::new()
2022                 });
2023                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2024                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2025                         short_channel_id: 12,
2026                         timestamp: 2,
2027                         flags: 2, // to disable
2028                         cltv_expiry_delta: 0,
2029                         htlc_minimum_msat: 0,
2030                         htlc_maximum_msat: OptionalField::Absent,
2031                         fee_base_msat: 0,
2032                         fee_proportional_millionths: 0,
2033                         excess_data: Vec::new()
2034                 });
2035
2036                 // If all the channels require some features we don't understand, route should fail
2037                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
2038                         assert_eq!(err, "Failed to find a path to the given destination");
2039                 } else { panic!(); }
2040
2041                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2042                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2043                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()),  &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2044                 assert_eq!(route.paths[0].len(), 2);
2045
2046                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2047                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2048                 assert_eq!(route.paths[0][0].fee_msat, 200);
2049                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2050                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2051                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2052
2053                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2054                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2055                 assert_eq!(route.paths[0][1].fee_msat, 100);
2056                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2057                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2058                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2059         }
2060
2061         #[test]
2062         fn disable_node_test() {
2063                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2064                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2065
2066                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2067                 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2068                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2069                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2070                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2071
2072                 // If all nodes require some features we don't understand, route should fail
2073                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
2074                         assert_eq!(err, "Failed to find a path to the given destination");
2075                 } else { panic!(); }
2076
2077                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2078                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2079                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2080                 assert_eq!(route.paths[0].len(), 2);
2081
2082                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2083                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2084                 assert_eq!(route.paths[0][0].fee_msat, 200);
2085                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2086                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2087                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2088
2089                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2090                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2091                 assert_eq!(route.paths[0][1].fee_msat, 100);
2092                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2093                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2094                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2095
2096                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2097                 // naively) assume that the user checked the feature bits on the invoice, which override
2098                 // the node_announcement.
2099         }
2100
2101         #[test]
2102         fn our_chans_test() {
2103                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2104                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2105
2106                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2107                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0], None, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2108                 assert_eq!(route.paths[0].len(), 3);
2109
2110                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2111                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2112                 assert_eq!(route.paths[0][0].fee_msat, 200);
2113                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2114                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2115                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2116
2117                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2118                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2119                 assert_eq!(route.paths[0][1].fee_msat, 100);
2120                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2121                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2122                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2123
2124                 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2125                 assert_eq!(route.paths[0][2].short_channel_id, 3);
2126                 assert_eq!(route.paths[0][2].fee_msat, 100);
2127                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2128                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2129                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2130
2131                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2132                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2133                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2134                 assert_eq!(route.paths[0].len(), 2);
2135
2136                 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2137                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2138                 assert_eq!(route.paths[0][0].fee_msat, 200);
2139                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2140                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2141                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2142
2143                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2144                 assert_eq!(route.paths[0][1].short_channel_id, 13);
2145                 assert_eq!(route.paths[0][1].fee_msat, 100);
2146                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2147                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2148                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2149         }
2150
2151         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2152                 let zero_fees = RoutingFees {
2153                         base_msat: 0,
2154                         proportional_millionths: 0,
2155                 };
2156                 vec![RouteHint(vec![RouteHintHop {
2157                         src_node_id: nodes[3].clone(),
2158                         short_channel_id: 8,
2159                         fees: zero_fees,
2160                         cltv_expiry_delta: (8 << 8) | 1,
2161                         htlc_minimum_msat: None,
2162                         htlc_maximum_msat: None,
2163                 }
2164                 ]), RouteHint(vec![RouteHintHop {
2165                         src_node_id: nodes[4].clone(),
2166                         short_channel_id: 9,
2167                         fees: RoutingFees {
2168                                 base_msat: 1001,
2169                                 proportional_millionths: 0,
2170                         },
2171                         cltv_expiry_delta: (9 << 8) | 1,
2172                         htlc_minimum_msat: None,
2173                         htlc_maximum_msat: None,
2174                 }]), RouteHint(vec![RouteHintHop {
2175                         src_node_id: nodes[5].clone(),
2176                         short_channel_id: 10,
2177                         fees: zero_fees,
2178                         cltv_expiry_delta: (10 << 8) | 1,
2179                         htlc_minimum_msat: None,
2180                         htlc_maximum_msat: None,
2181                 }])]
2182         }
2183
2184         fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2185                 let zero_fees = RoutingFees {
2186                         base_msat: 0,
2187                         proportional_millionths: 0,
2188                 };
2189                 vec![RouteHint(vec![RouteHintHop {
2190                         src_node_id: nodes[2].clone(),
2191                         short_channel_id: 5,
2192                         fees: RoutingFees {
2193                                 base_msat: 100,
2194                                 proportional_millionths: 0,
2195                         },
2196                         cltv_expiry_delta: (5 << 8) | 1,
2197                         htlc_minimum_msat: None,
2198                         htlc_maximum_msat: None,
2199                 }, RouteHintHop {
2200                         src_node_id: nodes[3].clone(),
2201                         short_channel_id: 8,
2202                         fees: zero_fees,
2203                         cltv_expiry_delta: (8 << 8) | 1,
2204                         htlc_minimum_msat: None,
2205                         htlc_maximum_msat: None,
2206                 }
2207                 ]), RouteHint(vec![RouteHintHop {
2208                         src_node_id: nodes[4].clone(),
2209                         short_channel_id: 9,
2210                         fees: RoutingFees {
2211                                 base_msat: 1001,
2212                                 proportional_millionths: 0,
2213                         },
2214                         cltv_expiry_delta: (9 << 8) | 1,
2215                         htlc_minimum_msat: None,
2216                         htlc_maximum_msat: None,
2217                 }]), RouteHint(vec![RouteHintHop {
2218                         src_node_id: nodes[5].clone(),
2219                         short_channel_id: 10,
2220                         fees: zero_fees,
2221                         cltv_expiry_delta: (10 << 8) | 1,
2222                         htlc_minimum_msat: None,
2223                         htlc_maximum_msat: None,
2224                 }])]
2225         }
2226
2227         #[test]
2228         fn partial_route_hint_test() {
2229                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2230                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2231
2232                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2233                 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2234                 // RouteHint may be partially used by the algo to build the best path.
2235
2236                 // First check that last hop can't have its source as the payee.
2237                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2238                         src_node_id: nodes[6],
2239                         short_channel_id: 8,
2240                         fees: RoutingFees {
2241                                 base_msat: 1000,
2242                                 proportional_millionths: 0,
2243                         },
2244                         cltv_expiry_delta: (8 << 8) | 1,
2245                         htlc_minimum_msat: None,
2246                         htlc_maximum_msat: None,
2247                 }]);
2248
2249                 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2250                 invalid_last_hops.push(invalid_last_hop);
2251                 {
2252                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)) {
2253                                 assert_eq!(err, "Last hop cannot have a payee as a source.");
2254                         } else { panic!(); }
2255                 }
2256
2257                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops_multi_private_channels(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2258                 assert_eq!(route.paths[0].len(), 5);
2259
2260                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2261                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2262                 assert_eq!(route.paths[0][0].fee_msat, 100);
2263                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2264                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2265                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2266
2267                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2268                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2269                 assert_eq!(route.paths[0][1].fee_msat, 0);
2270                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2271                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2272                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2273
2274                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2275                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2276                 assert_eq!(route.paths[0][2].fee_msat, 0);
2277                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2278                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2279                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2280
2281                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2282                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2283                 assert_eq!(route.paths[0][3].fee_msat, 0);
2284                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2285                 // If we have a peer in the node map, we'll use their features here since we don't have
2286                 // a way of figuring out their features from the invoice:
2287                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2288                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2289
2290                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2291                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2292                 assert_eq!(route.paths[0][4].fee_msat, 100);
2293                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2294                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2295                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2296         }
2297
2298         fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2299                 let zero_fees = RoutingFees {
2300                         base_msat: 0,
2301                         proportional_millionths: 0,
2302                 };
2303                 vec![RouteHint(vec![RouteHintHop {
2304                         src_node_id: nodes[3].clone(),
2305                         short_channel_id: 8,
2306                         fees: zero_fees,
2307                         cltv_expiry_delta: (8 << 8) | 1,
2308                         htlc_minimum_msat: None,
2309                         htlc_maximum_msat: None,
2310                 }]), RouteHint(vec![
2311
2312                 ]), RouteHint(vec![RouteHintHop {
2313                         src_node_id: nodes[5].clone(),
2314                         short_channel_id: 10,
2315                         fees: zero_fees,
2316                         cltv_expiry_delta: (10 << 8) | 1,
2317                         htlc_minimum_msat: None,
2318                         htlc_maximum_msat: None,
2319                 }])]
2320         }
2321
2322         #[test]
2323         fn ignores_empty_last_hops_test() {
2324                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2325                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2326
2327                 // Test handling of an empty RouteHint passed in Invoice.
2328
2329                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &empty_last_hop(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2330                 assert_eq!(route.paths[0].len(), 5);
2331
2332                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2333                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2334                 assert_eq!(route.paths[0][0].fee_msat, 100);
2335                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2336                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2337                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2338
2339                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2340                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2341                 assert_eq!(route.paths[0][1].fee_msat, 0);
2342                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2343                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2344                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2345
2346                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2347                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2348                 assert_eq!(route.paths[0][2].fee_msat, 0);
2349                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2350                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2351                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2352
2353                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2354                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2355                 assert_eq!(route.paths[0][3].fee_msat, 0);
2356                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2357                 // If we have a peer in the node map, we'll use their features here since we don't have
2358                 // a way of figuring out their features from the invoice:
2359                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2360                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2361
2362                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2363                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2364                 assert_eq!(route.paths[0][4].fee_msat, 100);
2365                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2366                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2367                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2368         }
2369
2370         fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2371                 let zero_fees = RoutingFees {
2372                         base_msat: 0,
2373                         proportional_millionths: 0,
2374                 };
2375                 vec![RouteHint(vec![RouteHintHop {
2376                         src_node_id: nodes[2].clone(),
2377                         short_channel_id: 5,
2378                         fees: RoutingFees {
2379                                 base_msat: 100,
2380                                 proportional_millionths: 0,
2381                         },
2382                         cltv_expiry_delta: (5 << 8) | 1,
2383                         htlc_minimum_msat: None,
2384                         htlc_maximum_msat: None,
2385                 }, RouteHintHop {
2386                         src_node_id: nodes[3].clone(),
2387                         short_channel_id: 8,
2388                         fees: zero_fees,
2389                         cltv_expiry_delta: (8 << 8) | 1,
2390                         htlc_minimum_msat: None,
2391                         htlc_maximum_msat: None,
2392                 }]), RouteHint(vec![RouteHintHop {
2393                         src_node_id: nodes[5].clone(),
2394                         short_channel_id: 10,
2395                         fees: zero_fees,
2396                         cltv_expiry_delta: (10 << 8) | 1,
2397                         htlc_minimum_msat: None,
2398                         htlc_maximum_msat: None,
2399                 }])]
2400         }
2401
2402         #[test]
2403         fn multi_hint_last_hops_test() {
2404                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2405                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2406                 // Test through channels 2, 3, 5, 8.
2407                 // Test shows that multiple hop hints are considered.
2408
2409                 // Disabling channels 6 & 7 by flags=2
2410                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2411                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2412                         short_channel_id: 6,
2413                         timestamp: 2,
2414                         flags: 2, // to disable
2415                         cltv_expiry_delta: 0,
2416                         htlc_minimum_msat: 0,
2417                         htlc_maximum_msat: OptionalField::Absent,
2418                         fee_base_msat: 0,
2419                         fee_proportional_millionths: 0,
2420                         excess_data: Vec::new()
2421                 });
2422                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2423                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2424                         short_channel_id: 7,
2425                         timestamp: 2,
2426                         flags: 2, // to disable
2427                         cltv_expiry_delta: 0,
2428                         htlc_minimum_msat: 0,
2429                         htlc_maximum_msat: OptionalField::Absent,
2430                         fee_base_msat: 0,
2431                         fee_proportional_millionths: 0,
2432                         excess_data: Vec::new()
2433                 });
2434
2435                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &multi_hint_last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2436                 assert_eq!(route.paths[0].len(), 4);
2437
2438                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2439                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2440                 assert_eq!(route.paths[0][0].fee_msat, 200);
2441                 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2442                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2443                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2444
2445                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2446                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2447                 assert_eq!(route.paths[0][1].fee_msat, 100);
2448                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2449                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2450                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2451
2452                 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2453                 assert_eq!(route.paths[0][2].short_channel_id, 5);
2454                 assert_eq!(route.paths[0][2].fee_msat, 0);
2455                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2456                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2457                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2458
2459                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2460                 assert_eq!(route.paths[0][3].short_channel_id, 8);
2461                 assert_eq!(route.paths[0][3].fee_msat, 100);
2462                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2463                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2464                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2465         }
2466
2467         fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2468                 let zero_fees = RoutingFees {
2469                         base_msat: 0,
2470                         proportional_millionths: 0,
2471                 };
2472                 vec![RouteHint(vec![RouteHintHop {
2473                         src_node_id: nodes[4].clone(),
2474                         short_channel_id: 11,
2475                         fees: zero_fees,
2476                         cltv_expiry_delta: (11 << 8) | 1,
2477                         htlc_minimum_msat: None,
2478                         htlc_maximum_msat: None,
2479                 }, RouteHintHop {
2480                         src_node_id: nodes[3].clone(),
2481                         short_channel_id: 8,
2482                         fees: zero_fees,
2483                         cltv_expiry_delta: (8 << 8) | 1,
2484                         htlc_minimum_msat: None,
2485                         htlc_maximum_msat: None,
2486                 }]), RouteHint(vec![RouteHintHop {
2487                         src_node_id: nodes[4].clone(),
2488                         short_channel_id: 9,
2489                         fees: RoutingFees {
2490                                 base_msat: 1001,
2491                                 proportional_millionths: 0,
2492                         },
2493                         cltv_expiry_delta: (9 << 8) | 1,
2494                         htlc_minimum_msat: None,
2495                         htlc_maximum_msat: None,
2496                 }]), RouteHint(vec![RouteHintHop {
2497                         src_node_id: nodes[5].clone(),
2498                         short_channel_id: 10,
2499                         fees: zero_fees,
2500                         cltv_expiry_delta: (10 << 8) | 1,
2501                         htlc_minimum_msat: None,
2502                         htlc_maximum_msat: None,
2503                 }])]
2504         }
2505
2506         #[test]
2507         fn last_hops_with_public_channel_test() {
2508                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2509                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2510                 // This test shows that public routes can be present in the invoice
2511                 // which would be handled in the same manner.
2512
2513                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops_with_public_channel(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2514                 assert_eq!(route.paths[0].len(), 5);
2515
2516                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2517                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2518                 assert_eq!(route.paths[0][0].fee_msat, 100);
2519                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2520                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2521                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2522
2523                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2524                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2525                 assert_eq!(route.paths[0][1].fee_msat, 0);
2526                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2527                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2528                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2529
2530                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2531                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2532                 assert_eq!(route.paths[0][2].fee_msat, 0);
2533                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2534                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2535                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2536
2537                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2538                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2539                 assert_eq!(route.paths[0][3].fee_msat, 0);
2540                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2541                 // If we have a peer in the node map, we'll use their features here since we don't have
2542                 // a way of figuring out their features from the invoice:
2543                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2544                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2545
2546                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2547                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2548                 assert_eq!(route.paths[0][4].fee_msat, 100);
2549                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2550                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2551                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2552         }
2553
2554         #[test]
2555         fn our_chans_last_hop_connect_test() {
2556                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2557                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2558
2559                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2560                 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2561                 let mut last_hops = last_hops(&nodes);
2562                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2563                 assert_eq!(route.paths[0].len(), 2);
2564
2565                 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2566                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2567                 assert_eq!(route.paths[0][0].fee_msat, 0);
2568                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2569                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2570                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2571
2572                 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2573                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2574                 assert_eq!(route.paths[0][1].fee_msat, 100);
2575                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2576                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2577                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2578
2579                 last_hops[0].0[0].fees.base_msat = 1000;
2580
2581                 // Revert to via 6 as the fee on 8 goes up
2582                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2583                 assert_eq!(route.paths[0].len(), 4);
2584
2585                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2586                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2587                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2588                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2589                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2590                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2591
2592                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2593                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2594                 assert_eq!(route.paths[0][1].fee_msat, 100);
2595                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2596                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2597                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2598
2599                 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2600                 assert_eq!(route.paths[0][2].short_channel_id, 7);
2601                 assert_eq!(route.paths[0][2].fee_msat, 0);
2602                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2603                 // If we have a peer in the node map, we'll use their features here since we don't have
2604                 // a way of figuring out their features from the invoice:
2605                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2606                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2607
2608                 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2609                 assert_eq!(route.paths[0][3].short_channel_id, 10);
2610                 assert_eq!(route.paths[0][3].fee_msat, 100);
2611                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2612                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2613                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2614
2615                 // ...but still use 8 for larger payments as 6 has a variable feerate
2616                 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger)).unwrap();
2617                 assert_eq!(route.paths[0].len(), 5);
2618
2619                 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2620                 assert_eq!(route.paths[0][0].short_channel_id, 2);
2621                 assert_eq!(route.paths[0][0].fee_msat, 3000);
2622                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2623                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2624                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2625
2626                 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2627                 assert_eq!(route.paths[0][1].short_channel_id, 4);
2628                 assert_eq!(route.paths[0][1].fee_msat, 0);
2629                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2630                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2631                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2632
2633                 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2634                 assert_eq!(route.paths[0][2].short_channel_id, 6);
2635                 assert_eq!(route.paths[0][2].fee_msat, 0);
2636                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2637                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2638                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2639
2640                 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2641                 assert_eq!(route.paths[0][3].short_channel_id, 11);
2642                 assert_eq!(route.paths[0][3].fee_msat, 1000);
2643                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2644                 // If we have a peer in the node map, we'll use their features here since we don't have
2645                 // a way of figuring out their features from the invoice:
2646                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2647                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2648
2649                 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2650                 assert_eq!(route.paths[0][4].short_channel_id, 8);
2651                 assert_eq!(route.paths[0][4].fee_msat, 2000);
2652                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2653                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2654                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2655         }
2656
2657         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> {
2658                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2659                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2660                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2661
2662                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2663                 let last_hops = RouteHint(vec![RouteHintHop {
2664                         src_node_id: middle_node_id,
2665                         short_channel_id: 8,
2666                         fees: RoutingFees {
2667                                 base_msat: 1000,
2668                                 proportional_millionths: last_hop_fee_prop,
2669                         },
2670                         cltv_expiry_delta: (8 << 8) | 1,
2671                         htlc_minimum_msat: None,
2672                         htlc_maximum_msat: last_hop_htlc_max,
2673                 }]);
2674                 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2675                 get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &vec![&last_hops], route_val, 42, Arc::new(test_utils::TestLogger::new()))
2676         }
2677
2678         #[test]
2679         fn unannounced_path_test() {
2680                 // We should be able to send a payment to a destination without any help of a routing graph
2681                 // if we have a channel with a common counterparty that appears in the first and last hop
2682                 // hints.
2683                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2684
2685                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2686                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2687                 assert_eq!(route.paths[0].len(), 2);
2688
2689                 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2690                 assert_eq!(route.paths[0][0].short_channel_id, 42);
2691                 assert_eq!(route.paths[0][0].fee_msat, 1001);
2692                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2693                 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2694                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2695
2696                 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2697                 assert_eq!(route.paths[0][1].short_channel_id, 8);
2698                 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2699                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2700                 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2701                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2702         }
2703
2704         #[test]
2705         fn overflow_unannounced_path_test_liquidity_underflow() {
2706                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2707                 // the last-hop had a fee which overflowed a u64, we'd panic.
2708                 // This was due to us adding the first-hop from us unconditionally, causing us to think
2709                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2710                 // In this test, we previously hit a subtraction underflow due to having less available
2711                 // liquidity at the last hop than 0.
2712                 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());
2713         }
2714
2715         #[test]
2716         fn overflow_unannounced_path_test_feerate_overflow() {
2717                 // This tests for the same case as above, except instead of hitting a subtraction
2718                 // underflow, we hit a case where the fee charged at a hop overflowed.
2719                 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());
2720         }
2721
2722         #[test]
2723         fn available_amount_while_routing_test() {
2724                 // Tests whether we choose the correct available channel amount while routing.
2725
2726                 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2727                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2728
2729                 // We will use a simple single-path route from
2730                 // our node to node2 via node0: channels {1, 3}.
2731
2732                 // First disable all other paths.
2733                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2734                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2735                         short_channel_id: 2,
2736                         timestamp: 2,
2737                         flags: 2,
2738                         cltv_expiry_delta: 0,
2739                         htlc_minimum_msat: 0,
2740                         htlc_maximum_msat: OptionalField::Present(100_000),
2741                         fee_base_msat: 0,
2742                         fee_proportional_millionths: 0,
2743                         excess_data: Vec::new()
2744                 });
2745                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2746                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2747                         short_channel_id: 12,
2748                         timestamp: 2,
2749                         flags: 2,
2750                         cltv_expiry_delta: 0,
2751                         htlc_minimum_msat: 0,
2752                         htlc_maximum_msat: OptionalField::Present(100_000),
2753                         fee_base_msat: 0,
2754                         fee_proportional_millionths: 0,
2755                         excess_data: Vec::new()
2756                 });
2757
2758                 // Make the first channel (#1) very permissive,
2759                 // and we will be testing all limits on the second channel.
2760                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2761                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2762                         short_channel_id: 1,
2763                         timestamp: 2,
2764                         flags: 0,
2765                         cltv_expiry_delta: 0,
2766                         htlc_minimum_msat: 0,
2767                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2768                         fee_base_msat: 0,
2769                         fee_proportional_millionths: 0,
2770                         excess_data: Vec::new()
2771                 });
2772
2773                 // First, let's see if routing works if we have absolutely no idea about the available amount.
2774                 // In this case, it should be set to 250_000 sats.
2775                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2776                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2777                         short_channel_id: 3,
2778                         timestamp: 2,
2779                         flags: 0,
2780                         cltv_expiry_delta: 0,
2781                         htlc_minimum_msat: 0,
2782                         htlc_maximum_msat: OptionalField::Absent,
2783                         fee_base_msat: 0,
2784                         fee_proportional_millionths: 0,
2785                         excess_data: Vec::new()
2786                 });
2787
2788                 {
2789                         // Attempt to route more than available results in a failure.
2790                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2791                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2792                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2793                         } else { panic!(); }
2794                 }
2795
2796                 {
2797                         // Now, attempt to route an exact amount we have should be fine.
2798                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2799                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2800                         assert_eq!(route.paths.len(), 1);
2801                         let path = route.paths.last().unwrap();
2802                         assert_eq!(path.len(), 2);
2803                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2804                         assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2805                 }
2806
2807                 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2808                 // Disable channel #1 and use another first hop.
2809                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2810                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2811                         short_channel_id: 1,
2812                         timestamp: 3,
2813                         flags: 2,
2814                         cltv_expiry_delta: 0,
2815                         htlc_minimum_msat: 0,
2816                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2817                         fee_base_msat: 0,
2818                         fee_proportional_millionths: 0,
2819                         excess_data: Vec::new()
2820                 });
2821
2822                 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2823                 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
2824
2825                 {
2826                         // Attempt to route more than available results in a failure.
2827                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2828                                         Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2829                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2830                         } else { panic!(); }
2831                 }
2832
2833                 {
2834                         // Now, attempt to route an exact amount we have should be fine.
2835                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2836                                 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2837                         assert_eq!(route.paths.len(), 1);
2838                         let path = route.paths.last().unwrap();
2839                         assert_eq!(path.len(), 2);
2840                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2841                         assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2842                 }
2843
2844                 // Enable channel #1 back.
2845                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2846                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2847                         short_channel_id: 1,
2848                         timestamp: 4,
2849                         flags: 0,
2850                         cltv_expiry_delta: 0,
2851                         htlc_minimum_msat: 0,
2852                         htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2853                         fee_base_msat: 0,
2854                         fee_proportional_millionths: 0,
2855                         excess_data: Vec::new()
2856                 });
2857
2858
2859                 // Now let's see if routing works if we know only htlc_maximum_msat.
2860                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2861                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2862                         short_channel_id: 3,
2863                         timestamp: 3,
2864                         flags: 0,
2865                         cltv_expiry_delta: 0,
2866                         htlc_minimum_msat: 0,
2867                         htlc_maximum_msat: OptionalField::Present(15_000),
2868                         fee_base_msat: 0,
2869                         fee_proportional_millionths: 0,
2870                         excess_data: Vec::new()
2871                 });
2872
2873                 {
2874                         // Attempt to route more than available results in a failure.
2875                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2876                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2877                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2878                         } else { panic!(); }
2879                 }
2880
2881                 {
2882                         // Now, attempt to route an exact amount we have should be fine.
2883                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2884                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2885                         assert_eq!(route.paths.len(), 1);
2886                         let path = route.paths.last().unwrap();
2887                         assert_eq!(path.len(), 2);
2888                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2889                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2890                 }
2891
2892                 // Now let's see if routing works if we know only capacity from the UTXO.
2893
2894                 // We can't change UTXO capacity on the fly, so we'll disable
2895                 // the existing channel and add another one with the capacity we need.
2896                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2897                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2898                         short_channel_id: 3,
2899                         timestamp: 4,
2900                         flags: 2,
2901                         cltv_expiry_delta: 0,
2902                         htlc_minimum_msat: 0,
2903                         htlc_maximum_msat: OptionalField::Absent,
2904                         fee_base_msat: 0,
2905                         fee_proportional_millionths: 0,
2906                         excess_data: Vec::new()
2907                 });
2908
2909                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2910                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2911                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2912                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2913                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2914
2915                 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2916                 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2917
2918                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2919                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2920                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2921                         short_channel_id: 333,
2922                         timestamp: 1,
2923                         flags: 0,
2924                         cltv_expiry_delta: (3 << 8) | 1,
2925                         htlc_minimum_msat: 0,
2926                         htlc_maximum_msat: OptionalField::Absent,
2927                         fee_base_msat: 0,
2928                         fee_proportional_millionths: 0,
2929                         excess_data: Vec::new()
2930                 });
2931                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2932                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2933                         short_channel_id: 333,
2934                         timestamp: 1,
2935                         flags: 1,
2936                         cltv_expiry_delta: (3 << 8) | 2,
2937                         htlc_minimum_msat: 0,
2938                         htlc_maximum_msat: OptionalField::Absent,
2939                         fee_base_msat: 100,
2940                         fee_proportional_millionths: 0,
2941                         excess_data: Vec::new()
2942                 });
2943
2944                 {
2945                         // Attempt to route more than available results in a failure.
2946                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2947                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2948                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2949                         } else { panic!(); }
2950                 }
2951
2952                 {
2953                         // Now, attempt to route an exact amount we have should be fine.
2954                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2955                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2956                         assert_eq!(route.paths.len(), 1);
2957                         let path = route.paths.last().unwrap();
2958                         assert_eq!(path.len(), 2);
2959                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2960                         assert_eq!(path.last().unwrap().fee_msat, 15_000);
2961                 }
2962
2963                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2964                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2965                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2966                         short_channel_id: 333,
2967                         timestamp: 6,
2968                         flags: 0,
2969                         cltv_expiry_delta: 0,
2970                         htlc_minimum_msat: 0,
2971                         htlc_maximum_msat: OptionalField::Present(10_000),
2972                         fee_base_msat: 0,
2973                         fee_proportional_millionths: 0,
2974                         excess_data: Vec::new()
2975                 });
2976
2977                 {
2978                         // Attempt to route more than available results in a failure.
2979                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2980                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2981                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2982                         } else { panic!(); }
2983                 }
2984
2985                 {
2986                         // Now, attempt to route an exact amount we have should be fine.
2987                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2988                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2989                         assert_eq!(route.paths.len(), 1);
2990                         let path = route.paths.last().unwrap();
2991                         assert_eq!(path.len(), 2);
2992                         assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2993                         assert_eq!(path.last().unwrap().fee_msat, 10_000);
2994                 }
2995         }
2996
2997         #[test]
2998         fn available_liquidity_last_hop_test() {
2999                 // Check that available liquidity properly limits the path even when only
3000                 // one of the latter hops is limited.
3001                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3002                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3003
3004                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3005                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3006                 // Total capacity: 50 sats.
3007
3008                 // Disable other potential paths.
3009                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3010                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3011                         short_channel_id: 2,
3012                         timestamp: 2,
3013                         flags: 2,
3014                         cltv_expiry_delta: 0,
3015                         htlc_minimum_msat: 0,
3016                         htlc_maximum_msat: OptionalField::Present(100_000),
3017                         fee_base_msat: 0,
3018                         fee_proportional_millionths: 0,
3019                         excess_data: Vec::new()
3020                 });
3021                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3022                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3023                         short_channel_id: 7,
3024                         timestamp: 2,
3025                         flags: 2,
3026                         cltv_expiry_delta: 0,
3027                         htlc_minimum_msat: 0,
3028                         htlc_maximum_msat: OptionalField::Present(100_000),
3029                         fee_base_msat: 0,
3030                         fee_proportional_millionths: 0,
3031                         excess_data: Vec::new()
3032                 });
3033
3034                 // Limit capacities
3035
3036                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3037                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3038                         short_channel_id: 12,
3039                         timestamp: 2,
3040                         flags: 0,
3041                         cltv_expiry_delta: 0,
3042                         htlc_minimum_msat: 0,
3043                         htlc_maximum_msat: OptionalField::Present(100_000),
3044                         fee_base_msat: 0,
3045                         fee_proportional_millionths: 0,
3046                         excess_data: Vec::new()
3047                 });
3048                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3049                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3050                         short_channel_id: 13,
3051                         timestamp: 2,
3052                         flags: 0,
3053                         cltv_expiry_delta: 0,
3054                         htlc_minimum_msat: 0,
3055                         htlc_maximum_msat: OptionalField::Present(100_000),
3056                         fee_base_msat: 0,
3057                         fee_proportional_millionths: 0,
3058                         excess_data: Vec::new()
3059                 });
3060
3061                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3062                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3063                         short_channel_id: 6,
3064                         timestamp: 2,
3065                         flags: 0,
3066                         cltv_expiry_delta: 0,
3067                         htlc_minimum_msat: 0,
3068                         htlc_maximum_msat: OptionalField::Present(50_000),
3069                         fee_base_msat: 0,
3070                         fee_proportional_millionths: 0,
3071                         excess_data: Vec::new()
3072                 });
3073                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3074                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3075                         short_channel_id: 11,
3076                         timestamp: 2,
3077                         flags: 0,
3078                         cltv_expiry_delta: 0,
3079                         htlc_minimum_msat: 0,
3080                         htlc_maximum_msat: OptionalField::Present(100_000),
3081                         fee_base_msat: 0,
3082                         fee_proportional_millionths: 0,
3083                         excess_data: Vec::new()
3084                 });
3085                 {
3086                         // Attempt to route more than available results in a failure.
3087                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3088                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
3089                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3090                         } else { panic!(); }
3091                 }
3092
3093                 {
3094                         // Now, attempt to route 49 sats (just a bit below the capacity).
3095                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3096                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
3097                         assert_eq!(route.paths.len(), 1);
3098                         let mut total_amount_paid_msat = 0;
3099                         for path in &route.paths {
3100                                 assert_eq!(path.len(), 4);
3101                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3102                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3103                         }
3104                         assert_eq!(total_amount_paid_msat, 49_000);
3105                 }
3106
3107                 {
3108                         // Attempt to route an exact amount is also fine
3109                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3110                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3111                         assert_eq!(route.paths.len(), 1);
3112                         let mut total_amount_paid_msat = 0;
3113                         for path in &route.paths {
3114                                 assert_eq!(path.len(), 4);
3115                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3116                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3117                         }
3118                         assert_eq!(total_amount_paid_msat, 50_000);
3119                 }
3120         }
3121
3122         #[test]
3123         fn ignore_fee_first_hop_test() {
3124                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3125                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3126
3127                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3128                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3129                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3130                         short_channel_id: 1,
3131                         timestamp: 2,
3132                         flags: 0,
3133                         cltv_expiry_delta: 0,
3134                         htlc_minimum_msat: 0,
3135                         htlc_maximum_msat: OptionalField::Present(100_000),
3136                         fee_base_msat: 1_000_000,
3137                         fee_proportional_millionths: 0,
3138                         excess_data: Vec::new()
3139                 });
3140                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3141                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3142                         short_channel_id: 3,
3143                         timestamp: 2,
3144                         flags: 0,
3145                         cltv_expiry_delta: 0,
3146                         htlc_minimum_msat: 0,
3147                         htlc_maximum_msat: OptionalField::Present(50_000),
3148                         fee_base_msat: 0,
3149                         fee_proportional_millionths: 0,
3150                         excess_data: Vec::new()
3151                 });
3152
3153                 {
3154                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
3155                         assert_eq!(route.paths.len(), 1);
3156                         let mut total_amount_paid_msat = 0;
3157                         for path in &route.paths {
3158                                 assert_eq!(path.len(), 2);
3159                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3160                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3161                         }
3162                         assert_eq!(total_amount_paid_msat, 50_000);
3163                 }
3164         }
3165
3166         #[test]
3167         fn simple_mpp_route_test() {
3168                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3169                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3170
3171                 // We need a route consisting of 3 paths:
3172                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3173                 // To achieve this, the amount being transferred should be around
3174                 // the total capacity of these 3 paths.
3175
3176                 // First, we set limits on these (previously unlimited) channels.
3177                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3178
3179                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3180                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3181                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3182                         short_channel_id: 1,
3183                         timestamp: 2,
3184                         flags: 0,
3185                         cltv_expiry_delta: 0,
3186                         htlc_minimum_msat: 0,
3187                         htlc_maximum_msat: OptionalField::Present(100_000),
3188                         fee_base_msat: 0,
3189                         fee_proportional_millionths: 0,
3190                         excess_data: Vec::new()
3191                 });
3192                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3193                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3194                         short_channel_id: 3,
3195                         timestamp: 2,
3196                         flags: 0,
3197                         cltv_expiry_delta: 0,
3198                         htlc_minimum_msat: 0,
3199                         htlc_maximum_msat: OptionalField::Present(50_000),
3200                         fee_base_msat: 0,
3201                         fee_proportional_millionths: 0,
3202                         excess_data: Vec::new()
3203                 });
3204
3205                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3206                 // (total limit 60).
3207                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3208                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3209                         short_channel_id: 12,
3210                         timestamp: 2,
3211                         flags: 0,
3212                         cltv_expiry_delta: 0,
3213                         htlc_minimum_msat: 0,
3214                         htlc_maximum_msat: OptionalField::Present(60_000),
3215                         fee_base_msat: 0,
3216                         fee_proportional_millionths: 0,
3217                         excess_data: Vec::new()
3218                 });
3219                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3220                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3221                         short_channel_id: 13,
3222                         timestamp: 2,
3223                         flags: 0,
3224                         cltv_expiry_delta: 0,
3225                         htlc_minimum_msat: 0,
3226                         htlc_maximum_msat: OptionalField::Present(60_000),
3227                         fee_base_msat: 0,
3228                         fee_proportional_millionths: 0,
3229                         excess_data: Vec::new()
3230                 });
3231
3232                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3233                 // (total capacity 180 sats).
3234                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3235                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3236                         short_channel_id: 2,
3237                         timestamp: 2,
3238                         flags: 0,
3239                         cltv_expiry_delta: 0,
3240                         htlc_minimum_msat: 0,
3241                         htlc_maximum_msat: OptionalField::Present(200_000),
3242                         fee_base_msat: 0,
3243                         fee_proportional_millionths: 0,
3244                         excess_data: Vec::new()
3245                 });
3246                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3247                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3248                         short_channel_id: 4,
3249                         timestamp: 2,
3250                         flags: 0,
3251                         cltv_expiry_delta: 0,
3252                         htlc_minimum_msat: 0,
3253                         htlc_maximum_msat: OptionalField::Present(180_000),
3254                         fee_base_msat: 0,
3255                         fee_proportional_millionths: 0,
3256                         excess_data: Vec::new()
3257                 });
3258
3259                 {
3260                         // Attempt to route more than available results in a failure.
3261                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
3262                                         &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
3263                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3264                         } else { panic!(); }
3265                 }
3266
3267                 {
3268                         // Now, attempt to route 250 sats (just a bit below the capacity).
3269                         // Our algorithm should provide us with these 3 paths.
3270                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3271                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
3272                         assert_eq!(route.paths.len(), 3);
3273                         let mut total_amount_paid_msat = 0;
3274                         for path in &route.paths {
3275                                 assert_eq!(path.len(), 2);
3276                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3277                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3278                         }
3279                         assert_eq!(total_amount_paid_msat, 250_000);
3280                 }
3281
3282                 {
3283                         // Attempt to route an exact amount is also fine
3284                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3285                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
3286                         assert_eq!(route.paths.len(), 3);
3287                         let mut total_amount_paid_msat = 0;
3288                         for path in &route.paths {
3289                                 assert_eq!(path.len(), 2);
3290                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3291                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3292                         }
3293                         assert_eq!(total_amount_paid_msat, 290_000);
3294                 }
3295         }
3296
3297         #[test]
3298         fn long_mpp_route_test() {
3299                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3300                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3301
3302                 // We need a route consisting of 3 paths:
3303                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3304                 // Note that these paths overlap (channels 5, 12, 13).
3305                 // We will route 300 sats.
3306                 // Each path will have 100 sats capacity, those channels which
3307                 // are used twice will have 200 sats capacity.
3308
3309                 // Disable other potential paths.
3310                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3311                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3312                         short_channel_id: 2,
3313                         timestamp: 2,
3314                         flags: 2,
3315                         cltv_expiry_delta: 0,
3316                         htlc_minimum_msat: 0,
3317                         htlc_maximum_msat: OptionalField::Present(100_000),
3318                         fee_base_msat: 0,
3319                         fee_proportional_millionths: 0,
3320                         excess_data: Vec::new()
3321                 });
3322                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3323                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3324                         short_channel_id: 7,
3325                         timestamp: 2,
3326                         flags: 2,
3327                         cltv_expiry_delta: 0,
3328                         htlc_minimum_msat: 0,
3329                         htlc_maximum_msat: OptionalField::Present(100_000),
3330                         fee_base_msat: 0,
3331                         fee_proportional_millionths: 0,
3332                         excess_data: Vec::new()
3333                 });
3334
3335                 // Path via {node0, node2} is channels {1, 3, 5}.
3336                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3337                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3338                         short_channel_id: 1,
3339                         timestamp: 2,
3340                         flags: 0,
3341                         cltv_expiry_delta: 0,
3342                         htlc_minimum_msat: 0,
3343                         htlc_maximum_msat: OptionalField::Present(100_000),
3344                         fee_base_msat: 0,
3345                         fee_proportional_millionths: 0,
3346                         excess_data: Vec::new()
3347                 });
3348                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3349                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3350                         short_channel_id: 3,
3351                         timestamp: 2,
3352                         flags: 0,
3353                         cltv_expiry_delta: 0,
3354                         htlc_minimum_msat: 0,
3355                         htlc_maximum_msat: OptionalField::Present(100_000),
3356                         fee_base_msat: 0,
3357                         fee_proportional_millionths: 0,
3358                         excess_data: Vec::new()
3359                 });
3360
3361                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3362                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3363                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3364                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3365                         short_channel_id: 5,
3366                         timestamp: 2,
3367                         flags: 0,
3368                         cltv_expiry_delta: 0,
3369                         htlc_minimum_msat: 0,
3370                         htlc_maximum_msat: OptionalField::Present(200_000),
3371                         fee_base_msat: 0,
3372                         fee_proportional_millionths: 0,
3373                         excess_data: Vec::new()
3374                 });
3375
3376                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3377                 // Add 100 sats to the capacities of {12, 13}, because these channels
3378                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3379                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3380                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3381                         short_channel_id: 12,
3382                         timestamp: 2,
3383                         flags: 0,
3384                         cltv_expiry_delta: 0,
3385                         htlc_minimum_msat: 0,
3386                         htlc_maximum_msat: OptionalField::Present(200_000),
3387                         fee_base_msat: 0,
3388                         fee_proportional_millionths: 0,
3389                         excess_data: Vec::new()
3390                 });
3391                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3392                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3393                         short_channel_id: 13,
3394                         timestamp: 2,
3395                         flags: 0,
3396                         cltv_expiry_delta: 0,
3397                         htlc_minimum_msat: 0,
3398                         htlc_maximum_msat: OptionalField::Present(200_000),
3399                         fee_base_msat: 0,
3400                         fee_proportional_millionths: 0,
3401                         excess_data: Vec::new()
3402                 });
3403
3404                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3405                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3406                         short_channel_id: 6,
3407                         timestamp: 2,
3408                         flags: 0,
3409                         cltv_expiry_delta: 0,
3410                         htlc_minimum_msat: 0,
3411                         htlc_maximum_msat: OptionalField::Present(100_000),
3412                         fee_base_msat: 0,
3413                         fee_proportional_millionths: 0,
3414                         excess_data: Vec::new()
3415                 });
3416                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3417                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3418                         short_channel_id: 11,
3419                         timestamp: 2,
3420                         flags: 0,
3421                         cltv_expiry_delta: 0,
3422                         htlc_minimum_msat: 0,
3423                         htlc_maximum_msat: OptionalField::Present(100_000),
3424                         fee_base_msat: 0,
3425                         fee_proportional_millionths: 0,
3426                         excess_data: Vec::new()
3427                 });
3428
3429                 // Path via {node7, node2} is channels {12, 13, 5}.
3430                 // We already limited them to 200 sats (they are used twice for 100 sats).
3431                 // Nothing to do here.
3432
3433                 {
3434                         // Attempt to route more than available results in a failure.
3435                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3436                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3437                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3438                         } else { panic!(); }
3439                 }
3440
3441                 {
3442                         // Now, attempt to route 300 sats (exact amount we can route).
3443                         // Our algorithm should provide us with these 3 paths, 100 sats each.
3444                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3445                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3446                         assert_eq!(route.paths.len(), 3);
3447
3448                         let mut total_amount_paid_msat = 0;
3449                         for path in &route.paths {
3450                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3451                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3452                         }
3453                         assert_eq!(total_amount_paid_msat, 300_000);
3454                 }
3455
3456         }
3457
3458         #[test]
3459         fn mpp_cheaper_route_test() {
3460                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3461                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3462
3463                 // This test checks that if we have two cheaper paths and one more expensive path,
3464                 // so that liquidity-wise any 2 of 3 combination is sufficient,
3465                 // two cheaper paths will be taken.
3466                 // These paths have equal available liquidity.
3467
3468                 // We need a combination of 3 paths:
3469                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3470                 // Note that these paths overlap (channels 5, 12, 13).
3471                 // Each path will have 100 sats capacity, those channels which
3472                 // are used twice will have 200 sats capacity.
3473
3474                 // Disable other potential paths.
3475                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3476                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3477                         short_channel_id: 2,
3478                         timestamp: 2,
3479                         flags: 2,
3480                         cltv_expiry_delta: 0,
3481                         htlc_minimum_msat: 0,
3482                         htlc_maximum_msat: OptionalField::Present(100_000),
3483                         fee_base_msat: 0,
3484                         fee_proportional_millionths: 0,
3485                         excess_data: Vec::new()
3486                 });
3487                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3488                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3489                         short_channel_id: 7,
3490                         timestamp: 2,
3491                         flags: 2,
3492                         cltv_expiry_delta: 0,
3493                         htlc_minimum_msat: 0,
3494                         htlc_maximum_msat: OptionalField::Present(100_000),
3495                         fee_base_msat: 0,
3496                         fee_proportional_millionths: 0,
3497                         excess_data: Vec::new()
3498                 });
3499
3500                 // Path via {node0, node2} is channels {1, 3, 5}.
3501                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3502                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3503                         short_channel_id: 1,
3504                         timestamp: 2,
3505                         flags: 0,
3506                         cltv_expiry_delta: 0,
3507                         htlc_minimum_msat: 0,
3508                         htlc_maximum_msat: OptionalField::Present(100_000),
3509                         fee_base_msat: 0,
3510                         fee_proportional_millionths: 0,
3511                         excess_data: Vec::new()
3512                 });
3513                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3514                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3515                         short_channel_id: 3,
3516                         timestamp: 2,
3517                         flags: 0,
3518                         cltv_expiry_delta: 0,
3519                         htlc_minimum_msat: 0,
3520                         htlc_maximum_msat: OptionalField::Present(100_000),
3521                         fee_base_msat: 0,
3522                         fee_proportional_millionths: 0,
3523                         excess_data: Vec::new()
3524                 });
3525
3526                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3527                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3528                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3529                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3530                         short_channel_id: 5,
3531                         timestamp: 2,
3532                         flags: 0,
3533                         cltv_expiry_delta: 0,
3534                         htlc_minimum_msat: 0,
3535                         htlc_maximum_msat: OptionalField::Present(200_000),
3536                         fee_base_msat: 0,
3537                         fee_proportional_millionths: 0,
3538                         excess_data: Vec::new()
3539                 });
3540
3541                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3542                 // Add 100 sats to the capacities of {12, 13}, because these channels
3543                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3544                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3545                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3546                         short_channel_id: 12,
3547                         timestamp: 2,
3548                         flags: 0,
3549                         cltv_expiry_delta: 0,
3550                         htlc_minimum_msat: 0,
3551                         htlc_maximum_msat: OptionalField::Present(200_000),
3552                         fee_base_msat: 0,
3553                         fee_proportional_millionths: 0,
3554                         excess_data: Vec::new()
3555                 });
3556                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3557                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3558                         short_channel_id: 13,
3559                         timestamp: 2,
3560                         flags: 0,
3561                         cltv_expiry_delta: 0,
3562                         htlc_minimum_msat: 0,
3563                         htlc_maximum_msat: OptionalField::Present(200_000),
3564                         fee_base_msat: 0,
3565                         fee_proportional_millionths: 0,
3566                         excess_data: Vec::new()
3567                 });
3568
3569                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3570                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3571                         short_channel_id: 6,
3572                         timestamp: 2,
3573                         flags: 0,
3574                         cltv_expiry_delta: 0,
3575                         htlc_minimum_msat: 0,
3576                         htlc_maximum_msat: OptionalField::Present(100_000),
3577                         fee_base_msat: 1_000,
3578                         fee_proportional_millionths: 0,
3579                         excess_data: Vec::new()
3580                 });
3581                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3582                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3583                         short_channel_id: 11,
3584                         timestamp: 2,
3585                         flags: 0,
3586                         cltv_expiry_delta: 0,
3587                         htlc_minimum_msat: 0,
3588                         htlc_maximum_msat: OptionalField::Present(100_000),
3589                         fee_base_msat: 0,
3590                         fee_proportional_millionths: 0,
3591                         excess_data: Vec::new()
3592                 });
3593
3594                 // Path via {node7, node2} is channels {12, 13, 5}.
3595                 // We already limited them to 200 sats (they are used twice for 100 sats).
3596                 // Nothing to do here.
3597
3598                 {
3599                         // Now, attempt to route 180 sats.
3600                         // Our algorithm should provide us with these 2 paths.
3601                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3602                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3603                         assert_eq!(route.paths.len(), 2);
3604
3605                         let mut total_value_transferred_msat = 0;
3606                         let mut total_paid_msat = 0;
3607                         for path in &route.paths {
3608                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3609                                 total_value_transferred_msat += path.last().unwrap().fee_msat;
3610                                 for hop in path {
3611                                         total_paid_msat += hop.fee_msat;
3612                                 }
3613                         }
3614                         // If we paid fee, this would be higher.
3615                         assert_eq!(total_value_transferred_msat, 180_000);
3616                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3617                         assert_eq!(total_fees_paid, 0);
3618                 }
3619         }
3620
3621         #[test]
3622         fn fees_on_mpp_route_test() {
3623                 // This test makes sure that MPP algorithm properly takes into account
3624                 // fees charged on the channels, by making the fees impactful:
3625                 // if the fee is not properly accounted for, the behavior is different.
3626                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3627                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3628
3629                 // We need a route consisting of 2 paths:
3630                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3631                 // We will route 200 sats, Each path will have 100 sats capacity.
3632
3633                 // This test is not particularly stable: e.g.,
3634                 // there's a way to route via {node0, node2, node4}.
3635                 // It works while pathfinding is deterministic, but can be broken otherwise.
3636                 // It's fine to ignore this concern for now.
3637
3638                 // Disable other potential paths.
3639                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3640                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3641                         short_channel_id: 2,
3642                         timestamp: 2,
3643                         flags: 2,
3644                         cltv_expiry_delta: 0,
3645                         htlc_minimum_msat: 0,
3646                         htlc_maximum_msat: OptionalField::Present(100_000),
3647                         fee_base_msat: 0,
3648                         fee_proportional_millionths: 0,
3649                         excess_data: Vec::new()
3650                 });
3651
3652                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3653                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3654                         short_channel_id: 7,
3655                         timestamp: 2,
3656                         flags: 2,
3657                         cltv_expiry_delta: 0,
3658                         htlc_minimum_msat: 0,
3659                         htlc_maximum_msat: OptionalField::Present(100_000),
3660                         fee_base_msat: 0,
3661                         fee_proportional_millionths: 0,
3662                         excess_data: Vec::new()
3663                 });
3664
3665                 // Path via {node0, node2} is channels {1, 3, 5}.
3666                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3667                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3668                         short_channel_id: 1,
3669                         timestamp: 2,
3670                         flags: 0,
3671                         cltv_expiry_delta: 0,
3672                         htlc_minimum_msat: 0,
3673                         htlc_maximum_msat: OptionalField::Present(100_000),
3674                         fee_base_msat: 0,
3675                         fee_proportional_millionths: 0,
3676                         excess_data: Vec::new()
3677                 });
3678                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3679                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3680                         short_channel_id: 3,
3681                         timestamp: 2,
3682                         flags: 0,
3683                         cltv_expiry_delta: 0,
3684                         htlc_minimum_msat: 0,
3685                         htlc_maximum_msat: OptionalField::Present(100_000),
3686                         fee_base_msat: 0,
3687                         fee_proportional_millionths: 0,
3688                         excess_data: Vec::new()
3689                 });
3690
3691                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3692                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3693                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3694                         short_channel_id: 5,
3695                         timestamp: 2,
3696                         flags: 0,
3697                         cltv_expiry_delta: 0,
3698                         htlc_minimum_msat: 0,
3699                         htlc_maximum_msat: OptionalField::Present(100_000),
3700                         fee_base_msat: 0,
3701                         fee_proportional_millionths: 0,
3702                         excess_data: Vec::new()
3703                 });
3704
3705                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3706                 // All channels should be 100 sats capacity. But for the fee experiment,
3707                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3708                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3709                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3710                 // so no matter how large are other channels,
3711                 // the whole path will be limited by 100 sats with just these 2 conditions:
3712                 // - channel 12 capacity is 250 sats
3713                 // - fee for channel 6 is 150 sats
3714                 // Let's test this by enforcing these 2 conditions and removing other limits.
3715                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3716                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3717                         short_channel_id: 12,
3718                         timestamp: 2,
3719                         flags: 0,
3720                         cltv_expiry_delta: 0,
3721                         htlc_minimum_msat: 0,
3722                         htlc_maximum_msat: OptionalField::Present(250_000),
3723                         fee_base_msat: 0,
3724                         fee_proportional_millionths: 0,
3725                         excess_data: Vec::new()
3726                 });
3727                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3728                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3729                         short_channel_id: 13,
3730                         timestamp: 2,
3731                         flags: 0,
3732                         cltv_expiry_delta: 0,
3733                         htlc_minimum_msat: 0,
3734                         htlc_maximum_msat: OptionalField::Absent,
3735                         fee_base_msat: 0,
3736                         fee_proportional_millionths: 0,
3737                         excess_data: Vec::new()
3738                 });
3739
3740                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3741                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3742                         short_channel_id: 6,
3743                         timestamp: 2,
3744                         flags: 0,
3745                         cltv_expiry_delta: 0,
3746                         htlc_minimum_msat: 0,
3747                         htlc_maximum_msat: OptionalField::Absent,
3748                         fee_base_msat: 150_000,
3749                         fee_proportional_millionths: 0,
3750                         excess_data: Vec::new()
3751                 });
3752                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3753                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3754                         short_channel_id: 11,
3755                         timestamp: 2,
3756                         flags: 0,
3757                         cltv_expiry_delta: 0,
3758                         htlc_minimum_msat: 0,
3759                         htlc_maximum_msat: OptionalField::Absent,
3760                         fee_base_msat: 0,
3761                         fee_proportional_millionths: 0,
3762                         excess_data: Vec::new()
3763                 });
3764
3765                 {
3766                         // Attempt to route more than available results in a failure.
3767                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3768                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3769                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3770                         } else { panic!(); }
3771                 }
3772
3773                 {
3774                         // Now, attempt to route 200 sats (exact amount we can route).
3775                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3776                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3777                         assert_eq!(route.paths.len(), 2);
3778
3779                         let mut total_amount_paid_msat = 0;
3780                         for path in &route.paths {
3781                                 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3782                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3783                         }
3784                         assert_eq!(total_amount_paid_msat, 200_000);
3785                 }
3786
3787         }
3788
3789         #[test]
3790         fn drop_lowest_channel_mpp_route_test() {
3791                 // This test checks that low-capacity channel is dropped when after
3792                 // path finding we realize that we found more capacity than we need.
3793                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3794                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3795
3796                 // We need a route consisting of 3 paths:
3797                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3798
3799                 // The first and the second paths should be sufficient, but the third should be
3800                 // cheaper, so that we select it but drop later.
3801
3802                 // First, we set limits on these (previously unlimited) channels.
3803                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3804
3805                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3806                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3807                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3808                         short_channel_id: 1,
3809                         timestamp: 2,
3810                         flags: 0,
3811                         cltv_expiry_delta: 0,
3812                         htlc_minimum_msat: 0,
3813                         htlc_maximum_msat: OptionalField::Present(100_000),
3814                         fee_base_msat: 0,
3815                         fee_proportional_millionths: 0,
3816                         excess_data: Vec::new()
3817                 });
3818                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3819                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3820                         short_channel_id: 3,
3821                         timestamp: 2,
3822                         flags: 0,
3823                         cltv_expiry_delta: 0,
3824                         htlc_minimum_msat: 0,
3825                         htlc_maximum_msat: OptionalField::Present(50_000),
3826                         fee_base_msat: 100,
3827                         fee_proportional_millionths: 0,
3828                         excess_data: Vec::new()
3829                 });
3830
3831                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3832                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3833                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3834                         short_channel_id: 12,
3835                         timestamp: 2,
3836                         flags: 0,
3837                         cltv_expiry_delta: 0,
3838                         htlc_minimum_msat: 0,
3839                         htlc_maximum_msat: OptionalField::Present(60_000),
3840                         fee_base_msat: 100,
3841                         fee_proportional_millionths: 0,
3842                         excess_data: Vec::new()
3843                 });
3844                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3845                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3846                         short_channel_id: 13,
3847                         timestamp: 2,
3848                         flags: 0,
3849                         cltv_expiry_delta: 0,
3850                         htlc_minimum_msat: 0,
3851                         htlc_maximum_msat: OptionalField::Present(60_000),
3852                         fee_base_msat: 0,
3853                         fee_proportional_millionths: 0,
3854                         excess_data: Vec::new()
3855                 });
3856
3857                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3858                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3859                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3860                         short_channel_id: 2,
3861                         timestamp: 2,
3862                         flags: 0,
3863                         cltv_expiry_delta: 0,
3864                         htlc_minimum_msat: 0,
3865                         htlc_maximum_msat: OptionalField::Present(20_000),
3866                         fee_base_msat: 0,
3867                         fee_proportional_millionths: 0,
3868                         excess_data: Vec::new()
3869                 });
3870                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3871                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3872                         short_channel_id: 4,
3873                         timestamp: 2,
3874                         flags: 0,
3875                         cltv_expiry_delta: 0,
3876                         htlc_minimum_msat: 0,
3877                         htlc_maximum_msat: OptionalField::Present(20_000),
3878                         fee_base_msat: 0,
3879                         fee_proportional_millionths: 0,
3880                         excess_data: Vec::new()
3881                 });
3882
3883                 {
3884                         // Attempt to route more than available results in a failure.
3885                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3886                                         Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3887                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3888                         } else { panic!(); }
3889                 }
3890
3891                 {
3892                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3893                         // Our algorithm should provide us with these 3 paths.
3894                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3895                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3896                         assert_eq!(route.paths.len(), 3);
3897                         let mut total_amount_paid_msat = 0;
3898                         for path in &route.paths {
3899                                 assert_eq!(path.len(), 2);
3900                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3901                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3902                         }
3903                         assert_eq!(total_amount_paid_msat, 125_000);
3904                 }
3905
3906                 {
3907                         // Attempt to route without the last small cheap channel
3908                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3909                                 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3910                         assert_eq!(route.paths.len(), 2);
3911                         let mut total_amount_paid_msat = 0;
3912                         for path in &route.paths {
3913                                 assert_eq!(path.len(), 2);
3914                                 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3915                                 total_amount_paid_msat += path.last().unwrap().fee_msat;
3916                         }
3917                         assert_eq!(total_amount_paid_msat, 90_000);
3918                 }
3919         }
3920
3921         #[test]
3922         fn min_criteria_consistency() {
3923                 // Test that we don't use an inconsistent metric between updating and walking nodes during
3924                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3925                 // was updated with a different criterion from the heap sorting, resulting in loops in
3926                 // calculated paths. We test for that specific case here.
3927
3928                 // We construct a network that looks like this:
3929                 //
3930                 //            node2 -1(3)2- node3
3931                 //              2          2
3932                 //               (2)     (4)
3933                 //                  1   1
3934                 //    node1 -1(5)2- node4 -1(1)2- node6
3935                 //    2
3936                 //   (6)
3937                 //        1
3938                 // our_node
3939                 //
3940                 // We create a loop on the side of our real path - our destination is node 6, with a
3941                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3942                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3943                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3944                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3945                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3946                 // "previous hop" being set to node 3, creating a loop in the path.
3947                 let secp_ctx = Secp256k1::new();
3948                 let logger = Arc::new(test_utils::TestLogger::new());
3949                 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3950                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3951
3952                 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3953                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3954                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3955                         short_channel_id: 6,
3956                         timestamp: 1,
3957                         flags: 0,
3958                         cltv_expiry_delta: (6 << 8) | 0,
3959                         htlc_minimum_msat: 0,
3960                         htlc_maximum_msat: OptionalField::Absent,
3961                         fee_base_msat: 0,
3962                         fee_proportional_millionths: 0,
3963                         excess_data: Vec::new()
3964                 });
3965                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3966
3967                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3968                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3969                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3970                         short_channel_id: 5,
3971                         timestamp: 1,
3972                         flags: 0,
3973                         cltv_expiry_delta: (5 << 8) | 0,
3974                         htlc_minimum_msat: 0,
3975                         htlc_maximum_msat: OptionalField::Absent,
3976                         fee_base_msat: 100,
3977                         fee_proportional_millionths: 0,
3978                         excess_data: Vec::new()
3979                 });
3980                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3981
3982                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3983                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3984                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3985                         short_channel_id: 4,
3986                         timestamp: 1,
3987                         flags: 0,
3988                         cltv_expiry_delta: (4 << 8) | 0,
3989                         htlc_minimum_msat: 0,
3990                         htlc_maximum_msat: OptionalField::Absent,
3991                         fee_base_msat: 0,
3992                         fee_proportional_millionths: 0,
3993                         excess_data: Vec::new()
3994                 });
3995                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3996
3997                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3998                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3999                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4000                         short_channel_id: 3,
4001                         timestamp: 1,
4002                         flags: 0,
4003                         cltv_expiry_delta: (3 << 8) | 0,
4004                         htlc_minimum_msat: 0,
4005                         htlc_maximum_msat: OptionalField::Absent,
4006                         fee_base_msat: 0,
4007                         fee_proportional_millionths: 0,
4008                         excess_data: Vec::new()
4009                 });
4010                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4011
4012                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4013                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4014                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4015                         short_channel_id: 2,
4016                         timestamp: 1,
4017                         flags: 0,
4018                         cltv_expiry_delta: (2 << 8) | 0,
4019                         htlc_minimum_msat: 0,
4020                         htlc_maximum_msat: OptionalField::Absent,
4021                         fee_base_msat: 0,
4022                         fee_proportional_millionths: 0,
4023                         excess_data: Vec::new()
4024                 });
4025
4026                 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4027                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4028                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4029                         short_channel_id: 1,
4030                         timestamp: 1,
4031                         flags: 0,
4032                         cltv_expiry_delta: (1 << 8) | 0,
4033                         htlc_minimum_msat: 100,
4034                         htlc_maximum_msat: OptionalField::Absent,
4035                         fee_base_msat: 0,
4036                         fee_proportional_millionths: 0,
4037                         excess_data: Vec::new()
4038                 });
4039                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4040
4041                 {
4042                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
4043                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
4044                         assert_eq!(route.paths.len(), 1);
4045                         assert_eq!(route.paths[0].len(), 3);
4046
4047                         assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4048                         assert_eq!(route.paths[0][0].short_channel_id, 6);
4049                         assert_eq!(route.paths[0][0].fee_msat, 100);
4050                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4051                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4052                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4053
4054                         assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4055                         assert_eq!(route.paths[0][1].short_channel_id, 5);
4056                         assert_eq!(route.paths[0][1].fee_msat, 0);
4057                         assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4058                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4059                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4060
4061                         assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4062                         assert_eq!(route.paths[0][2].short_channel_id, 1);
4063                         assert_eq!(route.paths[0][2].fee_msat, 10_000);
4064                         assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4065                         assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4066                         assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4067                 }
4068         }
4069
4070
4071         #[test]
4072         fn exact_fee_liquidity_limit() {
4073                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4074                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4075                 // we calculated fees on a higher value, resulting in us ignoring such paths.
4076                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4077                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4078
4079                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4080                 // send.
4081                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4082                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4083                         short_channel_id: 2,
4084                         timestamp: 2,
4085                         flags: 0,
4086                         cltv_expiry_delta: 0,
4087                         htlc_minimum_msat: 0,
4088                         htlc_maximum_msat: OptionalField::Present(85_000),
4089                         fee_base_msat: 0,
4090                         fee_proportional_millionths: 0,
4091                         excess_data: Vec::new()
4092                 });
4093
4094                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4095                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4096                         short_channel_id: 12,
4097                         timestamp: 2,
4098                         flags: 0,
4099                         cltv_expiry_delta: (4 << 8) | 1,
4100                         htlc_minimum_msat: 0,
4101                         htlc_maximum_msat: OptionalField::Present(270_000),
4102                         fee_base_msat: 0,
4103                         fee_proportional_millionths: 1000000,
4104                         excess_data: Vec::new()
4105                 });
4106
4107                 {
4108                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4109                         // 200% fee charged channel 13 in the 1-to-2 direction.
4110                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
4111                         assert_eq!(route.paths.len(), 1);
4112                         assert_eq!(route.paths[0].len(), 2);
4113
4114                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4115                         assert_eq!(route.paths[0][0].short_channel_id, 12);
4116                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4117                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4118                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4119                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4120
4121                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4122                         assert_eq!(route.paths[0][1].short_channel_id, 13);
4123                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
4124                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4125                         assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4126                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4127                 }
4128         }
4129
4130         #[test]
4131         fn htlc_max_reduction_below_min() {
4132                 // Test that if, while walking the graph, we reduce the value being sent to meet an
4133                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4134                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4135                 // resulting in us thinking there is no possible path, even if other paths exist.
4136                 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
4137                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4138
4139                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4140                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4141                 // then try to send 90_000.
4142                 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4143                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4144                         short_channel_id: 2,
4145                         timestamp: 2,
4146                         flags: 0,
4147                         cltv_expiry_delta: 0,
4148                         htlc_minimum_msat: 0,
4149                         htlc_maximum_msat: OptionalField::Present(80_000),
4150                         fee_base_msat: 0,
4151                         fee_proportional_millionths: 0,
4152                         excess_data: Vec::new()
4153                 });
4154                 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4155                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4156                         short_channel_id: 4,
4157                         timestamp: 2,
4158                         flags: 0,
4159                         cltv_expiry_delta: (4 << 8) | 1,
4160                         htlc_minimum_msat: 90_000,
4161                         htlc_maximum_msat: OptionalField::Absent,
4162                         fee_base_msat: 0,
4163                         fee_proportional_millionths: 0,
4164                         excess_data: Vec::new()
4165                 });
4166
4167                 {
4168                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4169                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4170                         // expensive) channels 12-13 path.
4171                         let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
4172                         assert_eq!(route.paths.len(), 1);
4173                         assert_eq!(route.paths[0].len(), 2);
4174
4175                         assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4176                         assert_eq!(route.paths[0][0].short_channel_id, 12);
4177                         assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4178                         assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4179                         assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4180                         assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4181
4182                         assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4183                         assert_eq!(route.paths[0][1].short_channel_id, 13);
4184                         assert_eq!(route.paths[0][1].fee_msat, 90_000);
4185                         assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4186                         assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4187                         assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4188                 }
4189         }
4190
4191         #[cfg(not(feature = "no-std"))]
4192         pub(super) fn random_init_seed() -> u64 {
4193                 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4194                 use core::hash::{BuildHasher, Hasher};
4195                 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4196                 println!("Using seed of {}", seed);
4197                 seed
4198         }
4199         #[cfg(not(feature = "no-std"))]
4200         use util::ser::Readable;
4201
4202         #[test]
4203         #[cfg(not(feature = "no-std"))]
4204         fn generate_routes() {
4205                 let mut d = match super::test_utils::get_route_file() {
4206                         Ok(f) => f,
4207                         Err(e) => {
4208                                 eprintln!("{}", e);
4209                                 return;
4210                         },
4211                 };
4212                 let graph = NetworkGraph::read(&mut d).unwrap();
4213
4214                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4215                 let mut seed = random_init_seed() as usize;
4216                 let nodes = graph.get_nodes();
4217                 'load_endpoints: for _ in 0..10 {
4218                         loop {
4219                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4220                                 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4221                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4222                                 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4223                                 let amt = seed as u64 % 200_000_000;
4224                                 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4225                                         continue 'load_endpoints;
4226                                 }
4227                         }
4228                 }
4229         }
4230
4231         #[test]
4232         #[cfg(not(feature = "no-std"))]
4233         fn generate_routes_mpp() {
4234                 let mut d = match super::test_utils::get_route_file() {
4235                         Ok(f) => f,
4236                         Err(e) => {
4237                                 eprintln!("{}", e);
4238                                 return;
4239                         },
4240                 };
4241                 let graph = NetworkGraph::read(&mut d).unwrap();
4242
4243                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4244                 let mut seed = random_init_seed() as usize;
4245                 let nodes = graph.get_nodes();
4246                 'load_endpoints: for _ in 0..10 {
4247                         loop {
4248                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4249                                 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4250                                 seed = seed.overflowing_mul(0xdeadbeef).0;
4251                                 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4252                                 let amt = seed as u64 % 200_000_000;
4253                                 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
4254                                         continue 'load_endpoints;
4255                                 }
4256                         }
4257                 }
4258         }
4259 }
4260
4261 #[cfg(all(test, not(feature = "no-std")))]
4262 pub(crate) mod test_utils {
4263         use std::fs::File;
4264         /// Tries to open a network graph file, or panics with a URL to fetch it.
4265         pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4266                 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4267                         .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4268                         .or_else(|_| { // Fall back to guessing based on the binary location
4269                                 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4270                                 let mut path = std::env::current_exe().unwrap();
4271                                 path.pop(); // lightning-...
4272                                 path.pop(); // deps
4273                                 path.pop(); // debug
4274                                 path.pop(); // target
4275                                 path.push("lightning");
4276                                 path.push("net_graph-2021-05-31.bin");
4277                                 eprintln!("{}", path.to_str().unwrap());
4278                                 File::open(path)
4279                         })
4280                 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.15-2021-05-31.bin and place it at lightning/net_graph-2021-05-31.bin");
4281                 #[cfg(require_route_graph_test)]
4282                 return Ok(res.unwrap());
4283                 #[cfg(not(require_route_graph_test))]
4284                 return res;
4285         }
4286 }
4287
4288 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4289 mod benches {
4290         use super::*;
4291         use util::logger::{Logger, Record};
4292
4293         use test::Bencher;
4294
4295         struct DummyLogger {}
4296         impl Logger for DummyLogger {
4297                 fn log(&self, _record: &Record) {}
4298         }
4299
4300         #[bench]
4301         fn generate_routes(bench: &mut Bencher) {
4302                 let mut d = test_utils::get_route_file().unwrap();
4303                 let graph = NetworkGraph::read(&mut d).unwrap();
4304                 let nodes = graph.get_nodes();
4305
4306                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4307                 let mut path_endpoints = Vec::new();
4308                 let mut seed: usize = 0xdeadbeef;
4309                 'load_endpoints: for _ in 0..100 {
4310                         loop {
4311                                 seed *= 0xdeadbeef;
4312                                 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4313                                 seed *= 0xdeadbeef;
4314                                 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4315                                 let amt = seed as u64 % 1_000_000;
4316                                 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
4317                                         path_endpoints.push((src, dst, amt));
4318                                         continue 'load_endpoints;
4319                                 }
4320                         }
4321                 }
4322
4323                 // ...then benchmark finding paths between the nodes we learned.
4324                 let mut idx = 0;
4325                 bench.iter(|| {
4326                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4327                         assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
4328                         idx += 1;
4329                 });
4330         }
4331
4332         #[bench]
4333         fn generate_mpp_routes(bench: &mut Bencher) {
4334                 let mut d = test_utils::get_route_file().unwrap();
4335                 let graph = NetworkGraph::read(&mut d).unwrap();
4336                 let nodes = graph.get_nodes();
4337
4338                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4339                 let mut path_endpoints = Vec::new();
4340                 let mut seed: usize = 0xdeadbeef;
4341                 'load_endpoints: for _ in 0..100 {
4342                         loop {
4343                                 seed *= 0xdeadbeef;
4344                                 let src = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4345                                 seed *= 0xdeadbeef;
4346                                 let dst = nodes.keys().skip(seed % nodes.len()).next().unwrap();
4347                                 let amt = seed as u64 % 1_000_000;
4348                                 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4349                                         path_endpoints.push((src, dst, amt));
4350                                         continue 'load_endpoints;
4351                                 }
4352                         }
4353                 }
4354
4355                 // ...then benchmark finding paths between the nodes we learned.
4356                 let mut idx = 0;
4357                 bench.iter(|| {
4358                         let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4359                         assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());
4360                         idx += 1;
4361                 });
4362         }
4363 }