1 // This file is Copyright its original authors, visible in version control
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
10 //! The top-level routing/network map tracking logic lives here.
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.
15 use bitcoin::secp256k1::key::PublicKey;
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;
25 use alloc::collections::BinaryHeap;
27 use std::collections::HashMap;
31 #[derive(Clone, PartialEq)]
33 /// The node_id of the node at this hop.
34 pub pubkey: PublicKey,
35 /// The node_announcement features of the node at this hop. For the last hop, these may be
36 /// amended to match the features present in the invoice this node generated.
37 pub node_features: NodeFeatures,
38 /// The channel that should be used from the previous hop to reach this node.
39 pub short_channel_id: u64,
40 /// The channel_announcement features of the channel that should be used from the previous hop
41 /// to reach this node.
42 pub channel_features: ChannelFeatures,
43 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
44 /// For the last hop, this should be the full value of the payment (might be more than
45 /// requested if we had to match htlc_minimum_msat).
47 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
48 /// expected at the destination, in excess of the current block height.
49 pub cltv_expiry_delta: u32,
52 impl_writeable_tlv_based!(RouteHop, {
55 (4, short_channel_id),
56 (6, channel_features),
58 (10, cltv_expiry_delta),
61 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
62 /// it can take multiple paths. Each path is composed of one or more hops through the network.
63 #[derive(Clone, PartialEq)]
65 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
66 /// last RouteHop in each path must be the same.
67 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
68 /// destination. Thus, this must always be at least length one. While the maximum length of any
69 /// given path is variable, keeping the length of any path to less than 20 should currently
70 /// ensure it is viable.
71 pub paths: Vec<Vec<RouteHop>>,
74 const SERIALIZATION_VERSION: u8 = 1;
75 const MIN_SERIALIZATION_VERSION: u8 = 1;
77 impl Writeable for Route {
78 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
79 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
80 (self.paths.len() as u64).write(writer)?;
81 for hops in self.paths.iter() {
82 (hops.len() as u8).write(writer)?;
83 for hop in hops.iter() {
87 write_tlv_fields!(writer, {}, {});
92 impl Readable for Route {
93 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
94 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
95 let path_count: u64 = Readable::read(reader)?;
96 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
97 for _ in 0..path_count {
98 let hop_count: u8 = Readable::read(reader)?;
99 let mut hops = Vec::with_capacity(hop_count as usize);
100 for _ in 0..hop_count {
101 hops.push(Readable::read(reader)?);
105 read_tlv_fields!(reader, {}, {});
110 /// A list of hops along a payment path terminating with a channel to the recipient.
111 #[derive(Eq, PartialEq, Debug, Clone)]
112 pub struct RouteHint(pub Vec<RouteHintHop>);
114 /// A channel descriptor for a hop along a payment path.
115 #[derive(Eq, PartialEq, Debug, Clone)]
116 pub struct RouteHintHop {
117 /// The node_id of the non-target end of the route
118 pub src_node_id: PublicKey,
119 /// The short_channel_id of this channel
120 pub short_channel_id: u64,
121 /// The fees which must be paid to use this channel
122 pub fees: RoutingFees,
123 /// The difference in CLTV values between this node and the next node.
124 pub cltv_expiry_delta: u16,
125 /// The minimum value, in msat, which must be relayed to the next hop.
126 pub htlc_minimum_msat: Option<u64>,
127 /// The maximum value in msat available for routing with a single HTLC.
128 pub htlc_maximum_msat: Option<u64>,
131 #[derive(Eq, PartialEq)]
132 struct RouteGraphNode {
134 lowest_fee_to_peer_through_node: u64,
135 lowest_fee_to_node: u64,
136 // The maximum value a yet-to-be-constructed payment path might flow through this node.
137 // This value is upper-bounded by us by:
138 // - how much is needed for a path being constructed
139 // - how much value can channels following this node (up to the destination) can contribute,
140 // considering their capacity and fees
141 value_contribution_msat: u64,
142 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
143 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
144 path_htlc_minimum_msat: u64,
147 impl cmp::Ord for RouteGraphNode {
148 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
149 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
150 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
151 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
155 impl cmp::PartialOrd for RouteGraphNode {
156 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
157 Some(self.cmp(other))
161 struct DummyDirectionalChannelInfo {
162 cltv_expiry_delta: u32,
163 htlc_minimum_msat: u64,
164 htlc_maximum_msat: Option<u64>,
168 /// It's useful to keep track of the hops associated with the fees required to use them,
169 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
170 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
171 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
173 struct PathBuildingHop<'a> {
174 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
175 // Note that node_features is calculated separately after our initial graph walk.
177 short_channel_id: u64,
178 channel_features: &'a ChannelFeatures,
180 cltv_expiry_delta: u32,
182 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
183 src_lowest_inbound_fees: RoutingFees,
184 /// Fees of the channel used in this hop.
185 channel_fees: RoutingFees,
186 /// All the fees paid *after* this channel on the way to the destination
187 next_hops_fee_msat: u64,
188 /// Fee paid for the use of the current channel (see channel_fees).
189 /// The value will be actually deducted from the counterparty balance on the previous link.
190 hop_use_fee_msat: u64,
191 /// Used to compare channels when choosing the for routing.
192 /// Includes paying for the use of a hop and the following hops, as well as
193 /// an estimated cost of reaching this hop.
194 /// Might get stale when fees are recomputed. Primarily for internal use.
196 /// This is useful for update_value_and_recompute_fees to make sure
197 /// we don't fall below the minimum. Should not be updated manually and
198 /// generally should not be accessed.
199 htlc_minimum_msat: u64,
200 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
201 /// walk and may be invalid thereafter.
202 path_htlc_minimum_msat: u64,
203 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
204 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
205 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
206 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
207 /// avoid processing them again.
209 #[cfg(any(test, feature = "fuzztarget"))]
210 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
211 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
212 // value_contribution_msat, which requires tracking it here. See comments below where it is
213 // used for more info.
214 value_contribution_msat: u64,
217 // Instantiated with a list of hops with correct data in them collected during path finding,
218 // an instance of this struct should be further modified only via given methods.
220 struct PaymentPath<'a> {
221 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
224 impl<'a> PaymentPath<'a> {
225 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
226 fn get_value_msat(&self) -> u64 {
227 self.hops.last().unwrap().0.fee_msat
230 fn get_total_fee_paid_msat(&self) -> u64 {
231 if self.hops.len() < 1 {
235 // Can't use next_hops_fee_msat because it gets outdated.
236 for (i, (hop, _)) in self.hops.iter().enumerate() {
237 if i != self.hops.len() - 1 {
238 result += hop.fee_msat;
244 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
245 // to change fees may result in an inconsistency.
247 // Sometimes we call this function right after constructing a path which is inconsistent in
248 // that it the value being transferred has decreased while we were doing path finding, leading
249 // to the fees being paid not lining up with the actual limits.
251 // Note that this function is not aware of the available_liquidity limit, and thus does not
252 // support increasing the value being transferred.
253 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
254 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
256 let mut total_fee_paid_msat = 0 as u64;
257 for i in (0..self.hops.len()).rev() {
258 let last_hop = i == self.hops.len() - 1;
260 // For non-last-hop, this value will represent the fees paid on the current hop. It
261 // will consist of the fees for the use of the next hop, and extra fees to match
262 // htlc_minimum_msat of the current channel. Last hop is handled separately.
263 let mut cur_hop_fees_msat = 0;
265 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
268 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
269 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
270 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
271 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
272 // set it too high just to maliciously take more fees by exploiting this
273 // match htlc_minimum_msat logic.
274 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
275 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
276 // Note that there is a risk that *previous hops* (those closer to us, as we go
277 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
279 // This might make us end up with a broken route, although this should be super-rare
280 // in practice, both because of how healthy channels look like, and how we pick
281 // channels in add_entry.
282 // Also, this can't be exploited more heavily than *announce a free path and fail
284 cur_hop_transferred_amount_msat += extra_fees_msat;
285 total_fee_paid_msat += extra_fees_msat;
286 cur_hop_fees_msat += extra_fees_msat;
290 // Final hop is a special case: it usually has just value_msat (by design), but also
291 // it still could overpay for the htlc_minimum_msat.
292 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
294 // Propagate updated fees for the use of the channels to one hop back, where they
295 // will be actually paid (fee_msat). The last hop is handled above separately.
296 cur_hop.fee_msat = cur_hop_fees_msat;
299 // Fee for the use of the current hop which will be deducted on the previous hop.
300 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
301 // this channel is free for us.
303 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
304 cur_hop.hop_use_fee_msat = new_fee;
305 total_fee_paid_msat += new_fee;
307 // It should not be possible because this function is called only to reduce the
308 // value. In that case, compute_fee was already called with the same fees for
309 // larger amount and there was no overflow.
317 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
318 let proportional_fee_millions =
319 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
320 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
321 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
325 // This function may be (indirectly) called without any verification,
326 // with channel_fees provided by a caller. We should handle it gracefully.
331 /// Gets a route from us (payer) to the given target node (payee).
333 /// If the payee provided features in their invoice, they should be provided via payee_features.
334 /// Without this, MPP will only be used if the payee's features are available in the network graph.
336 /// Private routing paths between a public node and the target may be included in `last_hops`.
337 /// Currently, only the last hop in each path is considered.
339 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
340 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
341 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
342 /// in first_hops will be used.
344 /// Panics if first_hops contains channels without short_channel_ids
345 /// (ChannelManager::list_usable_channels will never include such channels).
347 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
348 /// equal), however the enabled/disabled bit on such channels as well as the
349 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
350 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
351 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
352 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
353 // uptime/success in using a node in the past.
354 if *payee == *our_node_id {
355 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
358 if final_value_msat > MAX_VALUE_MSAT {
359 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
362 if final_value_msat == 0 {
363 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
366 let last_hops = last_hops.iter().filter_map(|hops| hops.0.last()).collect::<Vec<_>>();
367 for last_hop in last_hops.iter() {
368 if last_hop.src_node_id == *payee {
369 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
373 // The general routing idea is the following:
374 // 1. Fill first/last hops communicated by the caller.
375 // 2. Attempt to construct a path from payer to payee for transferring
376 // any ~sufficient (described later) value.
377 // If succeed, remember which channels were used and how much liquidity they have available,
378 // so that future paths don't rely on the same liquidity.
379 // 3. Prooceed to the next step if:
380 // - we hit the recommended target value;
381 // - OR if we could not construct a new path. Any next attempt will fail too.
382 // Otherwise, repeat step 2.
383 // 4. See if we managed to collect paths which aggregately are able to transfer target value
384 // (not recommended value). If yes, proceed. If not, fail routing.
385 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
386 // 6. Of all the found paths, select only those with the lowest total fee.
387 // 7. The last path in every selected route is likely to be more than we need.
388 // Reduce its value-to-transfer and recompute fees.
389 // 8. Choose the best route by the lowest total fee.
391 // As for the actual search algorithm,
392 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
393 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
395 // We are not a faithful Dijkstra's implementation because we can change values which impact
396 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
397 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
398 // the value we are currently attempting to send over a path, we simply reduce the value being
399 // sent along the path for any hops after that channel. This may imply that later fees (which
400 // we've already tabulated) are lower because a smaller value is passing through the channels
401 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
402 // channels which were selected earlier (and which may still be used for other paths without a
403 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
406 // One potentially problematic case for this algorithm would be if there are many
407 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
408 // graph walking), we may never find a path which is not liquidity-limited and has lower
409 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
410 // Because we only consider paths with at least 5% of the total value being sent, the damage
411 // from such a case should be limited, however this could be further reduced in the future by
412 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
413 // limits for the purposes of fee calculation.
415 // Alternatively, we could store more detailed path information in the heap (targets, below)
416 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
417 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
418 // and practically (as we would need to store dynamically-allocated path information in heap
419 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
420 // results of such an algorithm would likely be biased towards lower-value paths.
422 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
423 // outside of our current search value, running a path search more times to gather candidate
424 // paths at different values. While this may be acceptable, further path searches may increase
425 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
426 // graph for candidate paths, calculating the maximum value which can realistically be sent at
427 // the same time, remaining generic across different payment values.
429 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
430 // to use as the A* heuristic beyond just the cost to get one node further than the current
433 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
434 cltv_expiry_delta: 0,
435 htlc_minimum_msat: 0,
436 htlc_maximum_msat: None,
439 proportional_millionths: 0,
443 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
444 // it. If the payee supports it they're supposed to include it in the invoice, so that should
446 let allow_mpp = if let Some(features) = &payee_features {
447 features.supports_basic_mpp()
448 } else if let Some(node) = network.get_nodes().get(&payee) {
449 if let Some(node_info) = node.announcement_info.as_ref() {
450 node_info.features.supports_basic_mpp()
455 // Prepare the data we'll use for payee-to-payer search by
456 // inserting first hops suggested by the caller as targets.
457 // Our search will then attempt to reach them while traversing from the payee node.
458 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
459 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
460 if let Some(hops) = first_hops {
462 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
463 if chan.remote_network_id == *our_node_id {
464 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
466 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()));
468 if first_hop_targets.is_empty() {
469 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
473 let empty_channel_features = ChannelFeatures::empty();
475 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
476 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
477 // adding duplicate entries when we find a better path to a given node.
478 let mut targets = BinaryHeap::new();
480 // Map from node_id to information about the best current path to that node, including feerate
482 let mut dist = HashMap::with_capacity(network.get_nodes().len());
484 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
485 // indicating that we may wish to try again with a higher value, potentially paying to meet an
486 // htlc_minimum with extra fees while still finding a cheaper path.
487 let mut hit_minimum_limit;
489 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
490 // We start with a path_value of the exact amount we want, and if that generates a route we may
491 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
492 // amount we want in total across paths, selecting the best subset at the end.
493 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
494 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
495 let mut path_value_msat = final_value_msat;
497 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
498 // This map allows paths to be aware of the channel use by other paths in the same call.
499 // This would help to make a better path finding decisions and not "overbook" channels.
500 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
501 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
503 // Keeping track of how much value we already collected across other paths. Helps to decide:
504 // - how much a new path should be transferring (upper bound);
505 // - whether a channel should be disregarded because
506 // it's available liquidity is too small comparing to how much more we need to collect;
507 // - when we want to stop looking for new paths.
508 let mut already_collected_value_msat = 0;
510 macro_rules! add_entry {
511 // Adds entry which goes from $src_node_id to $dest_node_id
512 // over the channel with id $chan_id with fees described in
513 // $directional_info.
514 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
515 // since that value has to be transferred over this channel.
516 // Returns whether this channel caused an update to `targets`.
517 ( $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,
518 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => { {
519 // We "return" whether we updated the path at the end, via this:
520 let mut did_add_update_path_to_src_node = false;
521 // Channels to self should not be used. This is more of belt-and-suspenders, because in
522 // practice these cases should be caught earlier:
523 // - for regular channels at channel announcement (TODO)
524 // - for first and last hops early in get_route
525 if $src_node_id != $dest_node_id.clone() {
526 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
527 let mut initial_liquidity_available_msat = None;
528 if let Some(capacity_sats) = $capacity_sats {
529 initial_liquidity_available_msat = Some(capacity_sats * 1000);
532 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
533 if let Some(available_msat) = initial_liquidity_available_msat {
534 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
536 initial_liquidity_available_msat = Some(htlc_maximum_msat);
540 match initial_liquidity_available_msat {
541 Some(available_msat) => available_msat,
542 // We assume channels with unknown balance have
543 // a capacity of 0.0025 BTC (or 250_000 sats).
544 None => 250_000 * 1000
548 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
549 // It may be misleading because we might later choose to reduce the value transferred
550 // over these channels, and the channel which was insufficient might become sufficient.
551 // Worst case: we drop a good channel here because it can't cover the high following
552 // fees caused by one expensive channel, but then this channel could have been used
553 // if the amount being transferred over this path is lower.
554 // We do this for now, but this is a subject for removal.
555 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
557 // Routing Fragmentation Mitigation heuristic:
559 // Routing fragmentation across many payment paths increases the overall routing
560 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
561 // Taking too many smaller paths also increases the chance of payment failure.
562 // Thus to avoid this effect, we require from our collected links to provide
563 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
565 // This requirement is currently 5% of the remaining-to-be-collected value.
566 // This means as we successfully advance in our collection,
567 // the absolute liquidity contribution is lowered,
568 // thus increasing the number of potential channels to be selected.
570 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
571 // or 100% if we're not allowed to do multipath payments.
572 let minimal_value_contribution_msat: u64 = if allow_mpp {
573 (recommended_value_msat - already_collected_value_msat + 19) / 20
577 // Verify the liquidity offered by this channel complies to the minimal contribution.
578 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
580 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
581 // Includes paying fees for the use of the following channels.
582 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
583 Some(result) => result,
584 // Can't overflow due to how the values were computed right above.
585 None => unreachable!(),
587 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
588 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
589 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
591 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
592 // bother considering this channel.
593 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
594 // be only reduced later (not increased), so this channel should just be skipped
595 // as not sufficient.
596 if !over_path_minimum_msat {
597 hit_minimum_limit = true;
598 } else if contributes_sufficient_value {
599 // Note that low contribution here (limited by available_liquidity_msat)
600 // might violate htlc_minimum_msat on the hops which are next along the
601 // payment path (upstream to the payee). To avoid that, we recompute path
602 // path fees knowing the final path contribution after constructing it.
603 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
604 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
605 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
606 _ => u64::max_value()
608 let hm_entry = dist.entry(&$src_node_id);
609 let old_entry = hm_entry.or_insert_with(|| {
610 // If there was previously no known way to access
611 // the source node (recall it goes payee-to-payer) of $chan_id, first add
612 // a semi-dummy record just to compute the fees to reach the source node.
613 // This will affect our decision on selecting $chan_id
614 // as a way to reach the $dest_node_id.
615 let mut fee_base_msat = u32::max_value();
616 let mut fee_proportional_millionths = u32::max_value();
617 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
618 fee_base_msat = fees.base_msat;
619 fee_proportional_millionths = fees.proportional_millionths;
622 pubkey: $dest_node_id.clone(),
624 channel_features: $chan_features,
626 cltv_expiry_delta: 0,
627 src_lowest_inbound_fees: RoutingFees {
628 base_msat: fee_base_msat,
629 proportional_millionths: fee_proportional_millionths,
631 channel_fees: $directional_info.fees,
632 next_hops_fee_msat: u64::max_value(),
633 hop_use_fee_msat: u64::max_value(),
634 total_fee_msat: u64::max_value(),
635 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
636 path_htlc_minimum_msat,
637 was_processed: false,
638 #[cfg(any(test, feature = "fuzztarget"))]
639 value_contribution_msat,
643 #[allow(unused_mut)] // We only use the mut in cfg(test)
644 let mut should_process = !old_entry.was_processed;
645 #[cfg(any(test, feature = "fuzztarget"))]
647 // In test/fuzzing builds, we do extra checks to make sure the skipping
648 // of already-seen nodes only happens in cases we expect (see below).
649 if !should_process { should_process = true; }
653 let mut hop_use_fee_msat = 0;
654 let mut total_fee_msat = $next_hops_fee_msat;
656 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
657 // will have the same effective-fee
658 if $src_node_id != *our_node_id {
659 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
660 // max_value means we'll always fail
661 // the old_entry.total_fee_msat > total_fee_msat check
662 None => total_fee_msat = u64::max_value(),
664 hop_use_fee_msat = fee_msat;
665 total_fee_msat += hop_use_fee_msat;
666 // When calculating the lowest inbound fees to a node, we
667 // calculate fees here not based on the actual value we think
668 // will flow over this channel, but on the minimum value that
669 // we'll accept flowing over it. The minimum accepted value
670 // is a constant through each path collection run, ensuring
671 // consistent basis. Otherwise we may later find a
672 // different path to the source node that is more expensive,
673 // but which we consider to be cheaper because we are capacity
674 // constrained and the relative fee becomes lower.
675 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
676 .map(|a| a.checked_add(total_fee_msat)) {
681 total_fee_msat = u64::max_value();
688 let new_graph_node = RouteGraphNode {
689 pubkey: $src_node_id,
690 lowest_fee_to_peer_through_node: total_fee_msat,
691 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
692 value_contribution_msat: value_contribution_msat,
693 path_htlc_minimum_msat,
696 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
697 // if this way is cheaper than the already known
698 // (considering the cost to "reach" this channel from the route destination,
699 // the cost of using this channel,
700 // and the cost of routing to the source node of this channel).
701 // Also, consider that htlc_minimum_msat_difference, because we might end up
702 // paying it. Consider the following exploit:
703 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
704 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
705 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
706 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
708 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
709 // but it may require additional tracking - we don't want to double-count
710 // the fees included in $next_hops_path_htlc_minimum_msat, but also
711 // can't use something that may decrease on future hops.
712 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
713 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
715 if !old_entry.was_processed && new_cost < old_cost {
716 targets.push(new_graph_node);
717 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
718 old_entry.hop_use_fee_msat = hop_use_fee_msat;
719 old_entry.total_fee_msat = total_fee_msat;
720 old_entry.pubkey = $dest_node_id.clone();
721 old_entry.short_channel_id = $chan_id.clone();
722 old_entry.channel_features = $chan_features;
723 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
724 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
725 old_entry.channel_fees = $directional_info.fees;
726 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
727 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
728 #[cfg(any(test, feature = "fuzztarget"))]
730 old_entry.value_contribution_msat = value_contribution_msat;
732 did_add_update_path_to_src_node = true;
733 } else if old_entry.was_processed && new_cost < old_cost {
734 #[cfg(any(test, feature = "fuzztarget"))]
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.
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.
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);
763 did_add_update_path_to_src_node
767 let empty_node_features = NodeFeatures::empty();
768 // Find ways (channels with destination) to reach a given node and store them
769 // in the corresponding data structures (routing graph etc).
770 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
771 // meaning how much will be paid in fees after this node (to the best of our knowledge).
772 // This data can later be helpful to optimize routing (pay lower fees).
773 macro_rules! add_entries_to_cheapest_to_target_node {
774 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
775 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
776 let was_processed = elem.was_processed;
777 elem.was_processed = true;
780 // Entries are added to dist in add_entry!() when there is a channel from a node.
781 // Because there are no channels from payee, it will not have a dist entry at this point.
782 // If we're processing any other node, it is always be the result of a channel from it.
783 assert_eq!($node_id, payee);
788 if first_hops.is_some() {
789 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
790 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);
794 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
800 if !features.requires_unknown_bits() {
801 for chan_id in $node.channels.iter() {
802 let chan = network.get_channels().get(chan_id).unwrap();
803 if !chan.features.requires_unknown_bits() {
804 if chan.node_one == *$node_id {
805 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
806 if first_hops.is_none() || chan.node_two != *our_node_id {
807 if let Some(two_to_one) = chan.two_to_one.as_ref() {
808 if two_to_one.enabled {
809 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);
814 if first_hops.is_none() || chan.node_one != *our_node_id {
815 if let Some(one_to_two) = chan.one_to_two.as_ref() {
816 if one_to_two.enabled {
817 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);
829 let mut payment_paths = Vec::<PaymentPath>::new();
831 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
832 'paths_collection: loop {
833 // For every new path, start from scratch, except
834 // bookkeeped_channels_liquidity_available_msat, which will improve
835 // the further iterations of path finding. Also don't erase first_hop_targets.
838 hit_minimum_limit = false;
840 // If first hop is a private channel and the only way to reach the payee, this is the only
841 // place where it could be added.
842 if first_hops.is_some() {
843 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
844 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
848 // Add the payee as a target, so that the payee-to-payer
849 // search algorithm knows what to start with.
850 match network.get_nodes().get(payee) {
851 // The payee is not in our network graph, so nothing to add here.
852 // There is still a chance of reaching them via last_hops though,
853 // so don't yet fail the payment here.
854 // If not, targets.pop() will not even let us enter the loop in step 2.
857 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
862 // If a caller provided us with last hops, add them to routing targets. Since this happens
863 // earlier than general path finding, they will be somewhat prioritized, although currently
864 // it matters only if the fees are exactly the same.
865 for hop in last_hops.iter() {
866 let have_hop_src_in_graph =
867 // Only add the last hop to our candidate set if either we have a direct channel or
868 // they are in the regular network graph.
869 first_hop_targets.get(&hop.src_node_id).is_some() ||
870 network.get_nodes().get(&hop.src_node_id).is_some();
871 if have_hop_src_in_graph {
872 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
873 // really sucks, cause we're gonna need that eventually.
874 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
875 Some(htlc_minimum_msat) => htlc_minimum_msat,
878 let directional_info = DummyDirectionalChannelInfo {
879 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
880 htlc_minimum_msat: last_hop_htlc_minimum_msat,
881 htlc_maximum_msat: hop.htlc_maximum_msat,
884 if add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, &empty_channel_features, 0, path_value_msat, 0) {
885 // If this hop connects to a node with which we have a direct channel,
886 // ignore the network graph and, if the last hop was added, add our
887 // direct channel to the candidate set.
889 // Note that we *must* check if the last hop was added as `add_entry`
890 // always assumes that the third argument is a node to which we have a
892 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
893 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);
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;
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() {
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()));
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();
927 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
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);
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 {
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!(),
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()));
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;
962 let mut payment_path = PaymentPath {hops: ordered_hops};
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));
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;
991 *channel_liquidity_available_msat -= spent_on_hop_msat;
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;
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;
1008 payment_paths.push(payment_path);
1009 found_new_path = true;
1010 break 'path_construction;
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; }
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) {
1024 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1030 // If we don't support MPP, no use trying to gather more value ever.
1031 break 'paths_collection;
1035 // Stop either when the recommended value is reached or if no new path was found in this
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;
1050 path_value_msat = recommended_value_msat;
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});
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});
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);
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;
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();
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;
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 {
1103 let mut keep = true;
1104 let path_value_msat = path.get_value_msat();
1105 if path_value_msat <= overpaid_value_msat {
1107 overpaid_value_msat -= path_value_msat;
1113 if overpaid_value_msat == 0 {
1117 assert!(cur_route.len() > 0);
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);
1133 drawn_routes.push(cur_route);
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)| {
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,
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();
1159 let route = Route { paths: selected_paths };
1160 log_trace!(logger, "Got route: {}", log_route!(route));
1166 use routing::router::{get_route, Route, RouteHint, 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;
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;
1186 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1187 use bitcoin::secp256k1::{Secp256k1, All};
1192 // Using the same keys for LN and BTC ids
1193 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1194 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1195 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1196 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1198 let unsigned_announcement = UnsignedChannelAnnouncement {
1200 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1204 bitcoin_key_1: node_id_1,
1205 bitcoin_key_2: node_id_2,
1206 excess_data: Vec::new(),
1209 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1210 let valid_announcement = ChannelAnnouncement {
1211 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1212 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1213 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1214 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1215 contents: unsigned_announcement.clone(),
1217 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1218 Ok(res) => assert!(res),
1223 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) {
1224 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1225 let valid_channel_update = ChannelUpdate {
1226 signature: secp_ctx.sign(&msghash, node_privkey),
1227 contents: update.clone()
1230 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1231 Ok(res) => assert!(res),
1236 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,
1237 features: NodeFeatures, timestamp: u32) {
1238 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1239 let unsigned_announcement = UnsignedNodeAnnouncement {
1245 addresses: Vec::new(),
1246 excess_address_data: Vec::new(),
1247 excess_data: Vec::new(),
1249 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1250 let valid_announcement = NodeAnnouncement {
1251 signature: secp_ctx.sign(&msghash, node_privkey),
1252 contents: unsigned_announcement.clone()
1255 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1261 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1262 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1263 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1266 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1268 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1269 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1271 (our_privkey, our_id, privkeys, pubkeys)
1274 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1275 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1276 // test for it later.
1277 let idx = (id - 1) * 2 + 1;
1279 vec![1 << (idx - 8*3), 0, 0, 0]
1280 } else if idx > 8*2 {
1281 vec![1 << (idx - 8*2), 0, 0]
1282 } else if idx > 8*1 {
1283 vec![1 << (idx - 8*1), 0]
1289 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>) {
1290 let secp_ctx = Secp256k1::new();
1291 let logger = Arc::new(test_utils::TestLogger::new());
1292 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1293 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1294 // Build network from our_id to node7:
1296 // -1(1)2- node0 -1(3)2-
1298 // our_id -1(12)2- node7 -1(13)2--- node2
1300 // -1(2)2- node1 -1(4)2-
1303 // chan1 1-to-2: disabled
1304 // chan1 2-to-1: enabled, 0 fee
1306 // chan2 1-to-2: enabled, ignored fee
1307 // chan2 2-to-1: enabled, 0 fee
1309 // chan3 1-to-2: enabled, 0 fee
1310 // chan3 2-to-1: enabled, 100 msat fee
1312 // chan4 1-to-2: enabled, 100% fee
1313 // chan4 2-to-1: enabled, 0 fee
1315 // chan12 1-to-2: enabled, ignored fee
1316 // chan12 2-to-1: enabled, 0 fee
1318 // chan13 1-to-2: enabled, 200% fee
1319 // chan13 2-to-1: enabled, 0 fee
1322 // -1(5)2- node3 -1(8)2--
1326 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1328 // -1(7)2- node5 -1(10)2-
1330 // chan5 1-to-2: enabled, 100 msat fee
1331 // chan5 2-to-1: enabled, 0 fee
1333 // chan6 1-to-2: enabled, 0 fee
1334 // chan6 2-to-1: enabled, 0 fee
1336 // chan7 1-to-2: enabled, 100% fee
1337 // chan7 2-to-1: enabled, 0 fee
1339 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1340 // chan8 2-to-1: enabled, 0 fee
1342 // chan9 1-to-2: enabled, 1001 msat fee
1343 // chan9 2-to-1: enabled, 0 fee
1345 // chan10 1-to-2: enabled, 0 fee
1346 // chan10 2-to-1: enabled, 0 fee
1348 // chan11 1-to-2: enabled, 0 fee
1349 // chan11 2-to-1: enabled, 0 fee
1351 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1353 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1354 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1355 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1356 short_channel_id: 1,
1359 cltv_expiry_delta: 0,
1360 htlc_minimum_msat: 0,
1361 htlc_maximum_msat: OptionalField::Absent,
1363 fee_proportional_millionths: 0,
1364 excess_data: Vec::new()
1367 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1369 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1370 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1372 short_channel_id: 2,
1375 cltv_expiry_delta: u16::max_value(),
1376 htlc_minimum_msat: 0,
1377 htlc_maximum_msat: OptionalField::Absent,
1378 fee_base_msat: u32::max_value(),
1379 fee_proportional_millionths: u32::max_value(),
1380 excess_data: Vec::new()
1382 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1384 short_channel_id: 2,
1387 cltv_expiry_delta: 0,
1388 htlc_minimum_msat: 0,
1389 htlc_maximum_msat: OptionalField::Absent,
1391 fee_proportional_millionths: 0,
1392 excess_data: Vec::new()
1395 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1397 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1398 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1400 short_channel_id: 12,
1403 cltv_expiry_delta: u16::max_value(),
1404 htlc_minimum_msat: 0,
1405 htlc_maximum_msat: OptionalField::Absent,
1406 fee_base_msat: u32::max_value(),
1407 fee_proportional_millionths: u32::max_value(),
1408 excess_data: Vec::new()
1410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1412 short_channel_id: 12,
1415 cltv_expiry_delta: 0,
1416 htlc_minimum_msat: 0,
1417 htlc_maximum_msat: OptionalField::Absent,
1419 fee_proportional_millionths: 0,
1420 excess_data: Vec::new()
1423 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1425 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1426 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1427 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1428 short_channel_id: 3,
1431 cltv_expiry_delta: (3 << 8) | 1,
1432 htlc_minimum_msat: 0,
1433 htlc_maximum_msat: OptionalField::Absent,
1435 fee_proportional_millionths: 0,
1436 excess_data: Vec::new()
1438 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1439 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1440 short_channel_id: 3,
1443 cltv_expiry_delta: (3 << 8) | 2,
1444 htlc_minimum_msat: 0,
1445 htlc_maximum_msat: OptionalField::Absent,
1447 fee_proportional_millionths: 0,
1448 excess_data: Vec::new()
1451 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1452 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1453 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1454 short_channel_id: 4,
1457 cltv_expiry_delta: (4 << 8) | 1,
1458 htlc_minimum_msat: 0,
1459 htlc_maximum_msat: OptionalField::Absent,
1461 fee_proportional_millionths: 1000000,
1462 excess_data: Vec::new()
1464 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1466 short_channel_id: 4,
1469 cltv_expiry_delta: (4 << 8) | 2,
1470 htlc_minimum_msat: 0,
1471 htlc_maximum_msat: OptionalField::Absent,
1473 fee_proportional_millionths: 0,
1474 excess_data: Vec::new()
1477 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1478 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1479 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1480 short_channel_id: 13,
1483 cltv_expiry_delta: (13 << 8) | 1,
1484 htlc_minimum_msat: 0,
1485 htlc_maximum_msat: OptionalField::Absent,
1487 fee_proportional_millionths: 2000000,
1488 excess_data: Vec::new()
1490 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1491 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1492 short_channel_id: 13,
1495 cltv_expiry_delta: (13 << 8) | 2,
1496 htlc_minimum_msat: 0,
1497 htlc_maximum_msat: OptionalField::Absent,
1499 fee_proportional_millionths: 0,
1500 excess_data: Vec::new()
1503 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1505 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1506 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1507 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1508 short_channel_id: 6,
1511 cltv_expiry_delta: (6 << 8) | 1,
1512 htlc_minimum_msat: 0,
1513 htlc_maximum_msat: OptionalField::Absent,
1515 fee_proportional_millionths: 0,
1516 excess_data: Vec::new()
1518 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1519 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1520 short_channel_id: 6,
1523 cltv_expiry_delta: (6 << 8) | 2,
1524 htlc_minimum_msat: 0,
1525 htlc_maximum_msat: OptionalField::Absent,
1527 fee_proportional_millionths: 0,
1528 excess_data: Vec::new(),
1531 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1532 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1533 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1534 short_channel_id: 11,
1537 cltv_expiry_delta: (11 << 8) | 1,
1538 htlc_minimum_msat: 0,
1539 htlc_maximum_msat: OptionalField::Absent,
1541 fee_proportional_millionths: 0,
1542 excess_data: Vec::new()
1544 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1545 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1546 short_channel_id: 11,
1549 cltv_expiry_delta: (11 << 8) | 2,
1550 htlc_minimum_msat: 0,
1551 htlc_maximum_msat: OptionalField::Absent,
1553 fee_proportional_millionths: 0,
1554 excess_data: Vec::new()
1557 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1559 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1561 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1562 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1563 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1564 short_channel_id: 7,
1567 cltv_expiry_delta: (7 << 8) | 1,
1568 htlc_minimum_msat: 0,
1569 htlc_maximum_msat: OptionalField::Absent,
1571 fee_proportional_millionths: 1000000,
1572 excess_data: Vec::new()
1574 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1575 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1576 short_channel_id: 7,
1579 cltv_expiry_delta: (7 << 8) | 2,
1580 htlc_minimum_msat: 0,
1581 htlc_maximum_msat: OptionalField::Absent,
1583 fee_proportional_millionths: 0,
1584 excess_data: Vec::new()
1587 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1589 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1593 fn simple_route_test() {
1594 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1595 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1597 // Simple route to 2 via 1
1599 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)) {
1600 assert_eq!(err, "Cannot send a payment of 0 msat");
1601 } else { panic!(); }
1603 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();
1604 assert_eq!(route.paths[0].len(), 2);
1606 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1607 assert_eq!(route.paths[0][0].short_channel_id, 2);
1608 assert_eq!(route.paths[0][0].fee_msat, 100);
1609 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1610 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1611 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1613 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1614 assert_eq!(route.paths[0][1].short_channel_id, 4);
1615 assert_eq!(route.paths[0][1].fee_msat, 100);
1616 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1617 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1618 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1622 fn invalid_first_hop_test() {
1623 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1624 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1626 // Simple route to 2 via 1
1628 let our_chans = vec![channelmanager::ChannelDetails {
1629 channel_id: [0; 32],
1630 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1631 short_channel_id: Some(2),
1632 remote_network_id: our_id,
1633 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1634 channel_value_satoshis: 100000,
1636 outbound_capacity_msat: 100000,
1637 inbound_capacity_msat: 100000,
1638 is_outbound: true, is_funding_locked: true,
1639 is_usable: true, is_public: true,
1640 counterparty_forwarding_info: None,
1643 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)) {
1644 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1645 } else { panic!(); }
1647 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();
1648 assert_eq!(route.paths[0].len(), 2);
1652 fn htlc_minimum_test() {
1653 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1654 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1656 // Simple route to 2 via 1
1658 // Disable other paths
1659 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1661 short_channel_id: 12,
1663 flags: 2, // to disable
1664 cltv_expiry_delta: 0,
1665 htlc_minimum_msat: 0,
1666 htlc_maximum_msat: OptionalField::Absent,
1668 fee_proportional_millionths: 0,
1669 excess_data: Vec::new()
1671 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1672 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1673 short_channel_id: 3,
1675 flags: 2, // to disable
1676 cltv_expiry_delta: 0,
1677 htlc_minimum_msat: 0,
1678 htlc_maximum_msat: OptionalField::Absent,
1680 fee_proportional_millionths: 0,
1681 excess_data: Vec::new()
1683 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1684 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1685 short_channel_id: 13,
1687 flags: 2, // to disable
1688 cltv_expiry_delta: 0,
1689 htlc_minimum_msat: 0,
1690 htlc_maximum_msat: OptionalField::Absent,
1692 fee_proportional_millionths: 0,
1693 excess_data: Vec::new()
1695 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1696 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1697 short_channel_id: 6,
1699 flags: 2, // to disable
1700 cltv_expiry_delta: 0,
1701 htlc_minimum_msat: 0,
1702 htlc_maximum_msat: OptionalField::Absent,
1704 fee_proportional_millionths: 0,
1705 excess_data: Vec::new()
1707 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1708 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1709 short_channel_id: 7,
1711 flags: 2, // to disable
1712 cltv_expiry_delta: 0,
1713 htlc_minimum_msat: 0,
1714 htlc_maximum_msat: OptionalField::Absent,
1716 fee_proportional_millionths: 0,
1717 excess_data: Vec::new()
1720 // Check against amount_to_transfer_over_msat.
1721 // Set minimal HTLC of 200_000_000 msat.
1722 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1723 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1724 short_channel_id: 2,
1727 cltv_expiry_delta: 0,
1728 htlc_minimum_msat: 200_000_000,
1729 htlc_maximum_msat: OptionalField::Absent,
1731 fee_proportional_millionths: 0,
1732 excess_data: Vec::new()
1735 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1737 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1739 short_channel_id: 4,
1742 cltv_expiry_delta: 0,
1743 htlc_minimum_msat: 0,
1744 htlc_maximum_msat: OptionalField::Present(199_999_999),
1746 fee_proportional_millionths: 0,
1747 excess_data: Vec::new()
1750 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1751 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)) {
1752 assert_eq!(err, "Failed to find a path to the given destination");
1753 } else { panic!(); }
1755 // Lift the restriction on the first hop.
1756 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1758 short_channel_id: 2,
1761 cltv_expiry_delta: 0,
1762 htlc_minimum_msat: 0,
1763 htlc_maximum_msat: OptionalField::Absent,
1765 fee_proportional_millionths: 0,
1766 excess_data: Vec::new()
1769 // A payment above the minimum should pass
1770 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();
1771 assert_eq!(route.paths[0].len(), 2);
1775 fn htlc_minimum_overpay_test() {
1776 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1777 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1779 // A route to node#2 via two paths.
1780 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1781 // Thus, they can't send 60 without overpaying.
1782 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1784 short_channel_id: 2,
1787 cltv_expiry_delta: 0,
1788 htlc_minimum_msat: 35_000,
1789 htlc_maximum_msat: OptionalField::Present(40_000),
1791 fee_proportional_millionths: 0,
1792 excess_data: Vec::new()
1794 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1795 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1796 short_channel_id: 12,
1799 cltv_expiry_delta: 0,
1800 htlc_minimum_msat: 35_000,
1801 htlc_maximum_msat: OptionalField::Present(40_000),
1803 fee_proportional_millionths: 0,
1804 excess_data: Vec::new()
1808 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1810 short_channel_id: 13,
1813 cltv_expiry_delta: 0,
1814 htlc_minimum_msat: 0,
1815 htlc_maximum_msat: OptionalField::Absent,
1817 fee_proportional_millionths: 0,
1818 excess_data: Vec::new()
1820 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1821 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1822 short_channel_id: 4,
1825 cltv_expiry_delta: 0,
1826 htlc_minimum_msat: 0,
1827 htlc_maximum_msat: OptionalField::Absent,
1829 fee_proportional_millionths: 0,
1830 excess_data: Vec::new()
1833 // Disable other paths
1834 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1835 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1836 short_channel_id: 1,
1838 flags: 2, // to disable
1839 cltv_expiry_delta: 0,
1840 htlc_minimum_msat: 0,
1841 htlc_maximum_msat: OptionalField::Absent,
1843 fee_proportional_millionths: 0,
1844 excess_data: Vec::new()
1847 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1848 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1849 // Overpay fees to hit htlc_minimum_msat.
1850 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1851 // TODO: this could be better balanced to overpay 10k and not 15k.
1852 assert_eq!(overpaid_fees, 15_000);
1854 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1855 // while taking even more fee to match htlc_minimum_msat.
1856 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1857 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1858 short_channel_id: 12,
1861 cltv_expiry_delta: 0,
1862 htlc_minimum_msat: 65_000,
1863 htlc_maximum_msat: OptionalField::Present(80_000),
1865 fee_proportional_millionths: 0,
1866 excess_data: Vec::new()
1868 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1869 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1870 short_channel_id: 2,
1873 cltv_expiry_delta: 0,
1874 htlc_minimum_msat: 0,
1875 htlc_maximum_msat: OptionalField::Absent,
1877 fee_proportional_millionths: 0,
1878 excess_data: Vec::new()
1880 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1882 short_channel_id: 4,
1885 cltv_expiry_delta: 0,
1886 htlc_minimum_msat: 0,
1887 htlc_maximum_msat: OptionalField::Absent,
1889 fee_proportional_millionths: 100_000,
1890 excess_data: Vec::new()
1893 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1894 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1895 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1896 assert_eq!(route.paths.len(), 1);
1897 assert_eq!(route.paths[0][0].short_channel_id, 12);
1898 let fees = route.paths[0][0].fee_msat;
1899 assert_eq!(fees, 5_000);
1901 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1902 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1903 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1904 // the other channel.
1905 assert_eq!(route.paths.len(), 1);
1906 assert_eq!(route.paths[0][0].short_channel_id, 2);
1907 let fees = route.paths[0][0].fee_msat;
1908 assert_eq!(fees, 5_000);
1912 fn disable_channels_test() {
1913 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1914 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1916 // // Disable channels 4 and 12 by flags=2
1917 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1919 short_channel_id: 4,
1921 flags: 2, // to disable
1922 cltv_expiry_delta: 0,
1923 htlc_minimum_msat: 0,
1924 htlc_maximum_msat: OptionalField::Absent,
1926 fee_proportional_millionths: 0,
1927 excess_data: Vec::new()
1929 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1930 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1931 short_channel_id: 12,
1933 flags: 2, // to disable
1934 cltv_expiry_delta: 0,
1935 htlc_minimum_msat: 0,
1936 htlc_maximum_msat: OptionalField::Absent,
1938 fee_proportional_millionths: 0,
1939 excess_data: Vec::new()
1942 // If all the channels require some features we don't understand, route should fail
1943 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)) {
1944 assert_eq!(err, "Failed to find a path to the given destination");
1945 } else { panic!(); }
1947 // If we specify a channel to node7, that overrides our local channel view and that gets used
1948 let our_chans = vec![channelmanager::ChannelDetails {
1949 channel_id: [0; 32],
1950 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1951 short_channel_id: Some(42),
1952 remote_network_id: nodes[7].clone(),
1953 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1954 channel_value_satoshis: 0,
1956 outbound_capacity_msat: 250_000_000,
1957 inbound_capacity_msat: 0,
1958 is_outbound: true, is_funding_locked: true,
1959 is_usable: true, is_public: true,
1960 counterparty_forwarding_info: None,
1962 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();
1963 assert_eq!(route.paths[0].len(), 2);
1965 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1966 assert_eq!(route.paths[0][0].short_channel_id, 42);
1967 assert_eq!(route.paths[0][0].fee_msat, 200);
1968 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1969 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1970 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1972 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1973 assert_eq!(route.paths[0][1].short_channel_id, 13);
1974 assert_eq!(route.paths[0][1].fee_msat, 100);
1975 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1976 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1977 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1981 fn disable_node_test() {
1982 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1983 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1985 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1986 let mut unknown_features = NodeFeatures::known();
1987 unknown_features.set_required_unknown_bits();
1988 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1989 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1990 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1992 // If all nodes require some features we don't understand, route should fail
1993 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)) {
1994 assert_eq!(err, "Failed to find a path to the given destination");
1995 } else { panic!(); }
1997 // If we specify a channel to node7, that overrides our local channel view and that gets used
1998 let our_chans = vec![channelmanager::ChannelDetails {
1999 channel_id: [0; 32],
2000 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2001 short_channel_id: Some(42),
2002 remote_network_id: nodes[7].clone(),
2003 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2004 channel_value_satoshis: 0,
2006 outbound_capacity_msat: 250_000_000,
2007 inbound_capacity_msat: 0,
2008 is_outbound: true, is_funding_locked: true,
2009 is_usable: true, is_public: true,
2010 counterparty_forwarding_info: None,
2012 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();
2013 assert_eq!(route.paths[0].len(), 2);
2015 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2016 assert_eq!(route.paths[0][0].short_channel_id, 42);
2017 assert_eq!(route.paths[0][0].fee_msat, 200);
2018 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2019 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2020 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2022 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2023 assert_eq!(route.paths[0][1].short_channel_id, 13);
2024 assert_eq!(route.paths[0][1].fee_msat, 100);
2025 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2026 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2027 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2029 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2030 // naively) assume that the user checked the feature bits on the invoice, which override
2031 // the node_announcement.
2035 fn our_chans_test() {
2036 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2037 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2039 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2040 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();
2041 assert_eq!(route.paths[0].len(), 3);
2043 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2044 assert_eq!(route.paths[0][0].short_channel_id, 2);
2045 assert_eq!(route.paths[0][0].fee_msat, 200);
2046 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2047 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2048 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2050 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2051 assert_eq!(route.paths[0][1].short_channel_id, 4);
2052 assert_eq!(route.paths[0][1].fee_msat, 100);
2053 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2054 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2055 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2057 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2058 assert_eq!(route.paths[0][2].short_channel_id, 3);
2059 assert_eq!(route.paths[0][2].fee_msat, 100);
2060 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2061 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2062 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2064 // If we specify a channel to node7, that overrides our local channel view and that gets used
2065 let our_chans = vec![channelmanager::ChannelDetails {
2066 channel_id: [0; 32],
2067 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2068 short_channel_id: Some(42),
2069 remote_network_id: nodes[7].clone(),
2070 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2071 channel_value_satoshis: 0,
2073 outbound_capacity_msat: 250_000_000,
2074 inbound_capacity_msat: 0,
2075 is_outbound: true, is_funding_locked: true,
2076 is_usable: true, is_public: true,
2077 counterparty_forwarding_info: None,
2079 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
2080 assert_eq!(route.paths[0].len(), 2);
2082 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2083 assert_eq!(route.paths[0][0].short_channel_id, 42);
2084 assert_eq!(route.paths[0][0].fee_msat, 200);
2085 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2086 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2087 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2089 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2090 assert_eq!(route.paths[0][1].short_channel_id, 13);
2091 assert_eq!(route.paths[0][1].fee_msat, 100);
2092 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2093 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2094 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2097 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2098 let zero_fees = RoutingFees {
2100 proportional_millionths: 0,
2102 vec![RouteHint(vec![RouteHintHop {
2103 src_node_id: nodes[3].clone(),
2104 short_channel_id: 8,
2106 cltv_expiry_delta: (8 << 8) | 1,
2107 htlc_minimum_msat: None,
2108 htlc_maximum_msat: None,
2109 }]), RouteHint(vec![RouteHintHop {
2110 src_node_id: nodes[4].clone(),
2111 short_channel_id: 9,
2114 proportional_millionths: 0,
2116 cltv_expiry_delta: (9 << 8) | 1,
2117 htlc_minimum_msat: None,
2118 htlc_maximum_msat: None,
2119 }]), RouteHint(vec![RouteHintHop {
2120 src_node_id: nodes[5].clone(),
2121 short_channel_id: 10,
2123 cltv_expiry_delta: (10 << 8) | 1,
2124 htlc_minimum_msat: None,
2125 htlc_maximum_msat: None,
2130 fn last_hops_test() {
2131 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2132 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2134 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2136 // First check that last hop can't have its source as the payee.
2137 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2138 src_node_id: nodes[6],
2139 short_channel_id: 8,
2142 proportional_millionths: 0,
2144 cltv_expiry_delta: (8 << 8) | 1,
2145 htlc_minimum_msat: None,
2146 htlc_maximum_msat: None,
2149 let mut invalid_last_hops = last_hops(&nodes);
2150 invalid_last_hops.push(invalid_last_hop);
2152 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)) {
2153 assert_eq!(err, "Last hop cannot have a payee as a source.");
2154 } else { panic!(); }
2157 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();
2158 assert_eq!(route.paths[0].len(), 5);
2160 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2161 assert_eq!(route.paths[0][0].short_channel_id, 2);
2162 assert_eq!(route.paths[0][0].fee_msat, 100);
2163 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2164 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2165 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2167 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2168 assert_eq!(route.paths[0][1].short_channel_id, 4);
2169 assert_eq!(route.paths[0][1].fee_msat, 0);
2170 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2171 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2172 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2174 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2175 assert_eq!(route.paths[0][2].short_channel_id, 6);
2176 assert_eq!(route.paths[0][2].fee_msat, 0);
2177 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2178 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2179 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2181 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2182 assert_eq!(route.paths[0][3].short_channel_id, 11);
2183 assert_eq!(route.paths[0][3].fee_msat, 0);
2184 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2185 // If we have a peer in the node map, we'll use their features here since we don't have
2186 // a way of figuring out their features from the invoice:
2187 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2188 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2190 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2191 assert_eq!(route.paths[0][4].short_channel_id, 8);
2192 assert_eq!(route.paths[0][4].fee_msat, 100);
2193 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2194 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2195 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2199 fn our_chans_last_hop_connect_test() {
2200 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2201 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2203 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2204 let our_chans = vec![channelmanager::ChannelDetails {
2205 channel_id: [0; 32],
2206 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2207 short_channel_id: Some(42),
2208 remote_network_id: nodes[3].clone(),
2209 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2210 channel_value_satoshis: 0,
2212 outbound_capacity_msat: 250_000_000,
2213 inbound_capacity_msat: 0,
2214 is_outbound: true, is_funding_locked: true,
2215 is_usable: true, is_public: true,
2216 counterparty_forwarding_info: None,
2218 let mut last_hops = last_hops(&nodes);
2219 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();
2220 assert_eq!(route.paths[0].len(), 2);
2222 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2223 assert_eq!(route.paths[0][0].short_channel_id, 42);
2224 assert_eq!(route.paths[0][0].fee_msat, 0);
2225 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2226 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2227 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2229 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2230 assert_eq!(route.paths[0][1].short_channel_id, 8);
2231 assert_eq!(route.paths[0][1].fee_msat, 100);
2232 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2233 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2234 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2236 last_hops[0].0[0].fees.base_msat = 1000;
2238 // Revert to via 6 as the fee on 8 goes up
2239 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();
2240 assert_eq!(route.paths[0].len(), 4);
2242 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2243 assert_eq!(route.paths[0][0].short_channel_id, 2);
2244 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2245 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2246 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2247 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2249 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2250 assert_eq!(route.paths[0][1].short_channel_id, 4);
2251 assert_eq!(route.paths[0][1].fee_msat, 100);
2252 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2253 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2254 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2256 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2257 assert_eq!(route.paths[0][2].short_channel_id, 7);
2258 assert_eq!(route.paths[0][2].fee_msat, 0);
2259 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2260 // If we have a peer in the node map, we'll use their features here since we don't have
2261 // a way of figuring out their features from the invoice:
2262 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2263 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2265 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2266 assert_eq!(route.paths[0][3].short_channel_id, 10);
2267 assert_eq!(route.paths[0][3].fee_msat, 100);
2268 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2269 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2270 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2272 // ...but still use 8 for larger payments as 6 has a variable feerate
2273 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();
2274 assert_eq!(route.paths[0].len(), 5);
2276 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2277 assert_eq!(route.paths[0][0].short_channel_id, 2);
2278 assert_eq!(route.paths[0][0].fee_msat, 3000);
2279 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2280 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2281 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2283 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2284 assert_eq!(route.paths[0][1].short_channel_id, 4);
2285 assert_eq!(route.paths[0][1].fee_msat, 0);
2286 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2287 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2288 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2290 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2291 assert_eq!(route.paths[0][2].short_channel_id, 6);
2292 assert_eq!(route.paths[0][2].fee_msat, 0);
2293 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2294 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2295 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2297 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2298 assert_eq!(route.paths[0][3].short_channel_id, 11);
2299 assert_eq!(route.paths[0][3].fee_msat, 1000);
2300 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2301 // If we have a peer in the node map, we'll use their features here since we don't have
2302 // a way of figuring out their features from the invoice:
2303 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2304 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2306 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2307 assert_eq!(route.paths[0][4].short_channel_id, 8);
2308 assert_eq!(route.paths[0][4].fee_msat, 2000);
2309 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2310 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2311 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2314 fn do_unannounced_path_test(last_hop_htlc_max: Option<u64>, last_hop_fee_prop: u32, outbound_capacity_msat: u64, route_val: u64) -> Result<Route, LightningError> {
2315 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2316 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2317 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2319 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2320 let last_hops = RouteHint(vec![RouteHintHop {
2321 src_node_id: middle_node_id,
2322 short_channel_id: 8,
2325 proportional_millionths: last_hop_fee_prop,
2327 cltv_expiry_delta: (8 << 8) | 1,
2328 htlc_minimum_msat: None,
2329 htlc_maximum_msat: last_hop_htlc_max,
2331 let our_chans = vec![channelmanager::ChannelDetails {
2332 channel_id: [0; 32],
2333 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2334 short_channel_id: Some(42),
2335 remote_network_id: middle_node_id,
2336 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2337 channel_value_satoshis: 100000,
2339 outbound_capacity_msat: outbound_capacity_msat,
2340 inbound_capacity_msat: 100000,
2341 is_outbound: true, is_funding_locked: true,
2342 is_usable: true, is_public: true,
2343 counterparty_forwarding_info: None,
2345 get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &vec![&last_hops], route_val, 42, Arc::new(test_utils::TestLogger::new()))
2349 fn unannounced_path_test() {
2350 // We should be able to send a payment to a destination without any help of a routing graph
2351 // if we have a channel with a common counterparty that appears in the first and last hop
2353 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2355 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2356 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2357 assert_eq!(route.paths[0].len(), 2);
2359 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2360 assert_eq!(route.paths[0][0].short_channel_id, 42);
2361 assert_eq!(route.paths[0][0].fee_msat, 1001);
2362 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2363 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2364 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2366 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2367 assert_eq!(route.paths[0][1].short_channel_id, 8);
2368 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2369 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2370 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2371 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2375 fn overflow_unannounced_path_test_liquidity_underflow() {
2376 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2377 // the last-hop had a fee which overflowed a u64, we'd panic.
2378 // This was due to us adding the first-hop from us unconditionally, causing us to think
2379 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2380 // In this test, we previously hit a subtraction underflow due to having less available
2381 // liquidity at the last hop than 0.
2382 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 0, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
2386 fn overflow_unannounced_path_test_feerate_overflow() {
2387 // This tests for the same case as above, except instead of hitting a subtraction
2388 // underflow, we hit a case where the fee charged at a hop overflowed.
2389 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 50000, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
2393 fn available_amount_while_routing_test() {
2394 // Tests whether we choose the correct available channel amount while routing.
2396 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2397 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2399 // We will use a simple single-path route from
2400 // our node to node2 via node0: channels {1, 3}.
2402 // First disable all other paths.
2403 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2404 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2405 short_channel_id: 2,
2408 cltv_expiry_delta: 0,
2409 htlc_minimum_msat: 0,
2410 htlc_maximum_msat: OptionalField::Present(100_000),
2412 fee_proportional_millionths: 0,
2413 excess_data: Vec::new()
2415 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2416 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2417 short_channel_id: 12,
2420 cltv_expiry_delta: 0,
2421 htlc_minimum_msat: 0,
2422 htlc_maximum_msat: OptionalField::Present(100_000),
2424 fee_proportional_millionths: 0,
2425 excess_data: Vec::new()
2428 // Make the first channel (#1) very permissive,
2429 // and we will be testing all limits on the second channel.
2430 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2432 short_channel_id: 1,
2435 cltv_expiry_delta: 0,
2436 htlc_minimum_msat: 0,
2437 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2439 fee_proportional_millionths: 0,
2440 excess_data: Vec::new()
2443 // First, let's see if routing works if we have absolutely no idea about the available amount.
2444 // In this case, it should be set to 250_000 sats.
2445 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2446 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2447 short_channel_id: 3,
2450 cltv_expiry_delta: 0,
2451 htlc_minimum_msat: 0,
2452 htlc_maximum_msat: OptionalField::Absent,
2454 fee_proportional_millionths: 0,
2455 excess_data: Vec::new()
2459 // Attempt to route more than available results in a failure.
2460 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2461 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2462 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2463 } else { panic!(); }
2467 // Now, attempt to route an exact amount we have should be fine.
2468 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2469 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2470 assert_eq!(route.paths.len(), 1);
2471 let path = route.paths.last().unwrap();
2472 assert_eq!(path.len(), 2);
2473 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2474 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2477 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2478 // Disable channel #1 and use another first hop.
2479 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2480 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2481 short_channel_id: 1,
2484 cltv_expiry_delta: 0,
2485 htlc_minimum_msat: 0,
2486 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2488 fee_proportional_millionths: 0,
2489 excess_data: Vec::new()
2492 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2493 let our_chans = vec![channelmanager::ChannelDetails {
2494 channel_id: [0; 32],
2495 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2496 short_channel_id: Some(42),
2497 remote_network_id: nodes[0].clone(),
2498 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2499 channel_value_satoshis: 0,
2501 outbound_capacity_msat: 200_000_000,
2502 inbound_capacity_msat: 0,
2503 is_outbound: true, is_funding_locked: true,
2504 is_usable: true, is_public: true,
2505 counterparty_forwarding_info: None,
2509 // Attempt to route more than available results in a failure.
2510 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2511 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2512 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2513 } else { panic!(); }
2517 // Now, attempt to route an exact amount we have should be fine.
2518 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2519 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2520 assert_eq!(route.paths.len(), 1);
2521 let path = route.paths.last().unwrap();
2522 assert_eq!(path.len(), 2);
2523 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2524 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2527 // Enable channel #1 back.
2528 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2529 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2530 short_channel_id: 1,
2533 cltv_expiry_delta: 0,
2534 htlc_minimum_msat: 0,
2535 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2537 fee_proportional_millionths: 0,
2538 excess_data: Vec::new()
2542 // Now let's see if routing works if we know only htlc_maximum_msat.
2543 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2544 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2545 short_channel_id: 3,
2548 cltv_expiry_delta: 0,
2549 htlc_minimum_msat: 0,
2550 htlc_maximum_msat: OptionalField::Present(15_000),
2552 fee_proportional_millionths: 0,
2553 excess_data: Vec::new()
2557 // Attempt to route more than available results in a failure.
2558 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2559 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2560 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2561 } else { panic!(); }
2565 // Now, attempt to route an exact amount we have should be fine.
2566 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2567 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2568 assert_eq!(route.paths.len(), 1);
2569 let path = route.paths.last().unwrap();
2570 assert_eq!(path.len(), 2);
2571 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2572 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2575 // Now let's see if routing works if we know only capacity from the UTXO.
2577 // We can't change UTXO capacity on the fly, so we'll disable
2578 // the existing channel and add another one with the capacity we need.
2579 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2580 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2581 short_channel_id: 3,
2584 cltv_expiry_delta: 0,
2585 htlc_minimum_msat: 0,
2586 htlc_maximum_msat: OptionalField::Absent,
2588 fee_proportional_millionths: 0,
2589 excess_data: Vec::new()
2592 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2593 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2594 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2595 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2596 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2598 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2599 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2601 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2602 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2603 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2604 short_channel_id: 333,
2607 cltv_expiry_delta: (3 << 8) | 1,
2608 htlc_minimum_msat: 0,
2609 htlc_maximum_msat: OptionalField::Absent,
2611 fee_proportional_millionths: 0,
2612 excess_data: Vec::new()
2614 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2615 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2616 short_channel_id: 333,
2619 cltv_expiry_delta: (3 << 8) | 2,
2620 htlc_minimum_msat: 0,
2621 htlc_maximum_msat: OptionalField::Absent,
2623 fee_proportional_millionths: 0,
2624 excess_data: Vec::new()
2628 // Attempt to route more than available results in a failure.
2629 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2630 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2631 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2632 } else { panic!(); }
2636 // Now, attempt to route an exact amount we have should be fine.
2637 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2638 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2639 assert_eq!(route.paths.len(), 1);
2640 let path = route.paths.last().unwrap();
2641 assert_eq!(path.len(), 2);
2642 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2643 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2646 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2647 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2648 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2649 short_channel_id: 333,
2652 cltv_expiry_delta: 0,
2653 htlc_minimum_msat: 0,
2654 htlc_maximum_msat: OptionalField::Present(10_000),
2656 fee_proportional_millionths: 0,
2657 excess_data: Vec::new()
2661 // Attempt to route more than available results in a failure.
2662 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2663 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2664 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2665 } else { panic!(); }
2669 // Now, attempt to route an exact amount we have should be fine.
2670 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2671 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2672 assert_eq!(route.paths.len(), 1);
2673 let path = route.paths.last().unwrap();
2674 assert_eq!(path.len(), 2);
2675 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2676 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2681 fn available_liquidity_last_hop_test() {
2682 // Check that available liquidity properly limits the path even when only
2683 // one of the latter hops is limited.
2684 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2685 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2687 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2688 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2689 // Total capacity: 50 sats.
2691 // Disable other potential paths.
2692 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2693 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2694 short_channel_id: 2,
2697 cltv_expiry_delta: 0,
2698 htlc_minimum_msat: 0,
2699 htlc_maximum_msat: OptionalField::Present(100_000),
2701 fee_proportional_millionths: 0,
2702 excess_data: Vec::new()
2704 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2705 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2706 short_channel_id: 7,
2709 cltv_expiry_delta: 0,
2710 htlc_minimum_msat: 0,
2711 htlc_maximum_msat: OptionalField::Present(100_000),
2713 fee_proportional_millionths: 0,
2714 excess_data: Vec::new()
2719 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2720 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2721 short_channel_id: 12,
2724 cltv_expiry_delta: 0,
2725 htlc_minimum_msat: 0,
2726 htlc_maximum_msat: OptionalField::Present(100_000),
2728 fee_proportional_millionths: 0,
2729 excess_data: Vec::new()
2731 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2732 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2733 short_channel_id: 13,
2736 cltv_expiry_delta: 0,
2737 htlc_minimum_msat: 0,
2738 htlc_maximum_msat: OptionalField::Present(100_000),
2740 fee_proportional_millionths: 0,
2741 excess_data: Vec::new()
2744 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2746 short_channel_id: 6,
2749 cltv_expiry_delta: 0,
2750 htlc_minimum_msat: 0,
2751 htlc_maximum_msat: OptionalField::Present(50_000),
2753 fee_proportional_millionths: 0,
2754 excess_data: Vec::new()
2756 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2758 short_channel_id: 11,
2761 cltv_expiry_delta: 0,
2762 htlc_minimum_msat: 0,
2763 htlc_maximum_msat: OptionalField::Present(100_000),
2765 fee_proportional_millionths: 0,
2766 excess_data: Vec::new()
2769 // Attempt to route more than available results in a failure.
2770 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2771 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2772 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2773 } else { panic!(); }
2777 // Now, attempt to route 49 sats (just a bit below the capacity).
2778 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2779 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2780 assert_eq!(route.paths.len(), 1);
2781 let mut total_amount_paid_msat = 0;
2782 for path in &route.paths {
2783 assert_eq!(path.len(), 4);
2784 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2785 total_amount_paid_msat += path.last().unwrap().fee_msat;
2787 assert_eq!(total_amount_paid_msat, 49_000);
2791 // Attempt to route an exact amount is also fine
2792 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2793 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2794 assert_eq!(route.paths.len(), 1);
2795 let mut total_amount_paid_msat = 0;
2796 for path in &route.paths {
2797 assert_eq!(path.len(), 4);
2798 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2799 total_amount_paid_msat += path.last().unwrap().fee_msat;
2801 assert_eq!(total_amount_paid_msat, 50_000);
2806 fn ignore_fee_first_hop_test() {
2807 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2808 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2810 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2811 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2812 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2813 short_channel_id: 1,
2816 cltv_expiry_delta: 0,
2817 htlc_minimum_msat: 0,
2818 htlc_maximum_msat: OptionalField::Present(100_000),
2819 fee_base_msat: 1_000_000,
2820 fee_proportional_millionths: 0,
2821 excess_data: Vec::new()
2823 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2824 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2825 short_channel_id: 3,
2828 cltv_expiry_delta: 0,
2829 htlc_minimum_msat: 0,
2830 htlc_maximum_msat: OptionalField::Present(50_000),
2832 fee_proportional_millionths: 0,
2833 excess_data: Vec::new()
2837 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();
2838 assert_eq!(route.paths.len(), 1);
2839 let mut total_amount_paid_msat = 0;
2840 for path in &route.paths {
2841 assert_eq!(path.len(), 2);
2842 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2843 total_amount_paid_msat += path.last().unwrap().fee_msat;
2845 assert_eq!(total_amount_paid_msat, 50_000);
2850 fn simple_mpp_route_test() {
2851 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2852 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2854 // We need a route consisting of 3 paths:
2855 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2856 // To achieve this, the amount being transferred should be around
2857 // the total capacity of these 3 paths.
2859 // First, we set limits on these (previously unlimited) channels.
2860 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2862 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2863 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2864 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2865 short_channel_id: 1,
2868 cltv_expiry_delta: 0,
2869 htlc_minimum_msat: 0,
2870 htlc_maximum_msat: OptionalField::Present(100_000),
2872 fee_proportional_millionths: 0,
2873 excess_data: Vec::new()
2875 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2876 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2877 short_channel_id: 3,
2880 cltv_expiry_delta: 0,
2881 htlc_minimum_msat: 0,
2882 htlc_maximum_msat: OptionalField::Present(50_000),
2884 fee_proportional_millionths: 0,
2885 excess_data: Vec::new()
2888 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2889 // (total limit 60).
2890 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2891 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2892 short_channel_id: 12,
2895 cltv_expiry_delta: 0,
2896 htlc_minimum_msat: 0,
2897 htlc_maximum_msat: OptionalField::Present(60_000),
2899 fee_proportional_millionths: 0,
2900 excess_data: Vec::new()
2902 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2904 short_channel_id: 13,
2907 cltv_expiry_delta: 0,
2908 htlc_minimum_msat: 0,
2909 htlc_maximum_msat: OptionalField::Present(60_000),
2911 fee_proportional_millionths: 0,
2912 excess_data: Vec::new()
2915 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2916 // (total capacity 180 sats).
2917 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2918 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2919 short_channel_id: 2,
2922 cltv_expiry_delta: 0,
2923 htlc_minimum_msat: 0,
2924 htlc_maximum_msat: OptionalField::Present(200_000),
2926 fee_proportional_millionths: 0,
2927 excess_data: Vec::new()
2929 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2930 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2931 short_channel_id: 4,
2934 cltv_expiry_delta: 0,
2935 htlc_minimum_msat: 0,
2936 htlc_maximum_msat: OptionalField::Present(180_000),
2938 fee_proportional_millionths: 0,
2939 excess_data: Vec::new()
2943 // Attempt to route more than available results in a failure.
2944 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2945 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2946 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2947 } else { panic!(); }
2951 // Now, attempt to route 250 sats (just a bit below the capacity).
2952 // Our algorithm should provide us with these 3 paths.
2953 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2954 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2955 assert_eq!(route.paths.len(), 3);
2956 let mut total_amount_paid_msat = 0;
2957 for path in &route.paths {
2958 assert_eq!(path.len(), 2);
2959 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2960 total_amount_paid_msat += path.last().unwrap().fee_msat;
2962 assert_eq!(total_amount_paid_msat, 250_000);
2966 // Attempt to route an exact amount is also fine
2967 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2968 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2969 assert_eq!(route.paths.len(), 3);
2970 let mut total_amount_paid_msat = 0;
2971 for path in &route.paths {
2972 assert_eq!(path.len(), 2);
2973 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2974 total_amount_paid_msat += path.last().unwrap().fee_msat;
2976 assert_eq!(total_amount_paid_msat, 290_000);
2981 fn long_mpp_route_test() {
2982 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2983 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2985 // We need a route consisting of 3 paths:
2986 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2987 // Note that these paths overlap (channels 5, 12, 13).
2988 // We will route 300 sats.
2989 // Each path will have 100 sats capacity, those channels which
2990 // are used twice will have 200 sats capacity.
2992 // Disable other potential paths.
2993 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2994 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2995 short_channel_id: 2,
2998 cltv_expiry_delta: 0,
2999 htlc_minimum_msat: 0,
3000 htlc_maximum_msat: OptionalField::Present(100_000),
3002 fee_proportional_millionths: 0,
3003 excess_data: Vec::new()
3005 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3006 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3007 short_channel_id: 7,
3010 cltv_expiry_delta: 0,
3011 htlc_minimum_msat: 0,
3012 htlc_maximum_msat: OptionalField::Present(100_000),
3014 fee_proportional_millionths: 0,
3015 excess_data: Vec::new()
3018 // Path via {node0, node2} is channels {1, 3, 5}.
3019 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3020 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3021 short_channel_id: 1,
3024 cltv_expiry_delta: 0,
3025 htlc_minimum_msat: 0,
3026 htlc_maximum_msat: OptionalField::Present(100_000),
3028 fee_proportional_millionths: 0,
3029 excess_data: Vec::new()
3031 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3032 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3033 short_channel_id: 3,
3036 cltv_expiry_delta: 0,
3037 htlc_minimum_msat: 0,
3038 htlc_maximum_msat: OptionalField::Present(100_000),
3040 fee_proportional_millionths: 0,
3041 excess_data: Vec::new()
3044 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3045 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3046 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3048 short_channel_id: 5,
3051 cltv_expiry_delta: 0,
3052 htlc_minimum_msat: 0,
3053 htlc_maximum_msat: OptionalField::Present(200_000),
3055 fee_proportional_millionths: 0,
3056 excess_data: Vec::new()
3059 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3060 // Add 100 sats to the capacities of {12, 13}, because these channels
3061 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3062 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3063 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3064 short_channel_id: 12,
3067 cltv_expiry_delta: 0,
3068 htlc_minimum_msat: 0,
3069 htlc_maximum_msat: OptionalField::Present(200_000),
3071 fee_proportional_millionths: 0,
3072 excess_data: Vec::new()
3074 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3075 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3076 short_channel_id: 13,
3079 cltv_expiry_delta: 0,
3080 htlc_minimum_msat: 0,
3081 htlc_maximum_msat: OptionalField::Present(200_000),
3083 fee_proportional_millionths: 0,
3084 excess_data: Vec::new()
3087 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3088 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3089 short_channel_id: 6,
3092 cltv_expiry_delta: 0,
3093 htlc_minimum_msat: 0,
3094 htlc_maximum_msat: OptionalField::Present(100_000),
3096 fee_proportional_millionths: 0,
3097 excess_data: Vec::new()
3099 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3100 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3101 short_channel_id: 11,
3104 cltv_expiry_delta: 0,
3105 htlc_minimum_msat: 0,
3106 htlc_maximum_msat: OptionalField::Present(100_000),
3108 fee_proportional_millionths: 0,
3109 excess_data: Vec::new()
3112 // Path via {node7, node2} is channels {12, 13, 5}.
3113 // We already limited them to 200 sats (they are used twice for 100 sats).
3114 // Nothing to do here.
3117 // Attempt to route more than available results in a failure.
3118 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3119 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3120 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3121 } else { panic!(); }
3125 // Now, attempt to route 300 sats (exact amount we can route).
3126 // Our algorithm should provide us with these 3 paths, 100 sats each.
3127 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3128 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3129 assert_eq!(route.paths.len(), 3);
3131 let mut total_amount_paid_msat = 0;
3132 for path in &route.paths {
3133 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3134 total_amount_paid_msat += path.last().unwrap().fee_msat;
3136 assert_eq!(total_amount_paid_msat, 300_000);
3142 fn mpp_cheaper_route_test() {
3143 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3144 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3146 // This test checks that if we have two cheaper paths and one more expensive path,
3147 // so that liquidity-wise any 2 of 3 combination is sufficient,
3148 // two cheaper paths will be taken.
3149 // These paths have equal available liquidity.
3151 // We need a combination of 3 paths:
3152 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3153 // Note that these paths overlap (channels 5, 12, 13).
3154 // Each path will have 100 sats capacity, those channels which
3155 // are used twice will have 200 sats capacity.
3157 // Disable other potential paths.
3158 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3159 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3160 short_channel_id: 2,
3163 cltv_expiry_delta: 0,
3164 htlc_minimum_msat: 0,
3165 htlc_maximum_msat: OptionalField::Present(100_000),
3167 fee_proportional_millionths: 0,
3168 excess_data: Vec::new()
3170 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3171 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3172 short_channel_id: 7,
3175 cltv_expiry_delta: 0,
3176 htlc_minimum_msat: 0,
3177 htlc_maximum_msat: OptionalField::Present(100_000),
3179 fee_proportional_millionths: 0,
3180 excess_data: Vec::new()
3183 // Path via {node0, node2} is channels {1, 3, 5}.
3184 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3185 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3186 short_channel_id: 1,
3189 cltv_expiry_delta: 0,
3190 htlc_minimum_msat: 0,
3191 htlc_maximum_msat: OptionalField::Present(100_000),
3193 fee_proportional_millionths: 0,
3194 excess_data: Vec::new()
3196 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3198 short_channel_id: 3,
3201 cltv_expiry_delta: 0,
3202 htlc_minimum_msat: 0,
3203 htlc_maximum_msat: OptionalField::Present(100_000),
3205 fee_proportional_millionths: 0,
3206 excess_data: Vec::new()
3209 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3210 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3211 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3212 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3213 short_channel_id: 5,
3216 cltv_expiry_delta: 0,
3217 htlc_minimum_msat: 0,
3218 htlc_maximum_msat: OptionalField::Present(200_000),
3220 fee_proportional_millionths: 0,
3221 excess_data: Vec::new()
3224 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3225 // Add 100 sats to the capacities of {12, 13}, because these channels
3226 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3227 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3229 short_channel_id: 12,
3232 cltv_expiry_delta: 0,
3233 htlc_minimum_msat: 0,
3234 htlc_maximum_msat: OptionalField::Present(200_000),
3236 fee_proportional_millionths: 0,
3237 excess_data: Vec::new()
3239 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3240 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3241 short_channel_id: 13,
3244 cltv_expiry_delta: 0,
3245 htlc_minimum_msat: 0,
3246 htlc_maximum_msat: OptionalField::Present(200_000),
3248 fee_proportional_millionths: 0,
3249 excess_data: Vec::new()
3252 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3253 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3254 short_channel_id: 6,
3257 cltv_expiry_delta: 0,
3258 htlc_minimum_msat: 0,
3259 htlc_maximum_msat: OptionalField::Present(100_000),
3260 fee_base_msat: 1_000,
3261 fee_proportional_millionths: 0,
3262 excess_data: Vec::new()
3264 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3265 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3266 short_channel_id: 11,
3269 cltv_expiry_delta: 0,
3270 htlc_minimum_msat: 0,
3271 htlc_maximum_msat: OptionalField::Present(100_000),
3273 fee_proportional_millionths: 0,
3274 excess_data: Vec::new()
3277 // Path via {node7, node2} is channels {12, 13, 5}.
3278 // We already limited them to 200 sats (they are used twice for 100 sats).
3279 // Nothing to do here.
3282 // Now, attempt to route 180 sats.
3283 // Our algorithm should provide us with these 2 paths.
3284 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3285 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3286 assert_eq!(route.paths.len(), 2);
3288 let mut total_value_transferred_msat = 0;
3289 let mut total_paid_msat = 0;
3290 for path in &route.paths {
3291 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3292 total_value_transferred_msat += path.last().unwrap().fee_msat;
3294 total_paid_msat += hop.fee_msat;
3297 // If we paid fee, this would be higher.
3298 assert_eq!(total_value_transferred_msat, 180_000);
3299 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3300 assert_eq!(total_fees_paid, 0);
3305 fn fees_on_mpp_route_test() {
3306 // This test makes sure that MPP algorithm properly takes into account
3307 // fees charged on the channels, by making the fees impactful:
3308 // if the fee is not properly accounted for, the behavior is different.
3309 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3310 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3312 // We need a route consisting of 2 paths:
3313 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3314 // We will route 200 sats, Each path will have 100 sats capacity.
3316 // This test is not particularly stable: e.g.,
3317 // there's a way to route via {node0, node2, node4}.
3318 // It works while pathfinding is deterministic, but can be broken otherwise.
3319 // It's fine to ignore this concern for now.
3321 // Disable other potential paths.
3322 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3323 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3324 short_channel_id: 2,
3327 cltv_expiry_delta: 0,
3328 htlc_minimum_msat: 0,
3329 htlc_maximum_msat: OptionalField::Present(100_000),
3331 fee_proportional_millionths: 0,
3332 excess_data: Vec::new()
3335 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3336 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3337 short_channel_id: 7,
3340 cltv_expiry_delta: 0,
3341 htlc_minimum_msat: 0,
3342 htlc_maximum_msat: OptionalField::Present(100_000),
3344 fee_proportional_millionths: 0,
3345 excess_data: Vec::new()
3348 // Path via {node0, node2} is channels {1, 3, 5}.
3349 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3350 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3351 short_channel_id: 1,
3354 cltv_expiry_delta: 0,
3355 htlc_minimum_msat: 0,
3356 htlc_maximum_msat: OptionalField::Present(100_000),
3358 fee_proportional_millionths: 0,
3359 excess_data: Vec::new()
3361 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3362 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3363 short_channel_id: 3,
3366 cltv_expiry_delta: 0,
3367 htlc_minimum_msat: 0,
3368 htlc_maximum_msat: OptionalField::Present(100_000),
3370 fee_proportional_millionths: 0,
3371 excess_data: Vec::new()
3374 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3375 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3376 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3377 short_channel_id: 5,
3380 cltv_expiry_delta: 0,
3381 htlc_minimum_msat: 0,
3382 htlc_maximum_msat: OptionalField::Present(100_000),
3384 fee_proportional_millionths: 0,
3385 excess_data: Vec::new()
3388 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3389 // All channels should be 100 sats capacity. But for the fee experiment,
3390 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3391 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3392 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3393 // so no matter how large are other channels,
3394 // the whole path will be limited by 100 sats with just these 2 conditions:
3395 // - channel 12 capacity is 250 sats
3396 // - fee for channel 6 is 150 sats
3397 // Let's test this by enforcing these 2 conditions and removing other limits.
3398 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3399 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3400 short_channel_id: 12,
3403 cltv_expiry_delta: 0,
3404 htlc_minimum_msat: 0,
3405 htlc_maximum_msat: OptionalField::Present(250_000),
3407 fee_proportional_millionths: 0,
3408 excess_data: Vec::new()
3410 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3411 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3412 short_channel_id: 13,
3415 cltv_expiry_delta: 0,
3416 htlc_minimum_msat: 0,
3417 htlc_maximum_msat: OptionalField::Absent,
3419 fee_proportional_millionths: 0,
3420 excess_data: Vec::new()
3423 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3424 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3425 short_channel_id: 6,
3428 cltv_expiry_delta: 0,
3429 htlc_minimum_msat: 0,
3430 htlc_maximum_msat: OptionalField::Absent,
3431 fee_base_msat: 150_000,
3432 fee_proportional_millionths: 0,
3433 excess_data: Vec::new()
3435 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3436 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3437 short_channel_id: 11,
3440 cltv_expiry_delta: 0,
3441 htlc_minimum_msat: 0,
3442 htlc_maximum_msat: OptionalField::Absent,
3444 fee_proportional_millionths: 0,
3445 excess_data: Vec::new()
3449 // Attempt to route more than available results in a failure.
3450 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3451 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3452 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3453 } else { panic!(); }
3457 // Now, attempt to route 200 sats (exact amount we can route).
3458 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3459 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3460 assert_eq!(route.paths.len(), 2);
3462 let mut total_amount_paid_msat = 0;
3463 for path in &route.paths {
3464 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3465 total_amount_paid_msat += path.last().unwrap().fee_msat;
3467 assert_eq!(total_amount_paid_msat, 200_000);
3473 fn drop_lowest_channel_mpp_route_test() {
3474 // This test checks that low-capacity channel is dropped when after
3475 // path finding we realize that we found more capacity than we need.
3476 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3477 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3479 // We need a route consisting of 3 paths:
3480 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3482 // The first and the second paths should be sufficient, but the third should be
3483 // cheaper, so that we select it but drop later.
3485 // First, we set limits on these (previously unlimited) channels.
3486 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3488 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3489 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3490 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3491 short_channel_id: 1,
3494 cltv_expiry_delta: 0,
3495 htlc_minimum_msat: 0,
3496 htlc_maximum_msat: OptionalField::Present(100_000),
3498 fee_proportional_millionths: 0,
3499 excess_data: Vec::new()
3501 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3502 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3503 short_channel_id: 3,
3506 cltv_expiry_delta: 0,
3507 htlc_minimum_msat: 0,
3508 htlc_maximum_msat: OptionalField::Present(50_000),
3510 fee_proportional_millionths: 0,
3511 excess_data: Vec::new()
3514 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3515 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3517 short_channel_id: 12,
3520 cltv_expiry_delta: 0,
3521 htlc_minimum_msat: 0,
3522 htlc_maximum_msat: OptionalField::Present(60_000),
3524 fee_proportional_millionths: 0,
3525 excess_data: Vec::new()
3527 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3529 short_channel_id: 13,
3532 cltv_expiry_delta: 0,
3533 htlc_minimum_msat: 0,
3534 htlc_maximum_msat: OptionalField::Present(60_000),
3536 fee_proportional_millionths: 0,
3537 excess_data: Vec::new()
3540 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3541 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3543 short_channel_id: 2,
3546 cltv_expiry_delta: 0,
3547 htlc_minimum_msat: 0,
3548 htlc_maximum_msat: OptionalField::Present(20_000),
3550 fee_proportional_millionths: 0,
3551 excess_data: Vec::new()
3553 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3555 short_channel_id: 4,
3558 cltv_expiry_delta: 0,
3559 htlc_minimum_msat: 0,
3560 htlc_maximum_msat: OptionalField::Present(20_000),
3562 fee_proportional_millionths: 0,
3563 excess_data: Vec::new()
3567 // Attempt to route more than available results in a failure.
3568 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3569 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3570 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3571 } else { panic!(); }
3575 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3576 // Our algorithm should provide us with these 3 paths.
3577 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3578 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3579 assert_eq!(route.paths.len(), 3);
3580 let mut total_amount_paid_msat = 0;
3581 for path in &route.paths {
3582 assert_eq!(path.len(), 2);
3583 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3584 total_amount_paid_msat += path.last().unwrap().fee_msat;
3586 assert_eq!(total_amount_paid_msat, 125_000);
3590 // Attempt to route without the last small cheap channel
3591 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3592 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3593 assert_eq!(route.paths.len(), 2);
3594 let mut total_amount_paid_msat = 0;
3595 for path in &route.paths {
3596 assert_eq!(path.len(), 2);
3597 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3598 total_amount_paid_msat += path.last().unwrap().fee_msat;
3600 assert_eq!(total_amount_paid_msat, 90_000);
3605 fn min_criteria_consistency() {
3606 // Test that we don't use an inconsistent metric between updating and walking nodes during
3607 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3608 // was updated with a different criterion from the heap sorting, resulting in loops in
3609 // calculated paths. We test for that specific case here.
3611 // We construct a network that looks like this:
3613 // node2 -1(3)2- node3
3617 // node1 -1(5)2- node4 -1(1)2- node6
3623 // We create a loop on the side of our real path - our destination is node 6, with a
3624 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3625 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3626 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3627 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3628 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3629 // "previous hop" being set to node 3, creating a loop in the path.
3630 let secp_ctx = Secp256k1::new();
3631 let logger = Arc::new(test_utils::TestLogger::new());
3632 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3633 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3635 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3636 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3637 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3638 short_channel_id: 6,
3641 cltv_expiry_delta: (6 << 8) | 0,
3642 htlc_minimum_msat: 0,
3643 htlc_maximum_msat: OptionalField::Absent,
3645 fee_proportional_millionths: 0,
3646 excess_data: Vec::new()
3648 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3650 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3651 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3653 short_channel_id: 5,
3656 cltv_expiry_delta: (5 << 8) | 0,
3657 htlc_minimum_msat: 0,
3658 htlc_maximum_msat: OptionalField::Absent,
3660 fee_proportional_millionths: 0,
3661 excess_data: Vec::new()
3663 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3665 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3666 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3668 short_channel_id: 4,
3671 cltv_expiry_delta: (4 << 8) | 0,
3672 htlc_minimum_msat: 0,
3673 htlc_maximum_msat: OptionalField::Absent,
3675 fee_proportional_millionths: 0,
3676 excess_data: Vec::new()
3678 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3680 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3681 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3683 short_channel_id: 3,
3686 cltv_expiry_delta: (3 << 8) | 0,
3687 htlc_minimum_msat: 0,
3688 htlc_maximum_msat: OptionalField::Absent,
3690 fee_proportional_millionths: 0,
3691 excess_data: Vec::new()
3693 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3695 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3696 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3697 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3698 short_channel_id: 2,
3701 cltv_expiry_delta: (2 << 8) | 0,
3702 htlc_minimum_msat: 0,
3703 htlc_maximum_msat: OptionalField::Absent,
3705 fee_proportional_millionths: 0,
3706 excess_data: Vec::new()
3709 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3710 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3711 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3712 short_channel_id: 1,
3715 cltv_expiry_delta: (1 << 8) | 0,
3716 htlc_minimum_msat: 100,
3717 htlc_maximum_msat: OptionalField::Absent,
3719 fee_proportional_millionths: 0,
3720 excess_data: Vec::new()
3722 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3725 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3726 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();
3727 assert_eq!(route.paths.len(), 1);
3728 assert_eq!(route.paths[0].len(), 3);
3730 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3731 assert_eq!(route.paths[0][0].short_channel_id, 6);
3732 assert_eq!(route.paths[0][0].fee_msat, 100);
3733 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3734 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3735 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3737 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3738 assert_eq!(route.paths[0][1].short_channel_id, 5);
3739 assert_eq!(route.paths[0][1].fee_msat, 0);
3740 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3741 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3742 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3744 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3745 assert_eq!(route.paths[0][2].short_channel_id, 1);
3746 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3747 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3748 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3749 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3755 fn exact_fee_liquidity_limit() {
3756 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3757 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3758 // we calculated fees on a higher value, resulting in us ignoring such paths.
3759 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3760 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3762 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3764 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3765 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3766 short_channel_id: 2,
3769 cltv_expiry_delta: 0,
3770 htlc_minimum_msat: 0,
3771 htlc_maximum_msat: OptionalField::Present(85_000),
3773 fee_proportional_millionths: 0,
3774 excess_data: Vec::new()
3777 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3778 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3779 short_channel_id: 12,
3782 cltv_expiry_delta: (4 << 8) | 1,
3783 htlc_minimum_msat: 0,
3784 htlc_maximum_msat: OptionalField::Present(270_000),
3786 fee_proportional_millionths: 1000000,
3787 excess_data: Vec::new()
3791 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3792 // 200% fee charged channel 13 in the 1-to-2 direction.
3793 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();
3794 assert_eq!(route.paths.len(), 1);
3795 assert_eq!(route.paths[0].len(), 2);
3797 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3798 assert_eq!(route.paths[0][0].short_channel_id, 12);
3799 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3800 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3801 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3802 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3804 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3805 assert_eq!(route.paths[0][1].short_channel_id, 13);
3806 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3807 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3808 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3809 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3814 fn htlc_max_reduction_below_min() {
3815 // Test that if, while walking the graph, we reduce the value being sent to meet an
3816 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3817 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3818 // resulting in us thinking there is no possible path, even if other paths exist.
3819 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3820 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3822 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3823 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3824 // then try to send 90_000.
3825 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3826 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3827 short_channel_id: 2,
3830 cltv_expiry_delta: 0,
3831 htlc_minimum_msat: 0,
3832 htlc_maximum_msat: OptionalField::Present(80_000),
3834 fee_proportional_millionths: 0,
3835 excess_data: Vec::new()
3837 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3838 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3839 short_channel_id: 4,
3842 cltv_expiry_delta: (4 << 8) | 1,
3843 htlc_minimum_msat: 90_000,
3844 htlc_maximum_msat: OptionalField::Absent,
3846 fee_proportional_millionths: 0,
3847 excess_data: Vec::new()
3851 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3852 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3853 // expensive) channels 12-13 path.
3854 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();
3855 assert_eq!(route.paths.len(), 1);
3856 assert_eq!(route.paths[0].len(), 2);
3858 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3859 assert_eq!(route.paths[0][0].short_channel_id, 12);
3860 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3861 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3862 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3863 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3865 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3866 assert_eq!(route.paths[0][1].short_channel_id, 13);
3867 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3868 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3869 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3870 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3874 pub(super) fn random_init_seed() -> u64 {
3875 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3876 use core::hash::{BuildHasher, Hasher};
3877 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3878 println!("Using seed of {}", seed);
3881 use util::ser::Readable;
3884 fn generate_routes() {
3885 let mut d = match super::test_utils::get_route_file() {
3892 let graph = NetworkGraph::read(&mut d).unwrap();
3894 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3895 let mut seed = random_init_seed() as usize;
3896 'load_endpoints: for _ in 0..10 {
3898 seed = seed.overflowing_mul(0xdeadbeef).0;
3899 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3900 seed = seed.overflowing_mul(0xdeadbeef).0;
3901 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3902 let amt = seed as u64 % 200_000_000;
3903 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3904 continue 'load_endpoints;
3911 fn generate_routes_mpp() {
3912 let mut d = match super::test_utils::get_route_file() {
3919 let graph = NetworkGraph::read(&mut d).unwrap();
3921 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3922 let mut seed = random_init_seed() as usize;
3923 'load_endpoints: for _ in 0..10 {
3925 seed = seed.overflowing_mul(0xdeadbeef).0;
3926 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3927 seed = seed.overflowing_mul(0xdeadbeef).0;
3928 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3929 let amt = seed as u64 % 200_000_000;
3930 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3931 continue 'load_endpoints;
3939 pub(crate) mod test_utils {
3941 /// Tries to open a network graph file, or panics with a URL to fetch it.
3942 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
3943 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
3944 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
3945 .or_else(|_| { // Fall back to guessing based on the binary location
3946 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3947 let mut path = std::env::current_exe().unwrap();
3948 path.pop(); // lightning-...
3950 path.pop(); // debug
3951 path.pop(); // target
3952 path.push("lightning");
3953 path.push("net_graph-2021-05-31.bin");
3954 eprintln!("{}", path.to_str().unwrap());
3957 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.15-2021-05-31.bin and place it at lightning/net_graph-2021-05-31.bin");
3958 #[cfg(require_route_graph_test)]
3959 return Ok(res.unwrap());
3960 #[cfg(not(require_route_graph_test))]
3965 #[cfg(all(test, feature = "unstable"))]
3968 use util::logger::{Logger, Record};
3972 struct DummyLogger {}
3973 impl Logger for DummyLogger {
3974 fn log(&self, _record: &Record) {}
3978 fn generate_routes(bench: &mut Bencher) {
3979 let mut d = test_utils::get_route_file().unwrap();
3980 let graph = NetworkGraph::read(&mut d).unwrap();
3982 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3983 let mut path_endpoints = Vec::new();
3984 let mut seed: usize = 0xdeadbeef;
3985 'load_endpoints: for _ in 0..100 {
3988 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3990 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3991 let amt = seed as u64 % 1_000_000;
3992 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3993 path_endpoints.push((src, dst, amt));
3994 continue 'load_endpoints;
3999 // ...then benchmark finding paths between the nodes we learned.
4002 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4003 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
4009 fn generate_mpp_routes(bench: &mut Bencher) {
4010 let mut d = test_utils::get_route_file().unwrap();
4011 let graph = NetworkGraph::read(&mut d).unwrap();
4013 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4014 let mut path_endpoints = Vec::new();
4015 let mut seed: usize = 0xdeadbeef;
4016 'load_endpoints: for _ in 0..100 {
4019 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4021 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4022 let amt = seed as u64 % 1_000_000;
4023 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4024 path_endpoints.push((src, dst, amt));
4025 continue 'load_endpoints;
4030 // ...then benchmark finding paths between the nodes we learned.
4033 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4034 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());