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,
53 impl Writeable for Vec<RouteHop> {
54 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
55 (self.len() as u8).write(writer)?;
56 for hop in self.iter() {
57 hop.pubkey.write(writer)?;
58 hop.node_features.write(writer)?;
59 hop.short_channel_id.write(writer)?;
60 hop.channel_features.write(writer)?;
61 hop.fee_msat.write(writer)?;
62 hop.cltv_expiry_delta.write(writer)?;
69 impl Readable for Vec<RouteHop> {
70 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
71 let hops_count: u8 = Readable::read(reader)?;
72 let mut hops = Vec::with_capacity(hops_count as usize);
73 for _ in 0..hops_count {
75 pubkey: Readable::read(reader)?,
76 node_features: Readable::read(reader)?,
77 short_channel_id: Readable::read(reader)?,
78 channel_features: Readable::read(reader)?,
79 fee_msat: Readable::read(reader)?,
80 cltv_expiry_delta: Readable::read(reader)?,
87 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
88 /// it can take multiple paths. Each path is composed of one or more hops through the network.
89 #[derive(Clone, PartialEq)]
91 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
92 /// last RouteHop in each path must be the same.
93 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
94 /// destination. Thus, this must always be at least length one. While the maximum length of any
95 /// given path is variable, keeping the length of any path to less than 20 should currently
96 /// ensure it is viable.
97 pub paths: Vec<Vec<RouteHop>>,
100 const SERIALIZATION_VERSION: u8 = 1;
101 const MIN_SERIALIZATION_VERSION: u8 = 1;
103 impl Writeable for Route {
104 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
105 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
106 (self.paths.len() as u64).write(writer)?;
107 for hops in self.paths.iter() {
110 write_tlv_fields!(writer, {}, {});
115 impl Readable for Route {
116 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
117 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
118 let path_count: u64 = Readable::read(reader)?;
119 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
120 for _ in 0..path_count {
121 paths.push(Readable::read(reader)?);
123 read_tlv_fields!(reader, {}, {});
128 /// A channel descriptor which provides a last-hop route to get_route
129 #[derive(Eq, PartialEq, Debug, Clone)]
130 pub struct RouteHintHop {
131 /// The node_id of the non-target end of the route
132 pub src_node_id: PublicKey,
133 /// The short_channel_id of this channel
134 pub short_channel_id: u64,
135 /// The fees which must be paid to use this channel
136 pub fees: RoutingFees,
137 /// The difference in CLTV values between this node and the next node.
138 pub cltv_expiry_delta: u16,
139 /// The minimum value, in msat, which must be relayed to the next hop.
140 pub htlc_minimum_msat: Option<u64>,
141 /// The maximum value in msat available for routing with a single HTLC.
142 pub htlc_maximum_msat: Option<u64>,
145 #[derive(Eq, PartialEq)]
146 struct RouteGraphNode {
148 lowest_fee_to_peer_through_node: u64,
149 lowest_fee_to_node: u64,
150 // The maximum value a yet-to-be-constructed payment path might flow through this node.
151 // This value is upper-bounded by us by:
152 // - how much is needed for a path being constructed
153 // - how much value can channels following this node (up to the destination) can contribute,
154 // considering their capacity and fees
155 value_contribution_msat: u64,
156 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
157 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
158 path_htlc_minimum_msat: u64,
161 impl cmp::Ord for RouteGraphNode {
162 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
163 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat);
164 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat);
165 other_score.cmp(&self_score).then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
169 impl cmp::PartialOrd for RouteGraphNode {
170 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
171 Some(self.cmp(other))
175 struct DummyDirectionalChannelInfo {
176 cltv_expiry_delta: u32,
177 htlc_minimum_msat: u64,
178 htlc_maximum_msat: Option<u64>,
182 /// It's useful to keep track of the hops associated with the fees required to use them,
183 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
184 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
185 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
187 struct PathBuildingHop<'a> {
188 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
189 // Note that node_features is calculated separately after our initial graph walk.
191 short_channel_id: u64,
192 channel_features: &'a ChannelFeatures,
194 cltv_expiry_delta: u32,
196 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
197 src_lowest_inbound_fees: RoutingFees,
198 /// Fees of the channel used in this hop.
199 channel_fees: RoutingFees,
200 /// All the fees paid *after* this channel on the way to the destination
201 next_hops_fee_msat: u64,
202 /// Fee paid for the use of the current channel (see channel_fees).
203 /// The value will be actually deducted from the counterparty balance on the previous link.
204 hop_use_fee_msat: u64,
205 /// Used to compare channels when choosing the for routing.
206 /// Includes paying for the use of a hop and the following hops, as well as
207 /// an estimated cost of reaching this hop.
208 /// Might get stale when fees are recomputed. Primarily for internal use.
210 /// This is useful for update_value_and_recompute_fees to make sure
211 /// we don't fall below the minimum. Should not be updated manually and
212 /// generally should not be accessed.
213 htlc_minimum_msat: u64,
214 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
215 /// walk and may be invalid thereafter.
216 path_htlc_minimum_msat: u64,
217 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
218 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
219 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
220 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
221 /// avoid processing them again.
223 #[cfg(any(test, feature = "fuzztarget"))]
224 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
225 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
226 // value_contribution_msat, which requires tracking it here. See comments below where it is
227 // used for more info.
228 value_contribution_msat: u64,
231 // Instantiated with a list of hops with correct data in them collected during path finding,
232 // an instance of this struct should be further modified only via given methods.
234 struct PaymentPath<'a> {
235 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
238 impl<'a> PaymentPath<'a> {
239 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
240 fn get_value_msat(&self) -> u64 {
241 self.hops.last().unwrap().0.fee_msat
244 fn get_total_fee_paid_msat(&self) -> u64 {
245 if self.hops.len() < 1 {
249 // Can't use next_hops_fee_msat because it gets outdated.
250 for (i, (hop, _)) in self.hops.iter().enumerate() {
251 if i != self.hops.len() - 1 {
252 result += hop.fee_msat;
258 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
259 // to change fees may result in an inconsistency.
261 // Sometimes we call this function right after constructing a path which is inconsistent in
262 // that it the value being transferred has decreased while we were doing path finding, leading
263 // to the fees being paid not lining up with the actual limits.
265 // Note that this function is not aware of the available_liquidity limit, and thus does not
266 // support increasing the value being transferred.
267 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
268 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
270 let mut total_fee_paid_msat = 0 as u64;
271 for i in (0..self.hops.len()).rev() {
272 let last_hop = i == self.hops.len() - 1;
274 // For non-last-hop, this value will represent the fees paid on the current hop. It
275 // will consist of the fees for the use of the next hop, and extra fees to match
276 // htlc_minimum_msat of the current channel. Last hop is handled separately.
277 let mut cur_hop_fees_msat = 0;
279 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
282 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
283 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
284 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
285 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
286 // set it too high just to maliciously take more fees by exploiting this
287 // match htlc_minimum_msat logic.
288 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
289 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
290 // Note that there is a risk that *previous hops* (those closer to us, as we go
291 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
293 // This might make us end up with a broken route, although this should be super-rare
294 // in practice, both because of how healthy channels look like, and how we pick
295 // channels in add_entry.
296 // Also, this can't be exploited more heavily than *announce a free path and fail
298 cur_hop_transferred_amount_msat += extra_fees_msat;
299 total_fee_paid_msat += extra_fees_msat;
300 cur_hop_fees_msat += extra_fees_msat;
304 // Final hop is a special case: it usually has just value_msat (by design), but also
305 // it still could overpay for the htlc_minimum_msat.
306 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
308 // Propagate updated fees for the use of the channels to one hop back, where they
309 // will be actually paid (fee_msat). The last hop is handled above separately.
310 cur_hop.fee_msat = cur_hop_fees_msat;
313 // Fee for the use of the current hop which will be deducted on the previous hop.
314 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
315 // this channel is free for us.
317 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
318 cur_hop.hop_use_fee_msat = new_fee;
319 total_fee_paid_msat += new_fee;
321 // It should not be possible because this function is called only to reduce the
322 // value. In that case, compute_fee was already called with the same fees for
323 // larger amount and there was no overflow.
331 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
332 let proportional_fee_millions =
333 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
334 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
335 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
339 // This function may be (indirectly) called without any verification,
340 // with channel_fees provided by a caller. We should handle it gracefully.
345 /// Gets a route from us (payer) to the given target node (payee).
347 /// If the payee provided features in their invoice, they should be provided via payee_features.
348 /// Without this, MPP will only be used if the payee's features are available in the network graph.
350 /// Extra routing hops between known nodes and the target will be used if they are included in
353 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
354 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
355 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
356 /// in first_hops will be used.
358 /// Panics if first_hops contains channels without short_channel_ids
359 /// (ChannelManager::list_usable_channels will never include such channels).
361 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
362 /// equal), however the enabled/disabled bit on such channels as well as the
363 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
364 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, payee_features: Option<InvoiceFeatures>, first_hops: Option<&[&ChannelDetails]>,
365 last_hops: &[&RouteHintHop], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
366 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
367 // uptime/success in using a node in the past.
368 if *payee == *our_node_id {
369 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
372 if final_value_msat > MAX_VALUE_MSAT {
373 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
376 if final_value_msat == 0 {
377 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
380 for last_hop in last_hops {
381 if last_hop.src_node_id == *payee {
382 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
386 // The general routing idea is the following:
387 // 1. Fill first/last hops communicated by the caller.
388 // 2. Attempt to construct a path from payer to payee for transferring
389 // any ~sufficient (described later) value.
390 // If succeed, remember which channels were used and how much liquidity they have available,
391 // so that future paths don't rely on the same liquidity.
392 // 3. Prooceed to the next step if:
393 // - we hit the recommended target value;
394 // - OR if we could not construct a new path. Any next attempt will fail too.
395 // Otherwise, repeat step 2.
396 // 4. See if we managed to collect paths which aggregately are able to transfer target value
397 // (not recommended value). If yes, proceed. If not, fail routing.
398 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
399 // 6. Of all the found paths, select only those with the lowest total fee.
400 // 7. The last path in every selected route is likely to be more than we need.
401 // Reduce its value-to-transfer and recompute fees.
402 // 8. Choose the best route by the lowest total fee.
404 // As for the actual search algorithm,
405 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
406 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
408 // We are not a faithful Dijkstra's implementation because we can change values which impact
409 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
410 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
411 // the value we are currently attempting to send over a path, we simply reduce the value being
412 // sent along the path for any hops after that channel. This may imply that later fees (which
413 // we've already tabulated) are lower because a smaller value is passing through the channels
414 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
415 // channels which were selected earlier (and which may still be used for other paths without a
416 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
419 // One potentially problematic case for this algorithm would be if there are many
420 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
421 // graph walking), we may never find a path which is not liquidity-limited and has lower
422 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
423 // Because we only consider paths with at least 5% of the total value being sent, the damage
424 // from such a case should be limited, however this could be further reduced in the future by
425 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
426 // limits for the purposes of fee calculation.
428 // Alternatively, we could store more detailed path information in the heap (targets, below)
429 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
430 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
431 // and practically (as we would need to store dynamically-allocated path information in heap
432 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
433 // results of such an algorithm would likely be biased towards lower-value paths.
435 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
436 // outside of our current search value, running a path search more times to gather candidate
437 // paths at different values. While this may be acceptable, further path searches may increase
438 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
439 // graph for candidate paths, calculating the maximum value which can realistically be sent at
440 // the same time, remaining generic across different payment values.
442 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
443 // to use as the A* heuristic beyond just the cost to get one node further than the current
446 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
447 cltv_expiry_delta: 0,
448 htlc_minimum_msat: 0,
449 htlc_maximum_msat: None,
452 proportional_millionths: 0,
456 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
457 // it. If the payee supports it they're supposed to include it in the invoice, so that should
459 let allow_mpp = if let Some(features) = &payee_features {
460 features.supports_basic_mpp()
461 } else if let Some(node) = network.get_nodes().get(&payee) {
462 if let Some(node_info) = node.announcement_info.as_ref() {
463 node_info.features.supports_basic_mpp()
468 // Prepare the data we'll use for payee-to-payer search by
469 // inserting first hops suggested by the caller as targets.
470 // Our search will then attempt to reach them while traversing from the payee node.
471 let mut first_hop_targets: HashMap<_, (_, ChannelFeatures, _, NodeFeatures)> =
472 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
473 if let Some(hops) = first_hops {
475 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
476 if chan.remote_network_id == *our_node_id {
477 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
479 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()));
481 if first_hop_targets.is_empty() {
482 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
486 let empty_channel_features = ChannelFeatures::empty();
488 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
489 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
490 // adding duplicate entries when we find a better path to a given node.
491 let mut targets = BinaryHeap::new();
493 // Map from node_id to information about the best current path to that node, including feerate
495 let mut dist = HashMap::with_capacity(network.get_nodes().len());
497 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
498 // indicating that we may wish to try again with a higher value, potentially paying to meet an
499 // htlc_minimum with extra fees while still finding a cheaper path.
500 let mut hit_minimum_limit;
502 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
503 // We start with a path_value of the exact amount we want, and if that generates a route we may
504 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
505 // amount we want in total across paths, selecting the best subset at the end.
506 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
507 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
508 let mut path_value_msat = final_value_msat;
510 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
511 // This map allows paths to be aware of the channel use by other paths in the same call.
512 // This would help to make a better path finding decisions and not "overbook" channels.
513 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
514 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network.get_nodes().len());
516 // Keeping track of how much value we already collected across other paths. Helps to decide:
517 // - how much a new path should be transferring (upper bound);
518 // - whether a channel should be disregarded because
519 // it's available liquidity is too small comparing to how much more we need to collect;
520 // - when we want to stop looking for new paths.
521 let mut already_collected_value_msat = 0;
523 macro_rules! add_entry {
524 // Adds entry which goes from $src_node_id to $dest_node_id
525 // over the channel with id $chan_id with fees described in
526 // $directional_info.
527 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
528 // since that value has to be transferred over this channel.
529 ( $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,
530 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
531 // Channels to self should not be used. This is more of belt-and-suspenders, because in
532 // practice these cases should be caught earlier:
533 // - for regular channels at channel announcement (TODO)
534 // - for first and last hops early in get_route
535 if $src_node_id != $dest_node_id.clone() {
536 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
537 let mut initial_liquidity_available_msat = None;
538 if let Some(capacity_sats) = $capacity_sats {
539 initial_liquidity_available_msat = Some(capacity_sats * 1000);
542 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
543 if let Some(available_msat) = initial_liquidity_available_msat {
544 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
546 initial_liquidity_available_msat = Some(htlc_maximum_msat);
550 match initial_liquidity_available_msat {
551 Some(available_msat) => available_msat,
552 // We assume channels with unknown balance have
553 // a capacity of 0.0025 BTC (or 250_000 sats).
554 None => 250_000 * 1000
558 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
559 // It may be misleading because we might later choose to reduce the value transferred
560 // over these channels, and the channel which was insufficient might become sufficient.
561 // Worst case: we drop a good channel here because it can't cover the high following
562 // fees caused by one expensive channel, but then this channel could have been used
563 // if the amount being transferred over this path is lower.
564 // We do this for now, but this is a subject for removal.
565 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
567 // Routing Fragmentation Mitigation heuristic:
569 // Routing fragmentation across many payment paths increases the overall routing
570 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
571 // Taking too many smaller paths also increases the chance of payment failure.
572 // Thus to avoid this effect, we require from our collected links to provide
573 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
575 // This requirement is currently 5% of the remaining-to-be-collected value.
576 // This means as we successfully advance in our collection,
577 // the absolute liquidity contribution is lowered,
578 // thus increasing the number of potential channels to be selected.
580 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
581 // or 100% if we're not allowed to do multipath payments.
582 let minimal_value_contribution_msat: u64 = if allow_mpp {
583 (recommended_value_msat - already_collected_value_msat + 19) / 20
587 // Verify the liquidity offered by this channel complies to the minimal contribution.
588 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
590 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
591 // Includes paying fees for the use of the following channels.
592 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
593 Some(result) => result,
594 // Can't overflow due to how the values were computed right above.
595 None => unreachable!(),
597 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
598 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
599 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
601 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
602 // bother considering this channel.
603 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
604 // be only reduced later (not increased), so this channel should just be skipped
605 // as not sufficient.
606 if !over_path_minimum_msat {
607 hit_minimum_limit = true;
608 } else if contributes_sufficient_value {
609 // Note that low contribution here (limited by available_liquidity_msat)
610 // might violate htlc_minimum_msat on the hops which are next along the
611 // payment path (upstream to the payee). To avoid that, we recompute path
612 // path fees knowing the final path contribution after constructing it.
613 let path_htlc_minimum_msat = match compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
614 .map(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat)) {
615 Some(Some(value_msat)) => cmp::max(value_msat, $directional_info.htlc_minimum_msat),
616 _ => u64::max_value()
618 let hm_entry = dist.entry(&$src_node_id);
619 let old_entry = hm_entry.or_insert_with(|| {
620 // If there was previously no known way to access
621 // the source node (recall it goes payee-to-payer) of $chan_id, first add
622 // a semi-dummy record just to compute the fees to reach the source node.
623 // This will affect our decision on selecting $chan_id
624 // as a way to reach the $dest_node_id.
625 let mut fee_base_msat = u32::max_value();
626 let mut fee_proportional_millionths = u32::max_value();
627 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
628 fee_base_msat = fees.base_msat;
629 fee_proportional_millionths = fees.proportional_millionths;
632 pubkey: $dest_node_id.clone(),
634 channel_features: $chan_features,
636 cltv_expiry_delta: 0,
637 src_lowest_inbound_fees: RoutingFees {
638 base_msat: fee_base_msat,
639 proportional_millionths: fee_proportional_millionths,
641 channel_fees: $directional_info.fees,
642 next_hops_fee_msat: u64::max_value(),
643 hop_use_fee_msat: u64::max_value(),
644 total_fee_msat: u64::max_value(),
645 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
646 path_htlc_minimum_msat,
647 was_processed: false,
648 #[cfg(any(test, feature = "fuzztarget"))]
649 value_contribution_msat,
653 #[allow(unused_mut)] // We only use the mut in cfg(test)
654 let mut should_process = !old_entry.was_processed;
655 #[cfg(any(test, feature = "fuzztarget"))]
657 // In test/fuzzing builds, we do extra checks to make sure the skipping
658 // of already-seen nodes only happens in cases we expect (see below).
659 if !should_process { should_process = true; }
663 let mut hop_use_fee_msat = 0;
664 let mut total_fee_msat = $next_hops_fee_msat;
666 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
667 // will have the same effective-fee
668 if $src_node_id != *our_node_id {
669 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
670 // max_value means we'll always fail
671 // the old_entry.total_fee_msat > total_fee_msat check
672 None => total_fee_msat = u64::max_value(),
674 hop_use_fee_msat = fee_msat;
675 total_fee_msat += hop_use_fee_msat;
676 // When calculating the lowest inbound fees to a node, we
677 // calculate fees here not based on the actual value we think
678 // will flow over this channel, but on the minimum value that
679 // we'll accept flowing over it. The minimum accepted value
680 // is a constant through each path collection run, ensuring
681 // consistent basis. Otherwise we may later find a
682 // different path to the source node that is more expensive,
683 // but which we consider to be cheaper because we are capacity
684 // constrained and the relative fee becomes lower.
685 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
686 .map(|a| a.checked_add(total_fee_msat)) {
691 total_fee_msat = u64::max_value();
698 let new_graph_node = RouteGraphNode {
699 pubkey: $src_node_id,
700 lowest_fee_to_peer_through_node: total_fee_msat,
701 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
702 value_contribution_msat: value_contribution_msat,
703 path_htlc_minimum_msat,
706 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
707 // if this way is cheaper than the already known
708 // (considering the cost to "reach" this channel from the route destination,
709 // the cost of using this channel,
710 // and the cost of routing to the source node of this channel).
711 // Also, consider that htlc_minimum_msat_difference, because we might end up
712 // paying it. Consider the following exploit:
713 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
714 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
715 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
716 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
718 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
719 // but it may require additional tracking - we don't want to double-count
720 // the fees included in $next_hops_path_htlc_minimum_msat, but also
721 // can't use something that may decrease on future hops.
722 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat);
723 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat);
725 if !old_entry.was_processed && new_cost < old_cost {
726 targets.push(new_graph_node);
727 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
728 old_entry.hop_use_fee_msat = hop_use_fee_msat;
729 old_entry.total_fee_msat = total_fee_msat;
730 old_entry.pubkey = $dest_node_id.clone();
731 old_entry.short_channel_id = $chan_id.clone();
732 old_entry.channel_features = $chan_features;
733 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
734 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
735 old_entry.channel_fees = $directional_info.fees;
736 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
737 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
738 #[cfg(any(test, feature = "fuzztarget"))]
740 old_entry.value_contribution_msat = value_contribution_msat;
742 } else if old_entry.was_processed && new_cost < old_cost {
743 #[cfg(any(test, feature = "fuzztarget"))]
745 // If we're skipping processing a node which was previously
746 // processed even though we found another path to it with a
747 // cheaper fee, check that it was because the second path we
748 // found (which we are processing now) has a lower value
749 // contribution due to an HTLC minimum limit.
751 // e.g. take a graph with two paths from node 1 to node 2, one
752 // through channel A, and one through channel B. Channel A and
753 // B are both in the to-process heap, with their scores set by
754 // a higher htlc_minimum than fee.
755 // Channel A is processed first, and the channels onwards from
756 // node 1 are added to the to-process heap. Thereafter, we pop
757 // Channel B off of the heap, note that it has a much more
758 // restrictive htlc_maximum_msat, and recalculate the fees for
759 // all of node 1's channels using the new, reduced, amount.
761 // This would be bogus - we'd be selecting a higher-fee path
762 // with a lower htlc_maximum_msat instead of the one we'd
763 // already decided to use.
764 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
765 debug_assert!(value_contribution_msat < old_entry.value_contribution_msat);
775 let empty_node_features = NodeFeatures::empty();
776 // Find ways (channels with destination) to reach a given node and store them
777 // in the corresponding data structures (routing graph etc).
778 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
779 // meaning how much will be paid in fees after this node (to the best of our knowledge).
780 // This data can later be helpful to optimize routing (pay lower fees).
781 macro_rules! add_entries_to_cheapest_to_target_node {
782 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr ) => {
783 let skip_node = if let Some(elem) = dist.get_mut($node_id) {
784 let was_processed = elem.was_processed;
785 elem.was_processed = true;
788 // Entries are added to dist in add_entry!() when there is a channel from a node.
789 // Because there are no channels from payee, it will not have a dist entry at this point.
790 // If we're processing any other node, it is always be the result of a channel from it.
791 assert_eq!($node_id, payee);
796 if first_hops.is_some() {
797 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&$node_id) {
798 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);
802 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
808 if !features.requires_unknown_bits() {
809 for chan_id in $node.channels.iter() {
810 let chan = network.get_channels().get(chan_id).unwrap();
811 if !chan.features.requires_unknown_bits() {
812 if chan.node_one == *$node_id {
813 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
814 if first_hops.is_none() || chan.node_two != *our_node_id {
815 if let Some(two_to_one) = chan.two_to_one.as_ref() {
816 if two_to_one.enabled {
817 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);
822 if first_hops.is_none() || chan.node_one != *our_node_id {
823 if let Some(one_to_two) = chan.one_to_two.as_ref() {
824 if one_to_two.enabled {
825 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);
837 let mut payment_paths = Vec::<PaymentPath>::new();
839 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
840 'paths_collection: loop {
841 // For every new path, start from scratch, except
842 // bookkeeped_channels_liquidity_available_msat, which will improve
843 // the further iterations of path finding. Also don't erase first_hop_targets.
846 hit_minimum_limit = false;
848 // If first hop is a private channel and the only way to reach the payee, this is the only
849 // place where it could be added.
850 if first_hops.is_some() {
851 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&payee) {
852 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0);
856 // Add the payee as a target, so that the payee-to-payer
857 // search algorithm knows what to start with.
858 match network.get_nodes().get(payee) {
859 // The payee is not in our network graph, so nothing to add here.
860 // There is still a chance of reaching them via last_hops though,
861 // so don't yet fail the payment here.
862 // If not, targets.pop() will not even let us enter the loop in step 2.
865 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0);
870 // If a caller provided us with last hops, add them to routing targets. Since this happens
871 // earlier than general path finding, they will be somewhat prioritized, although currently
872 // it matters only if the fees are exactly the same.
873 for hop in last_hops.iter() {
874 let have_hop_src_in_graph =
875 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat, _)) = first_hop_targets.get(&hop.src_node_id) {
876 // If this hop connects to a node with which we have a direct channel, ignore
877 // the network graph and add both the hop and our direct channel to
878 // the candidate set.
880 // Currently there are no channel-context features defined, so we are a
881 // bit lazy here. In the future, we should pull them out via our
882 // ChannelManager, but there's no reason to waste the space until we
884 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);
887 // In any other case, only add the hop if the source is in the regular network
889 network.get_nodes().get(&hop.src_node_id).is_some()
891 if have_hop_src_in_graph {
892 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
893 // really sucks, cause we're gonna need that eventually.
894 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
895 Some(htlc_minimum_msat) => htlc_minimum_msat,
898 let directional_info = DummyDirectionalChannelInfo {
899 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
900 htlc_minimum_msat: last_hop_htlc_minimum_msat,
901 htlc_maximum_msat: hop.htlc_maximum_msat,
904 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, &empty_channel_features, 0, path_value_msat, 0);
908 // At this point, targets are filled with the data from first and
909 // last hops communicated by the caller, and the payment receiver.
910 let mut found_new_path = false;
913 // If this loop terminates due the exhaustion of targets, two situations are possible:
914 // - not enough outgoing liquidity:
915 // 0 < already_collected_value_msat < final_value_msat
916 // - enough outgoing liquidity:
917 // final_value_msat <= already_collected_value_msat < recommended_value_msat
918 // Both these cases (and other cases except reaching recommended_value_msat) mean that
919 // paths_collection will be stopped because found_new_path==false.
920 // This is not necessarily a routing failure.
921 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, .. }) = targets.pop() {
923 // Since we're going payee-to-payer, hitting our node as a target means we should stop
924 // traversing the graph and arrange the path out of what we found.
925 if pubkey == *our_node_id {
926 let mut new_entry = dist.remove(&our_node_id).unwrap();
927 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
930 if let Some(&(_, _, _, ref features)) = first_hop_targets.get(&ordered_hops.last().unwrap().0.pubkey) {
931 ordered_hops.last_mut().unwrap().1 = features.clone();
932 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().0.pubkey) {
933 if let Some(node_info) = node.announcement_info.as_ref() {
934 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
936 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
939 // We should be able to fill in features for everything except the last
940 // hop, if the last hop was provided via a BOLT 11 invoice (though we
941 // should be able to extend it further as BOLT 11 does have feature
942 // flags for the last hop node itself).
943 assert!(ordered_hops.last().unwrap().0.pubkey == *payee);
946 // Means we succesfully traversed from the payer to the payee, now
947 // save this path for the payment route. Also, update the liquidity
948 // remaining on the used hops, so that we take them into account
949 // while looking for more paths.
950 if ordered_hops.last().unwrap().0.pubkey == *payee {
954 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.pubkey) {
955 Some(payment_hop) => payment_hop,
956 // We can't arrive at None because, if we ever add an entry to targets,
957 // we also fill in the entry in dist (see add_entry!).
958 None => unreachable!(),
960 // We "propagate" the fees one hop backward (topologically) here,
961 // so that fees paid for a HTLC forwarding on the current channel are
962 // associated with the previous channel (where they will be subtracted).
963 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
964 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
965 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
967 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
968 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
969 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv;
971 let mut payment_path = PaymentPath {hops: ordered_hops};
973 // We could have possibly constructed a slightly inconsistent path: since we reduce
974 // value being transferred along the way, we could have violated htlc_minimum_msat
975 // on some channels we already passed (assuming dest->source direction). Here, we
976 // recompute the fees again, so that if that's the case, we match the currently
977 // underpaid htlc_minimum_msat with fees.
978 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
980 // Since a path allows to transfer as much value as
981 // the smallest channel it has ("bottleneck"), we should recompute
982 // the fees so sender HTLC don't overpay fees when traversing
983 // larger channels than the bottleneck. This may happen because
984 // when we were selecting those channels we were not aware how much value
985 // this path will transfer, and the relative fee for them
986 // might have been computed considering a larger value.
987 // Remember that we used these channels so that we don't rely
988 // on the same liquidity in future paths.
989 let mut prevented_redundant_path_selection = false;
990 for (payment_hop, _) in payment_path.hops.iter() {
991 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
992 let mut spent_on_hop_msat = value_contribution_msat;
993 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
994 spent_on_hop_msat += next_hops_fee_msat;
995 if spent_on_hop_msat == *channel_liquidity_available_msat {
996 // If this path used all of this channel's available liquidity, we know
997 // this path will not be selected again in the next loop iteration.
998 prevented_redundant_path_selection = true;
1000 *channel_liquidity_available_msat -= spent_on_hop_msat;
1002 if !prevented_redundant_path_selection {
1003 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1004 // we'll probably end up picking the same path again on the next iteration.
1005 // Decrease the available liquidity of a hop in the middle of the path.
1006 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(
1007 &payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id).unwrap();
1008 *victim_liquidity = 0;
1011 // Track the total amount all our collected paths allow to send so that we:
1012 // - know when to stop looking for more paths
1013 // - know which of the hops are useless considering how much more sats we need
1014 // (contributes_sufficient_value)
1015 already_collected_value_msat += value_contribution_msat;
1017 payment_paths.push(payment_path);
1018 found_new_path = true;
1019 break 'path_construction;
1022 // If we found a path back to the payee, we shouldn't try to process it again. This is
1023 // the equivalent of the `elem.was_processed` check in
1024 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1025 if pubkey == *payee { continue 'path_construction; }
1027 // Otherwise, since the current target node is not us,
1028 // keep "unrolling" the payment graph from payee to payer by
1029 // finding a way to reach the current target from the payer side.
1030 match network.get_nodes().get(&pubkey) {
1033 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat);
1039 // If we don't support MPP, no use trying to gather more value ever.
1040 break 'paths_collection;
1044 // Stop either when the recommended value is reached or if no new path was found in this
1046 // In the latter case, making another path finding attempt won't help,
1047 // because we deterministically terminated the search due to low liquidity.
1048 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1049 break 'paths_collection;
1050 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1051 // Further, if this was our first walk of the graph, and we weren't limited by an
1052 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1053 // limited by an htlc_minimum_msat value, find another path with a higher value,
1054 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1055 // still keeping a lower total fee than this path.
1056 if !hit_minimum_limit {
1057 break 'paths_collection;
1059 path_value_msat = recommended_value_msat;
1064 if payment_paths.len() == 0 {
1065 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1068 if already_collected_value_msat < final_value_msat {
1069 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1072 // Sort by total fees and take the best paths.
1073 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1074 if payment_paths.len() > 50 {
1075 payment_paths.truncate(50);
1078 // Draw multiple sufficient routes by randomly combining the selected paths.
1079 let mut drawn_routes = Vec::new();
1080 for i in 0..payment_paths.len() {
1081 let mut cur_route = Vec::<PaymentPath>::new();
1082 let mut aggregate_route_value_msat = 0;
1085 // TODO: real random shuffle
1086 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1087 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1090 for payment_path in cur_payment_paths {
1091 cur_route.push(payment_path.clone());
1092 aggregate_route_value_msat += payment_path.get_value_msat();
1093 if aggregate_route_value_msat > final_value_msat {
1094 // Last path likely overpaid. Substract it from the most expensive
1095 // (in terms of proportional fee) path in this route and recompute fees.
1096 // This might be not the most economically efficient way, but fewer paths
1097 // also makes routing more reliable.
1098 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1100 // First, drop some expensive low-value paths entirely if possible.
1101 // Sort by value so that we drop many really-low values first, since
1102 // fewer paths is better: the payment is less likely to fail.
1103 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1104 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1105 cur_route.sort_by_key(|path| path.get_value_msat());
1106 // We should make sure that at least 1 path left.
1107 let mut paths_left = cur_route.len();
1108 cur_route.retain(|path| {
1109 if paths_left == 1 {
1112 let mut keep = true;
1113 let path_value_msat = path.get_value_msat();
1114 if path_value_msat <= overpaid_value_msat {
1116 overpaid_value_msat -= path_value_msat;
1122 if overpaid_value_msat == 0 {
1126 assert!(cur_route.len() > 0);
1129 // Now, substract the overpaid value from the most-expensive path.
1130 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1131 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1132 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1133 let expensive_payment_path = cur_route.first_mut().unwrap();
1134 // We already dropped all the small channels above, meaning all the
1135 // remaining channels are larger than remaining overpaid_value_msat.
1136 // Thus, this can't be negative.
1137 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1138 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1142 drawn_routes.push(cur_route);
1146 // Select the best route by lowest total fee.
1147 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1148 let mut selected_paths = Vec::<Vec<RouteHop>>::new();
1149 for payment_path in drawn_routes.first().unwrap() {
1150 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1152 pubkey: payment_hop.pubkey,
1153 node_features: node_features.clone(),
1154 short_channel_id: payment_hop.short_channel_id,
1155 channel_features: payment_hop.channel_features.clone(),
1156 fee_msat: payment_hop.fee_msat,
1157 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1162 if let Some(features) = &payee_features {
1163 for path in selected_paths.iter_mut() {
1164 path.last_mut().unwrap().node_features = features.to_context();
1168 let route = Route { paths: selected_paths };
1169 log_trace!(logger, "Got route: {}", log_route!(route));
1175 use routing::router::{get_route, RouteHintHop, RoutingFees};
1176 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
1177 use chain::transaction::OutPoint;
1178 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1179 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1180 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1181 use ln::channelmanager;
1182 use util::test_utils;
1183 use util::ser::Writeable;
1185 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1186 use bitcoin::hashes::Hash;
1187 use bitcoin::network::constants::Network;
1188 use bitcoin::blockdata::constants::genesis_block;
1189 use bitcoin::blockdata::script::Builder;
1190 use bitcoin::blockdata::opcodes;
1191 use bitcoin::blockdata::transaction::TxOut;
1195 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1196 use bitcoin::secp256k1::{Secp256k1, All};
1201 // Using the same keys for LN and BTC ids
1202 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1203 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1204 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1205 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1207 let unsigned_announcement = UnsignedChannelAnnouncement {
1209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1213 bitcoin_key_1: node_id_1,
1214 bitcoin_key_2: node_id_2,
1215 excess_data: Vec::new(),
1218 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1219 let valid_announcement = ChannelAnnouncement {
1220 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1221 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1222 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1223 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1224 contents: unsigned_announcement.clone(),
1226 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1227 Ok(res) => assert!(res),
1232 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) {
1233 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1234 let valid_channel_update = ChannelUpdate {
1235 signature: secp_ctx.sign(&msghash, node_privkey),
1236 contents: update.clone()
1239 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1240 Ok(res) => assert!(res),
1245 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,
1246 features: NodeFeatures, timestamp: u32) {
1247 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1248 let unsigned_announcement = UnsignedNodeAnnouncement {
1254 addresses: Vec::new(),
1255 excess_address_data: Vec::new(),
1256 excess_data: Vec::new(),
1258 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1259 let valid_announcement = NodeAnnouncement {
1260 signature: secp_ctx.sign(&msghash, node_privkey),
1261 contents: unsigned_announcement.clone()
1264 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1270 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1271 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1272 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1275 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1277 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1278 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1280 (our_privkey, our_id, privkeys, pubkeys)
1283 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1284 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1285 // test for it later.
1286 let idx = (id - 1) * 2 + 1;
1288 vec![1 << (idx - 8*3), 0, 0, 0]
1289 } else if idx > 8*2 {
1290 vec![1 << (idx - 8*2), 0, 0]
1291 } else if idx > 8*1 {
1292 vec![1 << (idx - 8*1), 0]
1298 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>) {
1299 let secp_ctx = Secp256k1::new();
1300 let logger = Arc::new(test_utils::TestLogger::new());
1301 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1302 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1303 // Build network from our_id to node7:
1305 // -1(1)2- node0 -1(3)2-
1307 // our_id -1(12)2- node7 -1(13)2--- node2
1309 // -1(2)2- node1 -1(4)2-
1312 // chan1 1-to-2: disabled
1313 // chan1 2-to-1: enabled, 0 fee
1315 // chan2 1-to-2: enabled, ignored fee
1316 // chan2 2-to-1: enabled, 0 fee
1318 // chan3 1-to-2: enabled, 0 fee
1319 // chan3 2-to-1: enabled, 100 msat fee
1321 // chan4 1-to-2: enabled, 100% fee
1322 // chan4 2-to-1: enabled, 0 fee
1324 // chan12 1-to-2: enabled, ignored fee
1325 // chan12 2-to-1: enabled, 0 fee
1327 // chan13 1-to-2: enabled, 200% fee
1328 // chan13 2-to-1: enabled, 0 fee
1331 // -1(5)2- node3 -1(8)2--
1335 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1337 // -1(7)2- node5 -1(10)2-
1339 // chan5 1-to-2: enabled, 100 msat fee
1340 // chan5 2-to-1: enabled, 0 fee
1342 // chan6 1-to-2: enabled, 0 fee
1343 // chan6 2-to-1: enabled, 0 fee
1345 // chan7 1-to-2: enabled, 100% fee
1346 // chan7 2-to-1: enabled, 0 fee
1348 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1349 // chan8 2-to-1: enabled, 0 fee
1351 // chan9 1-to-2: enabled, 1001 msat fee
1352 // chan9 2-to-1: enabled, 0 fee
1354 // chan10 1-to-2: enabled, 0 fee
1355 // chan10 2-to-1: enabled, 0 fee
1357 // chan11 1-to-2: enabled, 0 fee
1358 // chan11 2-to-1: enabled, 0 fee
1360 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1362 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1363 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1364 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1365 short_channel_id: 1,
1368 cltv_expiry_delta: 0,
1369 htlc_minimum_msat: 0,
1370 htlc_maximum_msat: OptionalField::Absent,
1372 fee_proportional_millionths: 0,
1373 excess_data: Vec::new()
1376 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1378 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1379 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1380 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1381 short_channel_id: 2,
1384 cltv_expiry_delta: u16::max_value(),
1385 htlc_minimum_msat: 0,
1386 htlc_maximum_msat: OptionalField::Absent,
1387 fee_base_msat: u32::max_value(),
1388 fee_proportional_millionths: u32::max_value(),
1389 excess_data: Vec::new()
1391 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1392 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1393 short_channel_id: 2,
1396 cltv_expiry_delta: 0,
1397 htlc_minimum_msat: 0,
1398 htlc_maximum_msat: OptionalField::Absent,
1400 fee_proportional_millionths: 0,
1401 excess_data: Vec::new()
1404 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1406 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1407 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1408 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1409 short_channel_id: 12,
1412 cltv_expiry_delta: u16::max_value(),
1413 htlc_minimum_msat: 0,
1414 htlc_maximum_msat: OptionalField::Absent,
1415 fee_base_msat: u32::max_value(),
1416 fee_proportional_millionths: u32::max_value(),
1417 excess_data: Vec::new()
1419 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1420 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1421 short_channel_id: 12,
1424 cltv_expiry_delta: 0,
1425 htlc_minimum_msat: 0,
1426 htlc_maximum_msat: OptionalField::Absent,
1428 fee_proportional_millionths: 0,
1429 excess_data: Vec::new()
1432 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1434 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1435 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1436 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1437 short_channel_id: 3,
1440 cltv_expiry_delta: (3 << 8) | 1,
1441 htlc_minimum_msat: 0,
1442 htlc_maximum_msat: OptionalField::Absent,
1444 fee_proportional_millionths: 0,
1445 excess_data: Vec::new()
1447 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1448 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1449 short_channel_id: 3,
1452 cltv_expiry_delta: (3 << 8) | 2,
1453 htlc_minimum_msat: 0,
1454 htlc_maximum_msat: OptionalField::Absent,
1456 fee_proportional_millionths: 0,
1457 excess_data: Vec::new()
1460 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1461 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1462 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1463 short_channel_id: 4,
1466 cltv_expiry_delta: (4 << 8) | 1,
1467 htlc_minimum_msat: 0,
1468 htlc_maximum_msat: OptionalField::Absent,
1470 fee_proportional_millionths: 1000000,
1471 excess_data: Vec::new()
1473 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1474 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1475 short_channel_id: 4,
1478 cltv_expiry_delta: (4 << 8) | 2,
1479 htlc_minimum_msat: 0,
1480 htlc_maximum_msat: OptionalField::Absent,
1482 fee_proportional_millionths: 0,
1483 excess_data: Vec::new()
1486 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1487 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1489 short_channel_id: 13,
1492 cltv_expiry_delta: (13 << 8) | 1,
1493 htlc_minimum_msat: 0,
1494 htlc_maximum_msat: OptionalField::Absent,
1496 fee_proportional_millionths: 2000000,
1497 excess_data: Vec::new()
1499 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1500 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1501 short_channel_id: 13,
1504 cltv_expiry_delta: (13 << 8) | 2,
1505 htlc_minimum_msat: 0,
1506 htlc_maximum_msat: OptionalField::Absent,
1508 fee_proportional_millionths: 0,
1509 excess_data: Vec::new()
1512 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1514 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1515 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1516 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1517 short_channel_id: 6,
1520 cltv_expiry_delta: (6 << 8) | 1,
1521 htlc_minimum_msat: 0,
1522 htlc_maximum_msat: OptionalField::Absent,
1524 fee_proportional_millionths: 0,
1525 excess_data: Vec::new()
1527 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1529 short_channel_id: 6,
1532 cltv_expiry_delta: (6 << 8) | 2,
1533 htlc_minimum_msat: 0,
1534 htlc_maximum_msat: OptionalField::Absent,
1536 fee_proportional_millionths: 0,
1537 excess_data: Vec::new(),
1540 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1541 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1542 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1543 short_channel_id: 11,
1546 cltv_expiry_delta: (11 << 8) | 1,
1547 htlc_minimum_msat: 0,
1548 htlc_maximum_msat: OptionalField::Absent,
1550 fee_proportional_millionths: 0,
1551 excess_data: Vec::new()
1553 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1554 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1555 short_channel_id: 11,
1558 cltv_expiry_delta: (11 << 8) | 2,
1559 htlc_minimum_msat: 0,
1560 htlc_maximum_msat: OptionalField::Absent,
1562 fee_proportional_millionths: 0,
1563 excess_data: Vec::new()
1566 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1568 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1570 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1571 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1572 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1573 short_channel_id: 7,
1576 cltv_expiry_delta: (7 << 8) | 1,
1577 htlc_minimum_msat: 0,
1578 htlc_maximum_msat: OptionalField::Absent,
1580 fee_proportional_millionths: 1000000,
1581 excess_data: Vec::new()
1583 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1584 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1585 short_channel_id: 7,
1588 cltv_expiry_delta: (7 << 8) | 2,
1589 htlc_minimum_msat: 0,
1590 htlc_maximum_msat: OptionalField::Absent,
1592 fee_proportional_millionths: 0,
1593 excess_data: Vec::new()
1596 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1598 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1602 fn simple_route_test() {
1603 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1604 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1606 // Simple route to 2 via 1
1608 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)) {
1609 assert_eq!(err, "Cannot send a payment of 0 msat");
1610 } else { panic!(); }
1612 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();
1613 assert_eq!(route.paths[0].len(), 2);
1615 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1616 assert_eq!(route.paths[0][0].short_channel_id, 2);
1617 assert_eq!(route.paths[0][0].fee_msat, 100);
1618 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1619 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1620 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1622 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1623 assert_eq!(route.paths[0][1].short_channel_id, 4);
1624 assert_eq!(route.paths[0][1].fee_msat, 100);
1625 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1626 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1627 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1631 fn invalid_first_hop_test() {
1632 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1633 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1635 // Simple route to 2 via 1
1637 let our_chans = vec![channelmanager::ChannelDetails {
1638 channel_id: [0; 32],
1639 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1640 short_channel_id: Some(2),
1641 remote_network_id: our_id,
1642 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1643 channel_value_satoshis: 100000,
1645 outbound_capacity_msat: 100000,
1646 inbound_capacity_msat: 100000,
1647 is_outbound: true, is_funding_locked: true,
1648 is_usable: true, is_public: true,
1649 counterparty_forwarding_info: None,
1652 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)) {
1653 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1654 } else { panic!(); }
1656 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();
1657 assert_eq!(route.paths[0].len(), 2);
1661 fn htlc_minimum_test() {
1662 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1663 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1665 // Simple route to 2 via 1
1667 // Disable other paths
1668 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1669 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1670 short_channel_id: 12,
1672 flags: 2, // to disable
1673 cltv_expiry_delta: 0,
1674 htlc_minimum_msat: 0,
1675 htlc_maximum_msat: OptionalField::Absent,
1677 fee_proportional_millionths: 0,
1678 excess_data: Vec::new()
1680 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1681 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1682 short_channel_id: 3,
1684 flags: 2, // to disable
1685 cltv_expiry_delta: 0,
1686 htlc_minimum_msat: 0,
1687 htlc_maximum_msat: OptionalField::Absent,
1689 fee_proportional_millionths: 0,
1690 excess_data: Vec::new()
1692 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1693 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1694 short_channel_id: 13,
1696 flags: 2, // to disable
1697 cltv_expiry_delta: 0,
1698 htlc_minimum_msat: 0,
1699 htlc_maximum_msat: OptionalField::Absent,
1701 fee_proportional_millionths: 0,
1702 excess_data: Vec::new()
1704 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1705 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1706 short_channel_id: 6,
1708 flags: 2, // to disable
1709 cltv_expiry_delta: 0,
1710 htlc_minimum_msat: 0,
1711 htlc_maximum_msat: OptionalField::Absent,
1713 fee_proportional_millionths: 0,
1714 excess_data: Vec::new()
1716 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1718 short_channel_id: 7,
1720 flags: 2, // to disable
1721 cltv_expiry_delta: 0,
1722 htlc_minimum_msat: 0,
1723 htlc_maximum_msat: OptionalField::Absent,
1725 fee_proportional_millionths: 0,
1726 excess_data: Vec::new()
1729 // Check against amount_to_transfer_over_msat.
1730 // Set minimal HTLC of 200_000_000 msat.
1731 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1732 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1733 short_channel_id: 2,
1736 cltv_expiry_delta: 0,
1737 htlc_minimum_msat: 200_000_000,
1738 htlc_maximum_msat: OptionalField::Absent,
1740 fee_proportional_millionths: 0,
1741 excess_data: Vec::new()
1744 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1746 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1748 short_channel_id: 4,
1751 cltv_expiry_delta: 0,
1752 htlc_minimum_msat: 0,
1753 htlc_maximum_msat: OptionalField::Present(199_999_999),
1755 fee_proportional_millionths: 0,
1756 excess_data: Vec::new()
1759 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1760 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)) {
1761 assert_eq!(err, "Failed to find a path to the given destination");
1762 } else { panic!(); }
1764 // Lift the restriction on the first hop.
1765 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1766 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1767 short_channel_id: 2,
1770 cltv_expiry_delta: 0,
1771 htlc_minimum_msat: 0,
1772 htlc_maximum_msat: OptionalField::Absent,
1774 fee_proportional_millionths: 0,
1775 excess_data: Vec::new()
1778 // A payment above the minimum should pass
1779 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();
1780 assert_eq!(route.paths[0].len(), 2);
1784 fn htlc_minimum_overpay_test() {
1785 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1786 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1788 // A route to node#2 via two paths.
1789 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1790 // Thus, they can't send 60 without overpaying.
1791 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1792 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1793 short_channel_id: 2,
1796 cltv_expiry_delta: 0,
1797 htlc_minimum_msat: 35_000,
1798 htlc_maximum_msat: OptionalField::Present(40_000),
1800 fee_proportional_millionths: 0,
1801 excess_data: Vec::new()
1803 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1804 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1805 short_channel_id: 12,
1808 cltv_expiry_delta: 0,
1809 htlc_minimum_msat: 35_000,
1810 htlc_maximum_msat: OptionalField::Present(40_000),
1812 fee_proportional_millionths: 0,
1813 excess_data: Vec::new()
1817 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1818 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1819 short_channel_id: 13,
1822 cltv_expiry_delta: 0,
1823 htlc_minimum_msat: 0,
1824 htlc_maximum_msat: OptionalField::Absent,
1826 fee_proportional_millionths: 0,
1827 excess_data: Vec::new()
1829 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1830 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1831 short_channel_id: 4,
1834 cltv_expiry_delta: 0,
1835 htlc_minimum_msat: 0,
1836 htlc_maximum_msat: OptionalField::Absent,
1838 fee_proportional_millionths: 0,
1839 excess_data: Vec::new()
1842 // Disable other paths
1843 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1844 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1845 short_channel_id: 1,
1847 flags: 2, // to disable
1848 cltv_expiry_delta: 0,
1849 htlc_minimum_msat: 0,
1850 htlc_maximum_msat: OptionalField::Absent,
1852 fee_proportional_millionths: 0,
1853 excess_data: Vec::new()
1856 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1857 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1858 // Overpay fees to hit htlc_minimum_msat.
1859 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1860 // TODO: this could be better balanced to overpay 10k and not 15k.
1861 assert_eq!(overpaid_fees, 15_000);
1863 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1864 // while taking even more fee to match htlc_minimum_msat.
1865 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1866 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1867 short_channel_id: 12,
1870 cltv_expiry_delta: 0,
1871 htlc_minimum_msat: 65_000,
1872 htlc_maximum_msat: OptionalField::Present(80_000),
1874 fee_proportional_millionths: 0,
1875 excess_data: Vec::new()
1877 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1878 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1879 short_channel_id: 2,
1882 cltv_expiry_delta: 0,
1883 htlc_minimum_msat: 0,
1884 htlc_maximum_msat: OptionalField::Absent,
1886 fee_proportional_millionths: 0,
1887 excess_data: Vec::new()
1889 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1890 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1891 short_channel_id: 4,
1894 cltv_expiry_delta: 0,
1895 htlc_minimum_msat: 0,
1896 htlc_maximum_msat: OptionalField::Absent,
1898 fee_proportional_millionths: 100_000,
1899 excess_data: Vec::new()
1902 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1903 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1904 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1905 assert_eq!(route.paths.len(), 1);
1906 assert_eq!(route.paths[0][0].short_channel_id, 12);
1907 let fees = route.paths[0][0].fee_msat;
1908 assert_eq!(fees, 5_000);
1910 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
1911 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1912 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1913 // the other channel.
1914 assert_eq!(route.paths.len(), 1);
1915 assert_eq!(route.paths[0][0].short_channel_id, 2);
1916 let fees = route.paths[0][0].fee_msat;
1917 assert_eq!(fees, 5_000);
1921 fn disable_channels_test() {
1922 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1923 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1925 // // Disable channels 4 and 12 by flags=2
1926 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1928 short_channel_id: 4,
1930 flags: 2, // to disable
1931 cltv_expiry_delta: 0,
1932 htlc_minimum_msat: 0,
1933 htlc_maximum_msat: OptionalField::Absent,
1935 fee_proportional_millionths: 0,
1936 excess_data: Vec::new()
1938 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1939 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1940 short_channel_id: 12,
1942 flags: 2, // to disable
1943 cltv_expiry_delta: 0,
1944 htlc_minimum_msat: 0,
1945 htlc_maximum_msat: OptionalField::Absent,
1947 fee_proportional_millionths: 0,
1948 excess_data: Vec::new()
1951 // If all the channels require some features we don't understand, route should fail
1952 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)) {
1953 assert_eq!(err, "Failed to find a path to the given destination");
1954 } else { panic!(); }
1956 // If we specify a channel to node7, that overrides our local channel view and that gets used
1957 let our_chans = vec![channelmanager::ChannelDetails {
1958 channel_id: [0; 32],
1959 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1960 short_channel_id: Some(42),
1961 remote_network_id: nodes[7].clone(),
1962 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1963 channel_value_satoshis: 0,
1965 outbound_capacity_msat: 250_000_000,
1966 inbound_capacity_msat: 0,
1967 is_outbound: true, is_funding_locked: true,
1968 is_usable: true, is_public: true,
1969 counterparty_forwarding_info: None,
1971 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1972 assert_eq!(route.paths[0].len(), 2);
1974 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1975 assert_eq!(route.paths[0][0].short_channel_id, 42);
1976 assert_eq!(route.paths[0][0].fee_msat, 200);
1977 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1978 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1979 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1981 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1982 assert_eq!(route.paths[0][1].short_channel_id, 13);
1983 assert_eq!(route.paths[0][1].fee_msat, 100);
1984 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1985 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1986 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1990 fn disable_node_test() {
1991 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1992 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1994 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1995 let mut unknown_features = NodeFeatures::known();
1996 unknown_features.set_required_unknown_bits();
1997 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1998 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1999 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2001 // If all nodes require some features we don't understand, route should fail
2002 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)) {
2003 assert_eq!(err, "Failed to find a path to the given destination");
2004 } else { panic!(); }
2006 // If we specify a channel to node7, that overrides our local channel view and that gets used
2007 let our_chans = vec![channelmanager::ChannelDetails {
2008 channel_id: [0; 32],
2009 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2010 short_channel_id: Some(42),
2011 remote_network_id: nodes[7].clone(),
2012 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2013 channel_value_satoshis: 0,
2015 outbound_capacity_msat: 250_000_000,
2016 inbound_capacity_msat: 0,
2017 is_outbound: true, is_funding_locked: true,
2018 is_usable: true, is_public: true,
2019 counterparty_forwarding_info: None,
2021 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();
2022 assert_eq!(route.paths[0].len(), 2);
2024 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2025 assert_eq!(route.paths[0][0].short_channel_id, 42);
2026 assert_eq!(route.paths[0][0].fee_msat, 200);
2027 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2028 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2029 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2031 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2032 assert_eq!(route.paths[0][1].short_channel_id, 13);
2033 assert_eq!(route.paths[0][1].fee_msat, 100);
2034 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2035 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2036 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2038 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2039 // naively) assume that the user checked the feature bits on the invoice, which override
2040 // the node_announcement.
2044 fn our_chans_test() {
2045 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2046 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2048 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2049 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();
2050 assert_eq!(route.paths[0].len(), 3);
2052 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2053 assert_eq!(route.paths[0][0].short_channel_id, 2);
2054 assert_eq!(route.paths[0][0].fee_msat, 200);
2055 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2056 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2057 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2059 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2060 assert_eq!(route.paths[0][1].short_channel_id, 4);
2061 assert_eq!(route.paths[0][1].fee_msat, 100);
2062 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2063 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2064 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2066 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2067 assert_eq!(route.paths[0][2].short_channel_id, 3);
2068 assert_eq!(route.paths[0][2].fee_msat, 100);
2069 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2070 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2071 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2073 // If we specify a channel to node7, that overrides our local channel view and that gets used
2074 let our_chans = vec![channelmanager::ChannelDetails {
2075 channel_id: [0; 32],
2076 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2077 short_channel_id: Some(42),
2078 remote_network_id: nodes[7].clone(),
2079 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2080 channel_value_satoshis: 0,
2082 outbound_capacity_msat: 250_000_000,
2083 inbound_capacity_msat: 0,
2084 is_outbound: true, is_funding_locked: true,
2085 is_usable: true, is_public: true,
2086 counterparty_forwarding_info: None,
2088 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();
2089 assert_eq!(route.paths[0].len(), 2);
2091 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2092 assert_eq!(route.paths[0][0].short_channel_id, 42);
2093 assert_eq!(route.paths[0][0].fee_msat, 200);
2094 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2095 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2096 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2098 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2099 assert_eq!(route.paths[0][1].short_channel_id, 13);
2100 assert_eq!(route.paths[0][1].fee_msat, 100);
2101 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2102 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2103 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2106 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHintHop> {
2107 let zero_fees = RoutingFees {
2109 proportional_millionths: 0,
2112 src_node_id: nodes[3].clone(),
2113 short_channel_id: 8,
2115 cltv_expiry_delta: (8 << 8) | 1,
2116 htlc_minimum_msat: None,
2117 htlc_maximum_msat: None,
2119 src_node_id: nodes[4].clone(),
2120 short_channel_id: 9,
2123 proportional_millionths: 0,
2125 cltv_expiry_delta: (9 << 8) | 1,
2126 htlc_minimum_msat: None,
2127 htlc_maximum_msat: None,
2129 src_node_id: nodes[5].clone(),
2130 short_channel_id: 10,
2132 cltv_expiry_delta: (10 << 8) | 1,
2133 htlc_minimum_msat: None,
2134 htlc_maximum_msat: None,
2139 fn last_hops_test() {
2140 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2141 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2143 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2145 // First check that lst hop can't have its source as the payee.
2146 let invalid_last_hop = RouteHintHop {
2147 src_node_id: nodes[6],
2148 short_channel_id: 8,
2151 proportional_millionths: 0,
2153 cltv_expiry_delta: (8 << 8) | 1,
2154 htlc_minimum_msat: None,
2155 htlc_maximum_msat: None,
2158 let mut invalid_last_hops = last_hops(&nodes);
2159 invalid_last_hops.push(invalid_last_hop);
2161 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)) {
2162 assert_eq!(err, "Last hop cannot have a payee as a source.");
2163 } else { panic!(); }
2166 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();
2167 assert_eq!(route.paths[0].len(), 5);
2169 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2170 assert_eq!(route.paths[0][0].short_channel_id, 2);
2171 assert_eq!(route.paths[0][0].fee_msat, 100);
2172 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2173 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2174 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2176 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2177 assert_eq!(route.paths[0][1].short_channel_id, 4);
2178 assert_eq!(route.paths[0][1].fee_msat, 0);
2179 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2180 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2181 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2183 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2184 assert_eq!(route.paths[0][2].short_channel_id, 6);
2185 assert_eq!(route.paths[0][2].fee_msat, 0);
2186 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2187 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2188 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2190 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2191 assert_eq!(route.paths[0][3].short_channel_id, 11);
2192 assert_eq!(route.paths[0][3].fee_msat, 0);
2193 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2194 // If we have a peer in the node map, we'll use their features here since we don't have
2195 // a way of figuring out their features from the invoice:
2196 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2197 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2199 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2200 assert_eq!(route.paths[0][4].short_channel_id, 8);
2201 assert_eq!(route.paths[0][4].fee_msat, 100);
2202 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2203 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2204 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2208 fn our_chans_last_hop_connect_test() {
2209 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2210 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2212 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2213 let our_chans = vec![channelmanager::ChannelDetails {
2214 channel_id: [0; 32],
2215 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2216 short_channel_id: Some(42),
2217 remote_network_id: nodes[3].clone(),
2218 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2219 channel_value_satoshis: 0,
2221 outbound_capacity_msat: 250_000_000,
2222 inbound_capacity_msat: 0,
2223 is_outbound: true, is_funding_locked: true,
2224 is_usable: true, is_public: true,
2225 counterparty_forwarding_info: None,
2227 let mut last_hops = last_hops(&nodes);
2228 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();
2229 assert_eq!(route.paths[0].len(), 2);
2231 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2232 assert_eq!(route.paths[0][0].short_channel_id, 42);
2233 assert_eq!(route.paths[0][0].fee_msat, 0);
2234 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2235 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2236 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2238 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2239 assert_eq!(route.paths[0][1].short_channel_id, 8);
2240 assert_eq!(route.paths[0][1].fee_msat, 100);
2241 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2242 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2243 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2245 last_hops[0].fees.base_msat = 1000;
2247 // Revert to via 6 as the fee on 8 goes up
2248 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();
2249 assert_eq!(route.paths[0].len(), 4);
2251 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2252 assert_eq!(route.paths[0][0].short_channel_id, 2);
2253 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2254 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2255 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2256 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2258 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2259 assert_eq!(route.paths[0][1].short_channel_id, 4);
2260 assert_eq!(route.paths[0][1].fee_msat, 100);
2261 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2262 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2263 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2265 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2266 assert_eq!(route.paths[0][2].short_channel_id, 7);
2267 assert_eq!(route.paths[0][2].fee_msat, 0);
2268 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2269 // If we have a peer in the node map, we'll use their features here since we don't have
2270 // a way of figuring out their features from the invoice:
2271 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2272 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2274 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2275 assert_eq!(route.paths[0][3].short_channel_id, 10);
2276 assert_eq!(route.paths[0][3].fee_msat, 100);
2277 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2278 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2279 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2281 // ...but still use 8 for larger payments as 6 has a variable feerate
2282 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();
2283 assert_eq!(route.paths[0].len(), 5);
2285 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2286 assert_eq!(route.paths[0][0].short_channel_id, 2);
2287 assert_eq!(route.paths[0][0].fee_msat, 3000);
2288 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2289 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2290 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2292 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2293 assert_eq!(route.paths[0][1].short_channel_id, 4);
2294 assert_eq!(route.paths[0][1].fee_msat, 0);
2295 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2296 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2297 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2299 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2300 assert_eq!(route.paths[0][2].short_channel_id, 6);
2301 assert_eq!(route.paths[0][2].fee_msat, 0);
2302 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2303 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2304 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2306 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2307 assert_eq!(route.paths[0][3].short_channel_id, 11);
2308 assert_eq!(route.paths[0][3].fee_msat, 1000);
2309 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2310 // If we have a peer in the node map, we'll use their features here since we don't have
2311 // a way of figuring out their features from the invoice:
2312 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2313 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2315 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2316 assert_eq!(route.paths[0][4].short_channel_id, 8);
2317 assert_eq!(route.paths[0][4].fee_msat, 2000);
2318 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2319 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2320 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2324 fn unannounced_path_test() {
2325 // We should be able to send a payment to a destination without any help of a routing graph
2326 // if we have a channel with a common counterparty that appears in the first and last hop
2328 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2329 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2330 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2332 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2333 let last_hops = vec![RouteHintHop {
2334 src_node_id: middle_node_id,
2335 short_channel_id: 8,
2338 proportional_millionths: 0,
2340 cltv_expiry_delta: (8 << 8) | 1,
2341 htlc_minimum_msat: None,
2342 htlc_maximum_msat: None,
2344 let our_chans = vec![channelmanager::ChannelDetails {
2345 channel_id: [0; 32],
2346 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2347 short_channel_id: Some(42),
2348 remote_network_id: middle_node_id,
2349 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2350 channel_value_satoshis: 100000,
2352 outbound_capacity_msat: 100000,
2353 inbound_capacity_msat: 100000,
2354 is_outbound: true, is_funding_locked: true,
2355 is_usable: true, is_public: true,
2356 counterparty_forwarding_info: None,
2358 let route = get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, None, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
2360 assert_eq!(route.paths[0].len(), 2);
2362 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2363 assert_eq!(route.paths[0][0].short_channel_id, 42);
2364 assert_eq!(route.paths[0][0].fee_msat, 1000);
2365 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2366 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2367 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2369 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2370 assert_eq!(route.paths[0][1].short_channel_id, 8);
2371 assert_eq!(route.paths[0][1].fee_msat, 100);
2372 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2373 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2374 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2378 fn available_amount_while_routing_test() {
2379 // Tests whether we choose the correct available channel amount while routing.
2381 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2382 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2384 // We will use a simple single-path route from
2385 // our node to node2 via node0: channels {1, 3}.
2387 // First disable all other paths.
2388 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2389 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2390 short_channel_id: 2,
2393 cltv_expiry_delta: 0,
2394 htlc_minimum_msat: 0,
2395 htlc_maximum_msat: OptionalField::Present(100_000),
2397 fee_proportional_millionths: 0,
2398 excess_data: Vec::new()
2400 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2401 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2402 short_channel_id: 12,
2405 cltv_expiry_delta: 0,
2406 htlc_minimum_msat: 0,
2407 htlc_maximum_msat: OptionalField::Present(100_000),
2409 fee_proportional_millionths: 0,
2410 excess_data: Vec::new()
2413 // Make the first channel (#1) very permissive,
2414 // and we will be testing all limits on the second channel.
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: 1,
2420 cltv_expiry_delta: 0,
2421 htlc_minimum_msat: 0,
2422 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2424 fee_proportional_millionths: 0,
2425 excess_data: Vec::new()
2428 // First, let's see if routing works if we have absolutely no idea about the available amount.
2429 // In this case, it should be set to 250_000 sats.
2430 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2431 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2432 short_channel_id: 3,
2435 cltv_expiry_delta: 0,
2436 htlc_minimum_msat: 0,
2437 htlc_maximum_msat: OptionalField::Absent,
2439 fee_proportional_millionths: 0,
2440 excess_data: Vec::new()
2444 // Attempt to route more than available results in a failure.
2445 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2446 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2447 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2448 } else { panic!(); }
2452 // Now, attempt to route an exact amount we have should be fine.
2453 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2454 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2455 assert_eq!(route.paths.len(), 1);
2456 let path = route.paths.last().unwrap();
2457 assert_eq!(path.len(), 2);
2458 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2459 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2462 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2463 // Disable channel #1 and use another first hop.
2464 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2466 short_channel_id: 1,
2469 cltv_expiry_delta: 0,
2470 htlc_minimum_msat: 0,
2471 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2473 fee_proportional_millionths: 0,
2474 excess_data: Vec::new()
2477 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2478 let our_chans = vec![channelmanager::ChannelDetails {
2479 channel_id: [0; 32],
2480 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2481 short_channel_id: Some(42),
2482 remote_network_id: nodes[0].clone(),
2483 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2484 channel_value_satoshis: 0,
2486 outbound_capacity_msat: 200_000_000,
2487 inbound_capacity_msat: 0,
2488 is_outbound: true, is_funding_locked: true,
2489 is_usable: true, is_public: true,
2490 counterparty_forwarding_info: None,
2494 // Attempt to route more than available results in a failure.
2495 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2496 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2497 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2498 } else { panic!(); }
2502 // Now, attempt to route an exact amount we have should be fine.
2503 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2504 Some(InvoiceFeatures::known()), Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2505 assert_eq!(route.paths.len(), 1);
2506 let path = route.paths.last().unwrap();
2507 assert_eq!(path.len(), 2);
2508 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2509 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2512 // Enable channel #1 back.
2513 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2514 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2515 short_channel_id: 1,
2518 cltv_expiry_delta: 0,
2519 htlc_minimum_msat: 0,
2520 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2522 fee_proportional_millionths: 0,
2523 excess_data: Vec::new()
2527 // Now let's see if routing works if we know only htlc_maximum_msat.
2528 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2529 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2530 short_channel_id: 3,
2533 cltv_expiry_delta: 0,
2534 htlc_minimum_msat: 0,
2535 htlc_maximum_msat: OptionalField::Present(15_000),
2537 fee_proportional_millionths: 0,
2538 excess_data: Vec::new()
2542 // Attempt to route more than available results in a failure.
2543 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2544 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2545 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2546 } else { panic!(); }
2550 // Now, attempt to route an exact amount we have should be fine.
2551 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2552 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2553 assert_eq!(route.paths.len(), 1);
2554 let path = route.paths.last().unwrap();
2555 assert_eq!(path.len(), 2);
2556 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2557 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2560 // Now let's see if routing works if we know only capacity from the UTXO.
2562 // We can't change UTXO capacity on the fly, so we'll disable
2563 // the existing channel and add another one with the capacity we need.
2564 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2565 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2566 short_channel_id: 3,
2569 cltv_expiry_delta: 0,
2570 htlc_minimum_msat: 0,
2571 htlc_maximum_msat: OptionalField::Absent,
2573 fee_proportional_millionths: 0,
2574 excess_data: Vec::new()
2577 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2578 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2579 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2580 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2581 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2583 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2584 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2586 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2587 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2588 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2589 short_channel_id: 333,
2592 cltv_expiry_delta: (3 << 8) | 1,
2593 htlc_minimum_msat: 0,
2594 htlc_maximum_msat: OptionalField::Absent,
2596 fee_proportional_millionths: 0,
2597 excess_data: Vec::new()
2599 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2601 short_channel_id: 333,
2604 cltv_expiry_delta: (3 << 8) | 2,
2605 htlc_minimum_msat: 0,
2606 htlc_maximum_msat: OptionalField::Absent,
2608 fee_proportional_millionths: 0,
2609 excess_data: Vec::new()
2613 // Attempt to route more than available results in a failure.
2614 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2615 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2616 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2617 } else { panic!(); }
2621 // Now, attempt to route an exact amount we have should be fine.
2622 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2623 Some(InvoiceFeatures::known()), None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2624 assert_eq!(route.paths.len(), 1);
2625 let path = route.paths.last().unwrap();
2626 assert_eq!(path.len(), 2);
2627 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2628 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2631 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2632 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2633 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2634 short_channel_id: 333,
2637 cltv_expiry_delta: 0,
2638 htlc_minimum_msat: 0,
2639 htlc_maximum_msat: OptionalField::Present(10_000),
2641 fee_proportional_millionths: 0,
2642 excess_data: Vec::new()
2646 // Attempt to route more than available results in a failure.
2647 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2648 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2649 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2650 } else { panic!(); }
2654 // Now, attempt to route an exact amount we have should be fine.
2655 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2656 Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2657 assert_eq!(route.paths.len(), 1);
2658 let path = route.paths.last().unwrap();
2659 assert_eq!(path.len(), 2);
2660 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2661 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2666 fn available_liquidity_last_hop_test() {
2667 // Check that available liquidity properly limits the path even when only
2668 // one of the latter hops is limited.
2669 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2670 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2672 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2673 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2674 // Total capacity: 50 sats.
2676 // Disable other potential paths.
2677 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2678 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2679 short_channel_id: 2,
2682 cltv_expiry_delta: 0,
2683 htlc_minimum_msat: 0,
2684 htlc_maximum_msat: OptionalField::Present(100_000),
2686 fee_proportional_millionths: 0,
2687 excess_data: Vec::new()
2689 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2690 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2691 short_channel_id: 7,
2694 cltv_expiry_delta: 0,
2695 htlc_minimum_msat: 0,
2696 htlc_maximum_msat: OptionalField::Present(100_000),
2698 fee_proportional_millionths: 0,
2699 excess_data: Vec::new()
2704 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2705 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2706 short_channel_id: 12,
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()
2716 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2717 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2718 short_channel_id: 13,
2721 cltv_expiry_delta: 0,
2722 htlc_minimum_msat: 0,
2723 htlc_maximum_msat: OptionalField::Present(100_000),
2725 fee_proportional_millionths: 0,
2726 excess_data: Vec::new()
2729 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2730 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2731 short_channel_id: 6,
2734 cltv_expiry_delta: 0,
2735 htlc_minimum_msat: 0,
2736 htlc_maximum_msat: OptionalField::Present(50_000),
2738 fee_proportional_millionths: 0,
2739 excess_data: Vec::new()
2741 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2742 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2743 short_channel_id: 11,
2746 cltv_expiry_delta: 0,
2747 htlc_minimum_msat: 0,
2748 htlc_maximum_msat: OptionalField::Present(100_000),
2750 fee_proportional_millionths: 0,
2751 excess_data: Vec::new()
2754 // Attempt to route more than available results in a failure.
2755 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2756 Some(InvoiceFeatures::known()), None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2757 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2758 } else { panic!(); }
2762 // Now, attempt to route 49 sats (just a bit below the capacity).
2763 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2764 Some(InvoiceFeatures::known()), None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2765 assert_eq!(route.paths.len(), 1);
2766 let mut total_amount_paid_msat = 0;
2767 for path in &route.paths {
2768 assert_eq!(path.len(), 4);
2769 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2770 total_amount_paid_msat += path.last().unwrap().fee_msat;
2772 assert_eq!(total_amount_paid_msat, 49_000);
2776 // Attempt to route an exact amount is also fine
2777 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
2778 Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2779 assert_eq!(route.paths.len(), 1);
2780 let mut total_amount_paid_msat = 0;
2781 for path in &route.paths {
2782 assert_eq!(path.len(), 4);
2783 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2784 total_amount_paid_msat += path.last().unwrap().fee_msat;
2786 assert_eq!(total_amount_paid_msat, 50_000);
2791 fn ignore_fee_first_hop_test() {
2792 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2793 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2795 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2796 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2797 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2798 short_channel_id: 1,
2801 cltv_expiry_delta: 0,
2802 htlc_minimum_msat: 0,
2803 htlc_maximum_msat: OptionalField::Present(100_000),
2804 fee_base_msat: 1_000_000,
2805 fee_proportional_millionths: 0,
2806 excess_data: Vec::new()
2808 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2809 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2810 short_channel_id: 3,
2813 cltv_expiry_delta: 0,
2814 htlc_minimum_msat: 0,
2815 htlc_maximum_msat: OptionalField::Present(50_000),
2817 fee_proportional_millionths: 0,
2818 excess_data: Vec::new()
2822 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();
2823 assert_eq!(route.paths.len(), 1);
2824 let mut total_amount_paid_msat = 0;
2825 for path in &route.paths {
2826 assert_eq!(path.len(), 2);
2827 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2828 total_amount_paid_msat += path.last().unwrap().fee_msat;
2830 assert_eq!(total_amount_paid_msat, 50_000);
2835 fn simple_mpp_route_test() {
2836 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2837 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2839 // We need a route consisting of 3 paths:
2840 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2841 // To achieve this, the amount being transferred should be around
2842 // the total capacity of these 3 paths.
2844 // First, we set limits on these (previously unlimited) channels.
2845 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2847 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2848 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2849 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2850 short_channel_id: 1,
2853 cltv_expiry_delta: 0,
2854 htlc_minimum_msat: 0,
2855 htlc_maximum_msat: OptionalField::Present(100_000),
2857 fee_proportional_millionths: 0,
2858 excess_data: Vec::new()
2860 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2861 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2862 short_channel_id: 3,
2865 cltv_expiry_delta: 0,
2866 htlc_minimum_msat: 0,
2867 htlc_maximum_msat: OptionalField::Present(50_000),
2869 fee_proportional_millionths: 0,
2870 excess_data: Vec::new()
2873 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2874 // (total limit 60).
2875 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2876 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2877 short_channel_id: 12,
2880 cltv_expiry_delta: 0,
2881 htlc_minimum_msat: 0,
2882 htlc_maximum_msat: OptionalField::Present(60_000),
2884 fee_proportional_millionths: 0,
2885 excess_data: Vec::new()
2887 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2888 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2889 short_channel_id: 13,
2892 cltv_expiry_delta: 0,
2893 htlc_minimum_msat: 0,
2894 htlc_maximum_msat: OptionalField::Present(60_000),
2896 fee_proportional_millionths: 0,
2897 excess_data: Vec::new()
2900 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2901 // (total capacity 180 sats).
2902 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2903 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2904 short_channel_id: 2,
2907 cltv_expiry_delta: 0,
2908 htlc_minimum_msat: 0,
2909 htlc_maximum_msat: OptionalField::Present(200_000),
2911 fee_proportional_millionths: 0,
2912 excess_data: Vec::new()
2914 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2915 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2916 short_channel_id: 4,
2919 cltv_expiry_delta: 0,
2920 htlc_minimum_msat: 0,
2921 htlc_maximum_msat: OptionalField::Present(180_000),
2923 fee_proportional_millionths: 0,
2924 excess_data: Vec::new()
2928 // Attempt to route more than available results in a failure.
2929 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(),
2930 &nodes[2], Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2931 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2932 } else { panic!(); }
2936 // Now, attempt to route 250 sats (just a bit below the capacity).
2937 // Our algorithm should provide us with these 3 paths.
2938 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2939 Some(InvoiceFeatures::known()), None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2940 assert_eq!(route.paths.len(), 3);
2941 let mut total_amount_paid_msat = 0;
2942 for path in &route.paths {
2943 assert_eq!(path.len(), 2);
2944 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2945 total_amount_paid_msat += path.last().unwrap().fee_msat;
2947 assert_eq!(total_amount_paid_msat, 250_000);
2951 // Attempt to route an exact amount is also fine
2952 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
2953 Some(InvoiceFeatures::known()), None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2954 assert_eq!(route.paths.len(), 3);
2955 let mut total_amount_paid_msat = 0;
2956 for path in &route.paths {
2957 assert_eq!(path.len(), 2);
2958 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2959 total_amount_paid_msat += path.last().unwrap().fee_msat;
2961 assert_eq!(total_amount_paid_msat, 290_000);
2966 fn long_mpp_route_test() {
2967 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2968 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2970 // We need a route consisting of 3 paths:
2971 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2972 // Note that these paths overlap (channels 5, 12, 13).
2973 // We will route 300 sats.
2974 // Each path will have 100 sats capacity, those channels which
2975 // are used twice will have 200 sats capacity.
2977 // Disable other potential paths.
2978 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2979 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2980 short_channel_id: 2,
2983 cltv_expiry_delta: 0,
2984 htlc_minimum_msat: 0,
2985 htlc_maximum_msat: OptionalField::Present(100_000),
2987 fee_proportional_millionths: 0,
2988 excess_data: Vec::new()
2990 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2991 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2992 short_channel_id: 7,
2995 cltv_expiry_delta: 0,
2996 htlc_minimum_msat: 0,
2997 htlc_maximum_msat: OptionalField::Present(100_000),
2999 fee_proportional_millionths: 0,
3000 excess_data: Vec::new()
3003 // Path via {node0, node2} is channels {1, 3, 5}.
3004 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3005 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3006 short_channel_id: 1,
3009 cltv_expiry_delta: 0,
3010 htlc_minimum_msat: 0,
3011 htlc_maximum_msat: OptionalField::Present(100_000),
3013 fee_proportional_millionths: 0,
3014 excess_data: Vec::new()
3016 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3017 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3018 short_channel_id: 3,
3021 cltv_expiry_delta: 0,
3022 htlc_minimum_msat: 0,
3023 htlc_maximum_msat: OptionalField::Present(100_000),
3025 fee_proportional_millionths: 0,
3026 excess_data: Vec::new()
3029 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3030 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3031 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3032 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3033 short_channel_id: 5,
3036 cltv_expiry_delta: 0,
3037 htlc_minimum_msat: 0,
3038 htlc_maximum_msat: OptionalField::Present(200_000),
3040 fee_proportional_millionths: 0,
3041 excess_data: Vec::new()
3044 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3045 // Add 100 sats to the capacities of {12, 13}, because these channels
3046 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3047 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3048 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3049 short_channel_id: 12,
3052 cltv_expiry_delta: 0,
3053 htlc_minimum_msat: 0,
3054 htlc_maximum_msat: OptionalField::Present(200_000),
3056 fee_proportional_millionths: 0,
3057 excess_data: Vec::new()
3059 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3060 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3061 short_channel_id: 13,
3064 cltv_expiry_delta: 0,
3065 htlc_minimum_msat: 0,
3066 htlc_maximum_msat: OptionalField::Present(200_000),
3068 fee_proportional_millionths: 0,
3069 excess_data: Vec::new()
3072 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3073 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3074 short_channel_id: 6,
3077 cltv_expiry_delta: 0,
3078 htlc_minimum_msat: 0,
3079 htlc_maximum_msat: OptionalField::Present(100_000),
3081 fee_proportional_millionths: 0,
3082 excess_data: Vec::new()
3084 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3085 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3086 short_channel_id: 11,
3089 cltv_expiry_delta: 0,
3090 htlc_minimum_msat: 0,
3091 htlc_maximum_msat: OptionalField::Present(100_000),
3093 fee_proportional_millionths: 0,
3094 excess_data: Vec::new()
3097 // Path via {node7, node2} is channels {12, 13, 5}.
3098 // We already limited them to 200 sats (they are used twice for 100 sats).
3099 // Nothing to do here.
3102 // Attempt to route more than available results in a failure.
3103 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3104 Some(InvoiceFeatures::known()), None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
3105 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3106 } else { panic!(); }
3110 // Now, attempt to route 300 sats (exact amount we can route).
3111 // Our algorithm should provide us with these 3 paths, 100 sats each.
3112 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3113 Some(InvoiceFeatures::known()), None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
3114 assert_eq!(route.paths.len(), 3);
3116 let mut total_amount_paid_msat = 0;
3117 for path in &route.paths {
3118 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3119 total_amount_paid_msat += path.last().unwrap().fee_msat;
3121 assert_eq!(total_amount_paid_msat, 300_000);
3127 fn mpp_cheaper_route_test() {
3128 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3129 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3131 // This test checks that if we have two cheaper paths and one more expensive path,
3132 // so that liquidity-wise any 2 of 3 combination is sufficient,
3133 // two cheaper paths will be taken.
3134 // These paths have equal available liquidity.
3136 // We need a combination of 3 paths:
3137 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3138 // Note that these paths overlap (channels 5, 12, 13).
3139 // Each path will have 100 sats capacity, those channels which
3140 // are used twice will have 200 sats capacity.
3142 // Disable other potential paths.
3143 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3144 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3145 short_channel_id: 2,
3148 cltv_expiry_delta: 0,
3149 htlc_minimum_msat: 0,
3150 htlc_maximum_msat: OptionalField::Present(100_000),
3152 fee_proportional_millionths: 0,
3153 excess_data: Vec::new()
3155 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3156 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3157 short_channel_id: 7,
3160 cltv_expiry_delta: 0,
3161 htlc_minimum_msat: 0,
3162 htlc_maximum_msat: OptionalField::Present(100_000),
3164 fee_proportional_millionths: 0,
3165 excess_data: Vec::new()
3168 // Path via {node0, node2} is channels {1, 3, 5}.
3169 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3170 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3171 short_channel_id: 1,
3174 cltv_expiry_delta: 0,
3175 htlc_minimum_msat: 0,
3176 htlc_maximum_msat: OptionalField::Present(100_000),
3178 fee_proportional_millionths: 0,
3179 excess_data: Vec::new()
3181 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3182 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3183 short_channel_id: 3,
3186 cltv_expiry_delta: 0,
3187 htlc_minimum_msat: 0,
3188 htlc_maximum_msat: OptionalField::Present(100_000),
3190 fee_proportional_millionths: 0,
3191 excess_data: Vec::new()
3194 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3195 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3196 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3197 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3198 short_channel_id: 5,
3201 cltv_expiry_delta: 0,
3202 htlc_minimum_msat: 0,
3203 htlc_maximum_msat: OptionalField::Present(200_000),
3205 fee_proportional_millionths: 0,
3206 excess_data: Vec::new()
3209 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3210 // Add 100 sats to the capacities of {12, 13}, because these channels
3211 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3212 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3213 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3214 short_channel_id: 12,
3217 cltv_expiry_delta: 0,
3218 htlc_minimum_msat: 0,
3219 htlc_maximum_msat: OptionalField::Present(200_000),
3221 fee_proportional_millionths: 0,
3222 excess_data: Vec::new()
3224 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3225 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3226 short_channel_id: 13,
3229 cltv_expiry_delta: 0,
3230 htlc_minimum_msat: 0,
3231 htlc_maximum_msat: OptionalField::Present(200_000),
3233 fee_proportional_millionths: 0,
3234 excess_data: Vec::new()
3237 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3238 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3239 short_channel_id: 6,
3242 cltv_expiry_delta: 0,
3243 htlc_minimum_msat: 0,
3244 htlc_maximum_msat: OptionalField::Present(100_000),
3245 fee_base_msat: 1_000,
3246 fee_proportional_millionths: 0,
3247 excess_data: Vec::new()
3249 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3250 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3251 short_channel_id: 11,
3254 cltv_expiry_delta: 0,
3255 htlc_minimum_msat: 0,
3256 htlc_maximum_msat: OptionalField::Present(100_000),
3258 fee_proportional_millionths: 0,
3259 excess_data: Vec::new()
3262 // Path via {node7, node2} is channels {12, 13, 5}.
3263 // We already limited them to 200 sats (they are used twice for 100 sats).
3264 // Nothing to do here.
3267 // Now, attempt to route 180 sats.
3268 // Our algorithm should provide us with these 2 paths.
3269 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3270 Some(InvoiceFeatures::known()), None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3271 assert_eq!(route.paths.len(), 2);
3273 let mut total_value_transferred_msat = 0;
3274 let mut total_paid_msat = 0;
3275 for path in &route.paths {
3276 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3277 total_value_transferred_msat += path.last().unwrap().fee_msat;
3279 total_paid_msat += hop.fee_msat;
3282 // If we paid fee, this would be higher.
3283 assert_eq!(total_value_transferred_msat, 180_000);
3284 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3285 assert_eq!(total_fees_paid, 0);
3290 fn fees_on_mpp_route_test() {
3291 // This test makes sure that MPP algorithm properly takes into account
3292 // fees charged on the channels, by making the fees impactful:
3293 // if the fee is not properly accounted for, the behavior is different.
3294 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3295 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3297 // We need a route consisting of 2 paths:
3298 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3299 // We will route 200 sats, Each path will have 100 sats capacity.
3301 // This test is not particularly stable: e.g.,
3302 // there's a way to route via {node0, node2, node4}.
3303 // It works while pathfinding is deterministic, but can be broken otherwise.
3304 // It's fine to ignore this concern for now.
3306 // Disable other potential paths.
3307 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3308 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3309 short_channel_id: 2,
3312 cltv_expiry_delta: 0,
3313 htlc_minimum_msat: 0,
3314 htlc_maximum_msat: OptionalField::Present(100_000),
3316 fee_proportional_millionths: 0,
3317 excess_data: Vec::new()
3320 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3321 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3322 short_channel_id: 7,
3325 cltv_expiry_delta: 0,
3326 htlc_minimum_msat: 0,
3327 htlc_maximum_msat: OptionalField::Present(100_000),
3329 fee_proportional_millionths: 0,
3330 excess_data: Vec::new()
3333 // Path via {node0, node2} is channels {1, 3, 5}.
3334 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3335 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3336 short_channel_id: 1,
3339 cltv_expiry_delta: 0,
3340 htlc_minimum_msat: 0,
3341 htlc_maximum_msat: OptionalField::Present(100_000),
3343 fee_proportional_millionths: 0,
3344 excess_data: Vec::new()
3346 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3347 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3348 short_channel_id: 3,
3351 cltv_expiry_delta: 0,
3352 htlc_minimum_msat: 0,
3353 htlc_maximum_msat: OptionalField::Present(100_000),
3355 fee_proportional_millionths: 0,
3356 excess_data: Vec::new()
3359 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3360 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3361 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3362 short_channel_id: 5,
3365 cltv_expiry_delta: 0,
3366 htlc_minimum_msat: 0,
3367 htlc_maximum_msat: OptionalField::Present(100_000),
3369 fee_proportional_millionths: 0,
3370 excess_data: Vec::new()
3373 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3374 // All channels should be 100 sats capacity. But for the fee experiment,
3375 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3376 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3377 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3378 // so no matter how large are other channels,
3379 // the whole path will be limited by 100 sats with just these 2 conditions:
3380 // - channel 12 capacity is 250 sats
3381 // - fee for channel 6 is 150 sats
3382 // Let's test this by enforcing these 2 conditions and removing other limits.
3383 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3384 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3385 short_channel_id: 12,
3388 cltv_expiry_delta: 0,
3389 htlc_minimum_msat: 0,
3390 htlc_maximum_msat: OptionalField::Present(250_000),
3392 fee_proportional_millionths: 0,
3393 excess_data: Vec::new()
3395 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3396 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3397 short_channel_id: 13,
3400 cltv_expiry_delta: 0,
3401 htlc_minimum_msat: 0,
3402 htlc_maximum_msat: OptionalField::Absent,
3404 fee_proportional_millionths: 0,
3405 excess_data: Vec::new()
3408 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3409 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3410 short_channel_id: 6,
3413 cltv_expiry_delta: 0,
3414 htlc_minimum_msat: 0,
3415 htlc_maximum_msat: OptionalField::Absent,
3416 fee_base_msat: 150_000,
3417 fee_proportional_millionths: 0,
3418 excess_data: Vec::new()
3420 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3421 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3422 short_channel_id: 11,
3425 cltv_expiry_delta: 0,
3426 htlc_minimum_msat: 0,
3427 htlc_maximum_msat: OptionalField::Absent,
3429 fee_proportional_millionths: 0,
3430 excess_data: Vec::new()
3434 // Attempt to route more than available results in a failure.
3435 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3436 Some(InvoiceFeatures::known()), None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3437 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3438 } else { panic!(); }
3442 // Now, attempt to route 200 sats (exact amount we can route).
3443 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3],
3444 Some(InvoiceFeatures::known()), None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3445 assert_eq!(route.paths.len(), 2);
3447 let mut total_amount_paid_msat = 0;
3448 for path in &route.paths {
3449 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3450 total_amount_paid_msat += path.last().unwrap().fee_msat;
3452 assert_eq!(total_amount_paid_msat, 200_000);
3458 fn drop_lowest_channel_mpp_route_test() {
3459 // This test checks that low-capacity channel is dropped when after
3460 // path finding we realize that we found more capacity than we need.
3461 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3462 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3464 // We need a route consisting of 3 paths:
3465 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3467 // The first and the second paths should be sufficient, but the third should be
3468 // cheaper, so that we select it but drop later.
3470 // First, we set limits on these (previously unlimited) channels.
3471 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3473 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3474 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3475 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3476 short_channel_id: 1,
3479 cltv_expiry_delta: 0,
3480 htlc_minimum_msat: 0,
3481 htlc_maximum_msat: OptionalField::Present(100_000),
3483 fee_proportional_millionths: 0,
3484 excess_data: Vec::new()
3486 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3487 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3488 short_channel_id: 3,
3491 cltv_expiry_delta: 0,
3492 htlc_minimum_msat: 0,
3493 htlc_maximum_msat: OptionalField::Present(50_000),
3495 fee_proportional_millionths: 0,
3496 excess_data: Vec::new()
3499 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3500 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3502 short_channel_id: 12,
3505 cltv_expiry_delta: 0,
3506 htlc_minimum_msat: 0,
3507 htlc_maximum_msat: OptionalField::Present(60_000),
3509 fee_proportional_millionths: 0,
3510 excess_data: Vec::new()
3512 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3514 short_channel_id: 13,
3517 cltv_expiry_delta: 0,
3518 htlc_minimum_msat: 0,
3519 htlc_maximum_msat: OptionalField::Present(60_000),
3521 fee_proportional_millionths: 0,
3522 excess_data: Vec::new()
3525 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3526 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3527 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3528 short_channel_id: 2,
3531 cltv_expiry_delta: 0,
3532 htlc_minimum_msat: 0,
3533 htlc_maximum_msat: OptionalField::Present(20_000),
3535 fee_proportional_millionths: 0,
3536 excess_data: Vec::new()
3538 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3539 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3540 short_channel_id: 4,
3543 cltv_expiry_delta: 0,
3544 htlc_minimum_msat: 0,
3545 htlc_maximum_msat: OptionalField::Present(20_000),
3547 fee_proportional_millionths: 0,
3548 excess_data: Vec::new()
3552 // Attempt to route more than available results in a failure.
3553 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3554 Some(InvoiceFeatures::known()), None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3555 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3556 } else { panic!(); }
3560 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3561 // Our algorithm should provide us with these 3 paths.
3562 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3563 Some(InvoiceFeatures::known()), None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3564 assert_eq!(route.paths.len(), 3);
3565 let mut total_amount_paid_msat = 0;
3566 for path in &route.paths {
3567 assert_eq!(path.len(), 2);
3568 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3569 total_amount_paid_msat += path.last().unwrap().fee_msat;
3571 assert_eq!(total_amount_paid_msat, 125_000);
3575 // Attempt to route without the last small cheap channel
3576 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2],
3577 Some(InvoiceFeatures::known()), None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3578 assert_eq!(route.paths.len(), 2);
3579 let mut total_amount_paid_msat = 0;
3580 for path in &route.paths {
3581 assert_eq!(path.len(), 2);
3582 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3583 total_amount_paid_msat += path.last().unwrap().fee_msat;
3585 assert_eq!(total_amount_paid_msat, 90_000);
3590 fn min_criteria_consistency() {
3591 // Test that we don't use an inconsistent metric between updating and walking nodes during
3592 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
3593 // was updated with a different criterion from the heap sorting, resulting in loops in
3594 // calculated paths. We test for that specific case here.
3596 // We construct a network that looks like this:
3598 // node2 -1(3)2- node3
3602 // node1 -1(5)2- node4 -1(1)2- node6
3608 // We create a loop on the side of our real path - our destination is node 6, with a
3609 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
3610 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
3611 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
3612 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
3613 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
3614 // "previous hop" being set to node 3, creating a loop in the path.
3615 let secp_ctx = Secp256k1::new();
3616 let logger = Arc::new(test_utils::TestLogger::new());
3617 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
3618 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3620 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
3621 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3622 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3623 short_channel_id: 6,
3626 cltv_expiry_delta: (6 << 8) | 0,
3627 htlc_minimum_msat: 0,
3628 htlc_maximum_msat: OptionalField::Absent,
3630 fee_proportional_millionths: 0,
3631 excess_data: Vec::new()
3633 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
3635 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3636 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3637 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3638 short_channel_id: 5,
3641 cltv_expiry_delta: (5 << 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[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
3650 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
3651 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3652 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3653 short_channel_id: 4,
3656 cltv_expiry_delta: (4 << 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[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
3665 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
3666 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
3667 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3668 short_channel_id: 3,
3671 cltv_expiry_delta: (3 << 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[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
3680 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
3681 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3682 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3683 short_channel_id: 2,
3686 cltv_expiry_delta: (2 << 8) | 0,
3687 htlc_minimum_msat: 0,
3688 htlc_maximum_msat: OptionalField::Absent,
3690 fee_proportional_millionths: 0,
3691 excess_data: Vec::new()
3694 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
3695 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3696 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3697 short_channel_id: 1,
3700 cltv_expiry_delta: (1 << 8) | 0,
3701 htlc_minimum_msat: 100,
3702 htlc_maximum_msat: OptionalField::Absent,
3704 fee_proportional_millionths: 0,
3705 excess_data: Vec::new()
3707 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
3710 // Now ensure the route flows simply over nodes 1 and 4 to 6.
3711 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();
3712 assert_eq!(route.paths.len(), 1);
3713 assert_eq!(route.paths[0].len(), 3);
3715 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
3716 assert_eq!(route.paths[0][0].short_channel_id, 6);
3717 assert_eq!(route.paths[0][0].fee_msat, 100);
3718 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
3719 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
3720 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
3722 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
3723 assert_eq!(route.paths[0][1].short_channel_id, 5);
3724 assert_eq!(route.paths[0][1].fee_msat, 0);
3725 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
3726 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
3727 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
3729 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
3730 assert_eq!(route.paths[0][2].short_channel_id, 1);
3731 assert_eq!(route.paths[0][2].fee_msat, 10_000);
3732 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
3733 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
3734 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
3740 fn exact_fee_liquidity_limit() {
3741 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
3742 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
3743 // we calculated fees on a higher value, resulting in us ignoring such paths.
3744 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3745 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
3747 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
3749 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3751 short_channel_id: 2,
3754 cltv_expiry_delta: 0,
3755 htlc_minimum_msat: 0,
3756 htlc_maximum_msat: OptionalField::Present(85_000),
3758 fee_proportional_millionths: 0,
3759 excess_data: Vec::new()
3762 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3763 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3764 short_channel_id: 12,
3767 cltv_expiry_delta: (4 << 8) | 1,
3768 htlc_minimum_msat: 0,
3769 htlc_maximum_msat: OptionalField::Present(270_000),
3771 fee_proportional_millionths: 1000000,
3772 excess_data: Vec::new()
3776 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
3777 // 200% fee charged channel 13 in the 1-to-2 direction.
3778 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();
3779 assert_eq!(route.paths.len(), 1);
3780 assert_eq!(route.paths[0].len(), 2);
3782 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3783 assert_eq!(route.paths[0][0].short_channel_id, 12);
3784 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3785 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3786 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3787 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3789 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3790 assert_eq!(route.paths[0][1].short_channel_id, 13);
3791 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3792 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3793 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
3794 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3799 fn htlc_max_reduction_below_min() {
3800 // Test that if, while walking the graph, we reduce the value being sent to meet an
3801 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
3802 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
3803 // resulting in us thinking there is no possible path, even if other paths exist.
3804 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3805 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3807 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
3808 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
3809 // then try to send 90_000.
3810 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3811 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3812 short_channel_id: 2,
3815 cltv_expiry_delta: 0,
3816 htlc_minimum_msat: 0,
3817 htlc_maximum_msat: OptionalField::Present(80_000),
3819 fee_proportional_millionths: 0,
3820 excess_data: Vec::new()
3822 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3823 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3824 short_channel_id: 4,
3827 cltv_expiry_delta: (4 << 8) | 1,
3828 htlc_minimum_msat: 90_000,
3829 htlc_maximum_msat: OptionalField::Absent,
3831 fee_proportional_millionths: 0,
3832 excess_data: Vec::new()
3836 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
3837 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
3838 // expensive) channels 12-13 path.
3839 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();
3840 assert_eq!(route.paths.len(), 1);
3841 assert_eq!(route.paths[0].len(), 2);
3843 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
3844 assert_eq!(route.paths[0][0].short_channel_id, 12);
3845 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
3846 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
3847 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
3848 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
3850 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
3851 assert_eq!(route.paths[0][1].short_channel_id, 13);
3852 assert_eq!(route.paths[0][1].fee_msat, 90_000);
3853 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
3854 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
3855 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
3860 use util::ser::Readable;
3861 /// Tries to open a network graph file, or panics with a URL to fetch it.
3862 pub(super) fn get_route_file() -> Result<std::fs::File, std::io::Error> {
3863 let res = File::open("net_graph-2021-05-27.bin") // By default we're run in RL/lightning
3864 .or_else(|_| File::open("lightning/net_graph-2021-05-27.bin")) // We may be run manually in RL/
3865 .or_else(|_| { // Fall back to guessing based on the binary location
3866 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
3867 let mut path = std::env::current_exe().unwrap();
3868 path.pop(); // lightning-...
3870 path.pop(); // debug
3871 path.pop(); // target
3872 path.push("lightning");
3873 path.push("net_graph-2021-05-27.bin");
3874 eprintln!("{}", path.to_str().unwrap());
3877 #[cfg(require_route_graph_test)]
3878 return Ok(res.expect("Didn't have route graph and was configured to require it"));
3879 #[cfg(not(require_route_graph_test))]
3883 pub(super) fn random_init_seed() -> u64 {
3884 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
3885 use core::hash::{BuildHasher, Hasher};
3886 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
3887 println!("Using seed of {}", seed);
3892 fn generate_routes() {
3893 let mut d = match get_route_file() {
3896 eprintln!("Please fetch https://bitcoin.ninja/ldk-net_graph-45d86ead641d-2021-05-27.bin and place it at lightning/net_graph-2021-05-27.bin");
3900 let graph = NetworkGraph::read(&mut d).unwrap();
3902 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3903 let mut seed = random_init_seed() as usize;
3904 'load_endpoints: for _ in 0..10 {
3906 seed = seed.overflowing_mul(0xdeadbeef).0;
3907 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3908 seed = seed.overflowing_mul(0xdeadbeef).0;
3909 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3910 let amt = seed as u64 % 200_000_000;
3911 if get_route(src, &graph, dst, None, None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3912 continue 'load_endpoints;
3919 fn generate_routes_mpp() {
3920 let mut d = match get_route_file() {
3923 eprintln!("Please fetch https://bitcoin.ninja/ldk-net_graph-45d86ead641d-2021-05-27.bin and place it at lightning/net_graph-2021-05-27.bin");
3927 let graph = NetworkGraph::read(&mut d).unwrap();
3929 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3930 let mut seed = random_init_seed() as usize;
3931 'load_endpoints: for _ in 0..10 {
3933 seed = seed.overflowing_mul(0xdeadbeef).0;
3934 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3935 seed = seed.overflowing_mul(0xdeadbeef).0;
3936 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3937 let amt = seed as u64 % 200_000_000;
3938 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &test_utils::TestLogger::new()).is_ok() {
3939 continue 'load_endpoints;
3946 #[cfg(all(test, feature = "unstable"))]
3949 use util::logger::{Logger, Record};
3954 struct DummyLogger {}
3955 impl Logger for DummyLogger {
3956 fn log(&self, _record: &Record) {}
3960 fn generate_routes(bench: &mut Bencher) {
3961 let mut d = tests::get_route_file()
3962 .expect("Please fetch https://bitcoin.ninja/ldk-net_graph-45d86ead641d-2021-05-27.bin and place it at lightning/net_graph-2021-05-27.bin");
3963 let graph = NetworkGraph::read(&mut d).unwrap();
3965 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3966 let mut path_endpoints = Vec::new();
3967 let mut seed: usize = 0xdeadbeef;
3968 'load_endpoints: for _ in 0..100 {
3971 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3973 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3974 let amt = seed as u64 % 1_000_000;
3975 if get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3976 path_endpoints.push((src, dst, amt));
3977 continue 'load_endpoints;
3982 // ...then benchmark finding paths between the nodes we learned.
3985 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3986 assert!(get_route(src, &graph, dst, None, None, &[], amt, 42, &DummyLogger{}).is_ok());
3992 fn generate_mpp_routes(bench: &mut Bencher) {
3993 let mut d = tests::get_route_file()
3994 .expect("Please fetch https://bitcoin.ninja/ldk-net_graph-45d86ead641d-2021-05-27.bin and place it at lightning/net_graph-2021-05-27.bin");
3995 let graph = NetworkGraph::read(&mut d).unwrap();
3997 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3998 let mut path_endpoints = Vec::new();
3999 let mut seed: usize = 0xdeadbeef;
4000 'load_endpoints: for _ in 0..100 {
4003 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4005 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
4006 let amt = seed as u64 % 1_000_000;
4007 if get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok() {
4008 path_endpoints.push((src, dst, amt));
4009 continue 'load_endpoints;
4014 // ...then benchmark finding paths between the nodes we learned.
4017 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4018 assert!(get_route(src, &graph, dst, Some(InvoiceFeatures::known()), None, &[], amt, 42, &DummyLogger{}).is_ok());