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