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