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