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