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, 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 std::collections::{HashMap, BinaryHeap};
29 #[derive(Clone, PartialEq)]
31 /// The node_id of the node at this hop.
32 pub pubkey: PublicKey,
33 /// The node_announcement features of the node at this hop. For the last hop, these may be
34 /// amended to match the features present in the invoice this node generated.
35 pub node_features: NodeFeatures,
36 /// The channel that should be used from the previous hop to reach this node.
37 pub short_channel_id: u64,
38 /// The channel_announcement features of the channel that should be used from the previous hop
39 /// to reach this node.
40 pub channel_features: ChannelFeatures,
41 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
42 /// For the last hop, this should be the full value of the payment (might be more than
43 /// requested if we had to match htlc_minimum_msat).
45 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
46 /// expected at the destination, in excess of the current block height.
47 pub cltv_expiry_delta: u32,
51 impl Writeable for Vec<RouteHop> {
52 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
53 (self.len() as u8).write(writer)?;
54 for hop in self.iter() {
55 hop.pubkey.write(writer)?;
56 hop.node_features.write(writer)?;
57 hop.short_channel_id.write(writer)?;
58 hop.channel_features.write(writer)?;
59 hop.fee_msat.write(writer)?;
60 hop.cltv_expiry_delta.write(writer)?;
67 impl Readable for Vec<RouteHop> {
68 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
69 let hops_count: u8 = Readable::read(reader)?;
70 let mut hops = Vec::with_capacity(hops_count as usize);
71 for _ in 0..hops_count {
73 pubkey: Readable::read(reader)?,
74 node_features: Readable::read(reader)?,
75 short_channel_id: Readable::read(reader)?,
76 channel_features: Readable::read(reader)?,
77 fee_msat: Readable::read(reader)?,
78 cltv_expiry_delta: Readable::read(reader)?,
85 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
86 /// it can take multiple paths. Each path is composed of one or more hops through the network.
87 #[derive(Clone, PartialEq)]
89 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
90 /// last RouteHop in each path must be the same.
91 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
92 /// destination. Thus, this must always be at least length one. While the maximum length of any
93 /// given path is variable, keeping the length of any path to less than 20 should currently
94 /// ensure it is viable.
95 pub paths: Vec<Vec<RouteHop>>,
98 impl Writeable for Route {
99 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
100 (self.paths.len() as u64).write(writer)?;
101 for hops in self.paths.iter() {
108 impl Readable for Route {
109 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
110 let path_count: u64 = Readable::read(reader)?;
111 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
112 for _ in 0..path_count {
113 paths.push(Readable::read(reader)?);
119 /// A channel descriptor which provides a last-hop route to get_route
121 pub struct RouteHint {
122 /// The node_id of the non-target end of the route
123 pub src_node_id: PublicKey,
124 /// The short_channel_id of this channel
125 pub short_channel_id: u64,
126 /// The fees which must be paid to use this channel
127 pub fees: RoutingFees,
128 /// The difference in CLTV values between this node and the next node.
129 pub cltv_expiry_delta: u16,
130 /// The minimum value, in msat, which must be relayed to the next hop.
131 pub htlc_minimum_msat: Option<u64>,
132 /// The maximum value in msat available for routing with a single HTLC.
133 pub htlc_maximum_msat: Option<u64>,
136 #[derive(Eq, PartialEq)]
137 struct RouteGraphNode {
139 lowest_fee_to_peer_through_node: u64,
140 lowest_fee_to_node: u64,
141 // The maximum value a yet-to-be-constructed payment path might flow through this node.
142 // This value is upper-bounded by us by:
143 // - how much is needed for a path being constructed
144 // - how much value can channels following this node (up to the destination) can contribute,
145 // considering their capacity and fees
146 value_contribution_msat: u64
149 impl cmp::Ord for RouteGraphNode {
150 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
151 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
152 .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
156 impl cmp::PartialOrd for RouteGraphNode {
157 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
158 Some(self.cmp(other))
162 struct DummyDirectionalChannelInfo {
163 cltv_expiry_delta: u32,
164 htlc_minimum_msat: u64,
165 htlc_maximum_msat: Option<u64>,
169 /// It's useful to keep track of the hops associated with the fees required to use them,
170 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
171 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
172 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
174 struct PathBuildingHop {
175 /// Hop-specific details unrelated to the path during the routing phase,
176 /// but rather relevant to the LN graph.
178 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
179 src_lowest_inbound_fees: RoutingFees,
180 /// Fees of the channel used in this hop.
181 channel_fees: RoutingFees,
182 /// All the fees paid *after* this channel on the way to the destination
183 next_hops_fee_msat: u64,
184 /// Fee paid for the use of the current channel (see channel_fees).
185 /// The value will be actually deducted from the counterparty balance on the previous link.
186 hop_use_fee_msat: u64,
187 /// Used to compare channels when choosing the for routing.
188 /// Includes paying for the use of a hop and the following hops, as well as
189 /// an estimated cost of reaching this hop.
190 /// Might get stale when fees are recomputed. Primarily for internal use.
192 /// This is useful for update_value_and_recompute_fees to make sure
193 /// we don't fall below the minimum. Should not be updated manually and
194 /// generally should not be accessed.
195 htlc_minimum_msat: u64,
198 // Instantiated with a list of hops with correct data in them collected during path finding,
199 // an instance of this struct should be further modified only via given methods.
202 hops: Vec<PathBuildingHop>,
207 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
208 fn get_value_msat(&self) -> u64 {
209 self.hops.last().unwrap().route_hop.fee_msat
212 fn get_total_fee_paid_msat(&self) -> u64 {
213 if self.hops.len() < 1 {
217 // Can't use next_hops_fee_msat because it gets outdated.
218 for (i, hop) in self.hops.iter().enumerate() {
219 if i != self.hops.len() - 1 {
220 result += hop.route_hop.fee_msat;
226 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
227 // to change fees may result in an inconsistency.
229 // Sometimes we call this function right after constructing a path which has inconsistent
230 // (in terms of reaching htlc_minimum_msat), so that this function puts the fees in order.
231 // In that case we call it on the "same" amount we initially allocated for this path, and which
232 // could have been reduced on the way. In that case, there is also a risk of exceeding
233 // available_liquidity inside this function, because the function is unaware of this bound.
234 // In our specific recomputation cases where we never increase the value the risk is pretty low.
235 // This function, however, does not support arbitrarily increasing the value being transferred,
236 // and the exception will be triggered.
237 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
238 assert!(value_msat <= self.hops.last().unwrap().route_hop.fee_msat);
240 let mut total_fee_paid_msat = 0 as u64;
241 for i in (0..self.hops.len()).rev() {
242 let last_hop = i == self.hops.len() - 1;
244 // For non-last-hop, this value will represent the fees paid on the current hop. It
245 // will consist of the fees for the use of the next hop, and extra fees to match
246 // htlc_minimum_msat of the current channel. Last hop is handled separately.
247 let mut cur_hop_fees_msat = 0;
249 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().hop_use_fee_msat;
252 let mut cur_hop = self.hops.get_mut(i).unwrap();
253 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
254 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
255 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
256 // set it too high just to maliciously take more fees by exploiting this
257 // match htlc_minimum_msat logic.
258 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
259 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
260 // Note that there is a risk that *previous hops* (those closer to us, as we go
261 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
263 // This might make us end up with a broken route, although this should be super-rare
264 // in practice, both because of how healthy channels look like, and how we pick
265 // channels in add_entry.
266 // Also, this can't be exploited more heavily than *announce a free path and fail
268 cur_hop_transferred_amount_msat += extra_fees_msat;
269 total_fee_paid_msat += extra_fees_msat;
270 cur_hop_fees_msat += extra_fees_msat;
274 // Final hop is a special case: it usually has just value_msat (by design), but also
275 // it still could overpay for the htlc_minimum_msat.
276 cur_hop.route_hop.fee_msat = cur_hop_transferred_amount_msat;
278 // Propagate updated fees for the use of the channels to one hop back, where they
279 // will be actually paid (fee_msat). The last hop is handled above separately.
280 cur_hop.route_hop.fee_msat = cur_hop_fees_msat;
283 // Fee for the use of the current hop which will be deducted on the previous hop.
284 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
285 // this channel is free for us.
287 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
288 cur_hop.hop_use_fee_msat = new_fee;
289 total_fee_paid_msat += new_fee;
291 // It should not be possible because this function is called only to reduce the
292 // value. In that case, compute_fee was already called with the same fees for
293 // larger amount and there was no overflow.
301 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
302 let proportional_fee_millions =
303 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
304 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
305 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
309 // This function may be (indirectly) called without any verification,
310 // with channel_fees provided by a caller. We should handle it gracefully.
315 /// Gets a route from us (payer) to the given target node (payee).
317 /// Extra routing hops between known nodes and the target will be used if they are included in
320 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
321 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
322 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those
323 /// in first_hops will be used.
325 /// Panics if first_hops contains channels without short_channel_ids
326 /// (ChannelManager::list_usable_channels will never include such channels).
328 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
329 /// equal), however the enabled/disabled bit on such channels as well as the
330 /// htlc_minimum_msat/htlc_maximum_msat *are* checked as they may change based on the receiving node.
331 pub fn get_route<L: Deref>(our_node_id: &PublicKey, network: &NetworkGraph, payee: &PublicKey, first_hops: Option<&[&ChannelDetails]>,
332 last_hops: &[&RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where L::Target: Logger {
333 // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
334 // uptime/success in using a node in the past.
335 if *payee == *our_node_id {
336 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
339 if final_value_msat > MAX_VALUE_MSAT {
340 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
343 if final_value_msat == 0 {
344 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
347 for last_hop in last_hops {
348 if last_hop.src_node_id == *payee {
349 return Err(LightningError{err: "Last hop cannot have a payee as a source.".to_owned(), action: ErrorAction::IgnoreError});
353 // The general routing idea is the following:
354 // 1. Fill first/last hops communicated by the caller.
355 // 2. Attempt to construct a path from payer to payee for transferring
356 // any ~sufficient (described later) value.
357 // If succeed, remember which channels were used and how much liquidity they have available,
358 // so that future paths don't rely on the same liquidity.
359 // 3. Prooceed to the next step if:
360 // - we hit the recommended target value;
361 // - OR if we could not construct a new path. Any next attempt will fail too.
362 // Otherwise, repeat step 2.
363 // 4. See if we managed to collect paths which aggregately are able to transfer target value
364 // (not recommended value). If yes, proceed. If not, fail routing.
365 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
366 // 6. Of all the found paths, select only those with the lowest total fee.
367 // 7. The last path in every selected route is likely to be more than we need.
368 // Reduce its value-to-transfer and recompute fees.
369 // 8. Choose the best route by the lowest total fee.
371 // As for the actual search algorithm,
372 // we do a payee-to-payer Dijkstra's sorting by each node's distance from the payee
373 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
374 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
375 // to use as the A* heuristic beyond just the cost to get one node further than the current
378 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
379 cltv_expiry_delta: 0,
380 htlc_minimum_msat: 0,
381 htlc_maximum_msat: None,
384 proportional_millionths: 0,
388 let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
389 let mut dist = HashMap::with_capacity(network.get_nodes().len());
391 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
392 // Don't stop searching for paths when we think they're
393 // sufficient to transfer a given value aggregately.
394 // Search for higher value, so that we collect many more paths,
395 // and then select the best combination among them.
396 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
397 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
400 // Prepare the data we'll use for payee-to-payer search by
401 // inserting first hops suggested by the caller as targets.
402 // Our search will then attempt to reach them while traversing from the payee node.
403 let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
404 if let Some(hops) = first_hops {
406 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
407 if chan.remote_network_id == *our_node_id {
408 return Err(LightningError{err: "First hop cannot have our_node_id as a destination.".to_owned(), action: ErrorAction::IgnoreError});
410 first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone(), chan.outbound_capacity_msat));
412 if first_hop_targets.is_empty() {
413 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
417 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
418 // This map allows paths to be aware of the channel use by other paths in the same call.
419 // This would help to make a better path finding decisions and not "overbook" channels.
420 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
421 let mut bookkeeped_channels_liquidity_available_msat = HashMap::new();
423 // Keeping track of how much value we already collected across other paths. Helps to decide:
424 // - how much a new path should be transferring (upper bound);
425 // - whether a channel should be disregarded because
426 // it's available liquidity is too small comparing to how much more we need to collect;
427 // - when we want to stop looking for new paths.
428 let mut already_collected_value_msat = 0;
430 macro_rules! add_entry {
431 // Adds entry which goes from $src_node_id to $dest_node_id
432 // over the channel with id $chan_id with fees described in
433 // $directional_info.
434 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
435 // since that value has to be transferred over this channel.
436 ( $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,
437 $next_hops_value_contribution: expr ) => {
438 // Channels to self should not be used. This is more of belt-and-suspenders, because in
439 // practice these cases should be caught earlier:
440 // - for regular channels at channel announcement (TODO)
441 // - for first and last hops early in get_route
442 if $src_node_id != $dest_node_id.clone() {
443 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
444 let mut initial_liquidity_available_msat = None;
445 if let Some(capacity_sats) = $capacity_sats {
446 initial_liquidity_available_msat = Some(capacity_sats * 1000);
449 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
450 if let Some(available_msat) = initial_liquidity_available_msat {
451 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
453 initial_liquidity_available_msat = Some(htlc_maximum_msat);
457 match initial_liquidity_available_msat {
458 Some(available_msat) => available_msat,
459 // We assume channels with unknown balance have
460 // a capacity of 0.0025 BTC (or 250_000 sats).
461 None => 250_000 * 1000
465 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
466 // It may be misleading because we might later choose to reduce the value transferred
467 // over these channels, and the channel which was insufficient might become sufficient.
468 // Worst case: we drop a good channel here because it can't cover the high following
469 // fees caused by one expensive channel, but then this channel could have been used
470 // if the amount being transferred over this path is lower.
471 // We do this for now, but this is a subject for removal.
472 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
474 // Routing Fragmentation Mitigation heuristic:
476 // Routing fragmentation across many payment paths increases the overall routing
477 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
478 // Taking too many smaller paths also increases the chance of payment failure.
479 // Thus to avoid this effect, we require from our collected links to provide
480 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
482 // This requirement is currently 5% of the remaining-to-be-collected value.
483 // This means as we successfully advance in our collection,
484 // the absolute liquidity contribution is lowered,
485 // thus increasing the number of potential channels to be selected.
487 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up).
488 let minimal_value_contribution_msat: u64 = (recommended_value_msat - already_collected_value_msat + 19) / 20;
489 // Verify the liquidity offered by this channel complies to the minimal contribution.
490 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
492 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
493 // Includes paying fees for the use of the following channels.
494 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
495 Some(result) => result,
496 // Can't overflow due to how the values were computed right above.
497 None => unreachable!(),
500 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
501 // bother considering this channel.
502 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
503 // be only reduced later (not increased), so this channel should just be skipped
504 // as not sufficient.
505 // TODO: Explore simply adding fee to hit htlc_minimum_msat
506 if contributes_sufficient_value && amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat {
507 // Note that low contribution here (limited by available_liquidity_msat)
508 // might violate htlc_minimum_msat on the hops which are next along the
509 // payment path (upstream to the payee). To avoid that, we recompute path
510 // path fees knowing the final path contribution after constructing it.
511 let hm_entry = dist.entry(&$src_node_id);
512 let old_entry = hm_entry.or_insert_with(|| {
513 // If there was previously no known way to access
514 // the source node (recall it goes payee-to-payer) of $chan_id, first add
515 // a semi-dummy record just to compute the fees to reach the source node.
516 // This will affect our decision on selecting $chan_id
517 // as a way to reach the $dest_node_id.
518 let mut fee_base_msat = u32::max_value();
519 let mut fee_proportional_millionths = u32::max_value();
520 if let Some(Some(fees)) = network.get_nodes().get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
521 fee_base_msat = fees.base_msat;
522 fee_proportional_millionths = fees.proportional_millionths;
525 route_hop: RouteHop {
526 pubkey: $dest_node_id.clone(),
527 node_features: NodeFeatures::empty(),
529 channel_features: $chan_features.clone(),
531 cltv_expiry_delta: 0,
533 src_lowest_inbound_fees: RoutingFees {
534 base_msat: fee_base_msat,
535 proportional_millionths: fee_proportional_millionths,
537 channel_fees: $directional_info.fees,
538 next_hops_fee_msat: u64::max_value(),
539 hop_use_fee_msat: u64::max_value(),
540 total_fee_msat: u64::max_value(),
541 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
545 let mut hop_use_fee_msat = 0;
546 let mut total_fee_msat = $next_hops_fee_msat;
548 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
549 // will have the same effective-fee
550 if $src_node_id != *our_node_id {
551 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
552 // max_value means we'll always fail
553 // the old_entry.total_fee_msat > total_fee_msat check
554 None => total_fee_msat = u64::max_value(),
556 hop_use_fee_msat = fee_msat;
557 total_fee_msat += hop_use_fee_msat;
558 if let Some(prev_hop_fee_msat) = compute_fees(total_fee_msat + amount_to_transfer_over_msat,
559 old_entry.src_lowest_inbound_fees) {
560 if let Some(incremented_total_fee_msat) = total_fee_msat.checked_add(prev_hop_fee_msat) {
561 total_fee_msat = incremented_total_fee_msat;
564 // max_value means we'll always fail
565 // the old_entry.total_fee_msat > total_fee_msat check
566 total_fee_msat = u64::max_value();
569 // max_value means we'll always fail
570 // the old_entry.total_fee_msat > total_fee_msat check
571 total_fee_msat = u64::max_value();
577 let new_graph_node = RouteGraphNode {
578 pubkey: $src_node_id,
579 lowest_fee_to_peer_through_node: total_fee_msat,
580 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
581 value_contribution_msat: value_contribution_msat,
584 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
585 // if this way is cheaper than the already known
586 // (considering the cost to "reach" this channel from the route destination,
587 // the cost of using this channel,
588 // and the cost of routing to the source node of this channel).
589 // Also, consider that htlc_minimum_msat_difference, because we might end up
590 // paying it. Consider the following exploit:
591 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
592 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
593 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
594 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
596 // TODO: this scoring could be smarter (e.g. 0.5*htlc_minimum_msat here).
597 let mut old_cost = old_entry.total_fee_msat;
598 if let Some(increased_old_cost) = old_cost.checked_add(old_entry.htlc_minimum_msat) {
599 old_cost = increased_old_cost;
601 old_cost = u64::max_value();
604 let mut new_cost = total_fee_msat;
605 if let Some(increased_new_cost) = new_cost.checked_add($directional_info.htlc_minimum_msat) {
606 new_cost = increased_new_cost;
608 new_cost = u64::max_value();
611 if new_cost < old_cost {
612 targets.push(new_graph_node);
613 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
614 old_entry.hop_use_fee_msat = hop_use_fee_msat;
615 old_entry.total_fee_msat = total_fee_msat;
616 old_entry.route_hop = RouteHop {
617 pubkey: $dest_node_id.clone(),
618 node_features: NodeFeatures::empty(),
619 short_channel_id: $chan_id.clone(),
620 channel_features: $chan_features.clone(),
621 fee_msat: 0, // This value will be later filled with hop_use_fee_msat of the following channel
622 cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
624 old_entry.channel_fees = $directional_info.fees;
625 // It's probably fine to replace the old entry, because the new one
626 // passed the htlc_minimum-related checks above.
627 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
635 // Find ways (channels with destination) to reach a given node and store them
636 // in the corresponding data structures (routing graph etc).
637 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
638 // meaning how much will be paid in fees after this node (to the best of our knowledge).
639 // This data can later be helpful to optimize routing (pay lower fees).
640 macro_rules! add_entries_to_cheapest_to_target_node {
641 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr ) => {
642 if first_hops.is_some() {
643 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&$node_id) {
644 add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), $fee_to_target_msat, $next_hops_value_contribution);
649 if let Some(node_info) = $node.announcement_info.as_ref() {
650 features = node_info.features.clone();
652 features = NodeFeatures::empty();
655 if !features.requires_unknown_bits() {
656 for chan_id in $node.channels.iter() {
657 let chan = network.get_channels().get(chan_id).unwrap();
658 if !chan.features.requires_unknown_bits() {
659 if chan.node_one == *$node_id {
660 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
661 if first_hops.is_none() || chan.node_two != *our_node_id {
662 if let Some(two_to_one) = chan.two_to_one.as_ref() {
663 if two_to_one.enabled {
664 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);
669 if first_hops.is_none() || chan.node_one != *our_node_id {
670 if let Some(one_to_two) = chan.one_to_two.as_ref() {
671 if one_to_two.enabled {
672 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);
684 let mut payment_paths = Vec::<PaymentPath>::new();
686 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
687 'paths_collection: loop {
688 // For every new path, start from scratch, except
689 // bookkeeped_channels_liquidity_available_msat, which will improve
690 // the further iterations of path finding. Also don't erase first_hop_targets.
694 // If first hop is a private channel and the only way to reach the payee, this is the only
695 // place where it could be added.
696 if first_hops.is_some() {
697 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&payee) {
698 add_entry!(first_hop, *our_node_id, payee, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, recommended_value_msat);
702 // Add the payee as a target, so that the payee-to-payer
703 // search algorithm knows what to start with.
704 match network.get_nodes().get(payee) {
705 // The payee is not in our network graph, so nothing to add here.
706 // There is still a chance of reaching them via last_hops though,
707 // so don't yet fail the payment here.
708 // If not, targets.pop() will not even let us enter the loop in step 2.
711 add_entries_to_cheapest_to_target_node!(node, payee, 0, recommended_value_msat);
716 // If a caller provided us with last hops, add them to routing targets. Since this happens
717 // earlier than general path finding, they will be somewhat prioritized, although currently
718 // it matters only if the fees are exactly the same.
719 for hop in last_hops.iter() {
720 let have_hop_src_in_graph =
721 if let Some(&(ref first_hop, ref features, ref outbound_capacity_msat)) = first_hop_targets.get(&hop.src_node_id) {
722 // If this hop connects to a node with which we have a direct channel, ignore
723 // the network graph and add both the hop and our direct channel to
724 // the candidate set.
726 // Currently there are no channel-context features defined, so we are a
727 // bit lazy here. In the future, we should pull them out via our
728 // ChannelManager, but there's no reason to waste the space until we
730 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features.to_context(), 0, recommended_value_msat);
733 // In any other case, only add the hop if the source is in the regular network
735 network.get_nodes().get(&hop.src_node_id).is_some()
737 if have_hop_src_in_graph {
738 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
739 // really sucks, cause we're gonna need that eventually.
740 let last_hop_htlc_minimum_msat: u64 = match hop.htlc_minimum_msat {
741 Some(htlc_minimum_msat) => htlc_minimum_msat,
744 let directional_info = DummyDirectionalChannelInfo {
745 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
746 htlc_minimum_msat: last_hop_htlc_minimum_msat,
747 htlc_maximum_msat: hop.htlc_maximum_msat,
750 add_entry!(hop.short_channel_id, hop.src_node_id, payee, directional_info, None::<u64>, ChannelFeatures::empty(), 0, recommended_value_msat);
754 // At this point, targets are filled with the data from first and
755 // last hops communicated by the caller, and the payment receiver.
756 let mut found_new_path = false;
759 // If this loop terminates due the exhaustion of targets, two situations are possible:
760 // - not enough outgoing liquidity:
761 // 0 < already_collected_value_msat < final_value_msat
762 // - enough outgoing liquidity:
763 // final_value_msat <= already_collected_value_msat < recommended_value_msat
764 // Both these cases (and other cases except reaching recommended_value_msat) mean that
765 // paths_collection will be stopped because found_new_path==false.
766 // This is not necessarily a routing failure.
767 'path_construction: while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, value_contribution_msat, .. }) = targets.pop() {
769 // Since we're going payee-to-payer, hitting our node as a target means we should stop
770 // traversing the graph and arrange the path out of what we found.
771 if pubkey == *our_node_id {
772 let mut new_entry = dist.remove(&our_node_id).unwrap();
773 let mut ordered_hops = vec!(new_entry.clone());
776 if let Some(&(_, ref features, _)) = first_hop_targets.get(&ordered_hops.last().unwrap().route_hop.pubkey) {
777 ordered_hops.last_mut().unwrap().route_hop.node_features = features.to_context();
778 } else if let Some(node) = network.get_nodes().get(&ordered_hops.last().unwrap().route_hop.pubkey) {
779 if let Some(node_info) = node.announcement_info.as_ref() {
780 ordered_hops.last_mut().unwrap().route_hop.node_features = node_info.features.clone();
782 ordered_hops.last_mut().unwrap().route_hop.node_features = NodeFeatures::empty();
785 // We should be able to fill in features for everything except the last
786 // hop, if the last hop was provided via a BOLT 11 invoice (though we
787 // should be able to extend it further as BOLT 11 does have feature
788 // flags for the last hop node itself).
789 assert!(ordered_hops.last().unwrap().route_hop.pubkey == *payee);
792 // Means we succesfully traversed from the payer to the payee, now
793 // save this path for the payment route. Also, update the liquidity
794 // remaining on the used hops, so that we take them into account
795 // while looking for more paths.
796 if ordered_hops.last().unwrap().route_hop.pubkey == *payee {
800 new_entry = match dist.remove(&ordered_hops.last().unwrap().route_hop.pubkey) {
801 Some(payment_hop) => payment_hop,
802 // We can't arrive at None because, if we ever add an entry to targets,
803 // we also fill in the entry in dist (see add_entry!).
804 None => unreachable!(),
806 // We "propagate" the fees one hop backward (topologically) here,
807 // so that fees paid for a HTLC forwarding on the current channel are
808 // associated with the previous channel (where they will be subtracted).
809 ordered_hops.last_mut().unwrap().route_hop.fee_msat = new_entry.hop_use_fee_msat;
810 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = new_entry.route_hop.cltv_expiry_delta;
811 ordered_hops.push(new_entry.clone());
813 ordered_hops.last_mut().unwrap().route_hop.fee_msat = value_contribution_msat;
814 ordered_hops.last_mut().unwrap().hop_use_fee_msat = 0;
815 ordered_hops.last_mut().unwrap().route_hop.cltv_expiry_delta = final_cltv;
817 let mut payment_path = PaymentPath {hops: ordered_hops};
819 // We could have possibly constructed a slightly inconsistent path: since we reduce
820 // value being transferred along the way, we could have violated htlc_minimum_msat
821 // on some channels we already passed (assuming dest->source direction). Here, we
822 // recompute the fees again, so that if that's the case, we match the currently
823 // underpaid htlc_minimum_msat with fees.
824 payment_path.update_value_and_recompute_fees(value_contribution_msat);
826 // Since a path allows to transfer as much value as
827 // the smallest channel it has ("bottleneck"), we should recompute
828 // the fees so sender HTLC don't overpay fees when traversing
829 // larger channels than the bottleneck. This may happen because
830 // when we were selecting those channels we were not aware how much value
831 // this path will transfer, and the relative fee for them
832 // might have been computed considering a larger value.
833 // Remember that we used these channels so that we don't rely
834 // on the same liquidity in future paths.
835 for payment_hop in payment_path.hops.iter() {
836 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.route_hop.short_channel_id).unwrap();
837 let mut spent_on_hop_msat = value_contribution_msat;
838 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
839 spent_on_hop_msat += next_hops_fee_msat;
840 if *channel_liquidity_available_msat < spent_on_hop_msat {
841 // This should not happen because we do recompute fees right before,
842 // trying to avoid cases when a hop is not usable due to the fee situation.
843 break 'path_construction;
845 *channel_liquidity_available_msat -= spent_on_hop_msat;
847 // Track the total amount all our collected paths allow to send so that we:
848 // - know when to stop looking for more paths
849 // - know which of the hops are useless considering how much more sats we need
850 // (contributes_sufficient_value)
851 already_collected_value_msat += value_contribution_msat;
853 payment_paths.push(payment_path);
854 found_new_path = true;
855 break 'path_construction;
858 // Otherwise, since the current target node is not us,
859 // keep "unrolling" the payment graph from payee to payer by
860 // finding a way to reach the current target from the payer side.
861 match network.get_nodes().get(&pubkey) {
864 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node, value_contribution_msat);
870 // Stop either when recommended value is reached,
871 // or if during last iteration no new path was found.
872 // In the latter case, making another path finding attempt could not help,
873 // because we deterministically terminate the search due to low liquidity.
874 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
875 break 'paths_collection;
880 if payment_paths.len() == 0 {
881 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
884 if already_collected_value_msat < final_value_msat {
885 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
888 // Sort by total fees and take the best paths.
889 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
890 if payment_paths.len() > 50 {
891 payment_paths.truncate(50);
894 // Draw multiple sufficient routes by randomly combining the selected paths.
895 let mut drawn_routes = Vec::new();
896 for i in 0..payment_paths.len() {
897 let mut cur_route = Vec::<PaymentPath>::new();
898 let mut aggregate_route_value_msat = 0;
901 // TODO: real random shuffle
902 // Currently just starts with i_th and goes up to i-1_th in a looped way.
903 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
906 for payment_path in cur_payment_paths {
907 cur_route.push(payment_path.clone());
908 aggregate_route_value_msat += payment_path.get_value_msat();
909 if aggregate_route_value_msat > final_value_msat {
910 // Last path likely overpaid. Substract it from the most expensive
911 // (in terms of proportional fee) path in this route and recompute fees.
912 // This might be not the most economically efficient way, but fewer paths
913 // also makes routing more reliable.
914 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
916 // First, drop some expensive low-value paths entirely if possible.
917 // Sort by value so that we drop many really-low values first, since
918 // fewer paths is better: the payment is less likely to fail.
919 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
920 // so that the sender pays less fees overall. And also htlc_minimum_msat.
921 cur_route.sort_by_key(|path| path.get_value_msat());
922 // We should make sure that at least 1 path left.
923 let mut paths_left = cur_route.len();
924 cur_route.retain(|path| {
929 let path_value_msat = path.get_value_msat();
930 if path_value_msat <= overpaid_value_msat {
932 overpaid_value_msat -= path_value_msat;
938 if overpaid_value_msat == 0 {
942 assert!(cur_route.len() > 0);
945 // Now, substract the overpaid value from the most-expensive path.
946 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
947 // so that the sender pays less fees overall. And also htlc_minimum_msat.
948 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.channel_fees.proportional_millionths as u64).sum::<u64>() });
949 let mut expensive_payment_path = cur_route.first_mut().unwrap();
950 // We already dropped all the small channels above, meaning all the
951 // remaining channels are larger than remaining overpaid_value_msat.
952 // Thus, this can't be negative.
953 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
954 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
958 drawn_routes.push(cur_route);
962 // Select the best route by lowest total fee.
963 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
964 let mut selected_paths = Vec::<Vec::<RouteHop>>::new();
965 for payment_path in drawn_routes.first().unwrap() {
966 selected_paths.push(payment_path.hops.iter().map(|payment_hop| payment_hop.route_hop.clone()).collect());
969 let route = Route { paths: selected_paths };
970 log_trace!(logger, "Got route: {}", log_route!(route));
976 use routing::router::{get_route, RouteHint, RoutingFees};
977 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler};
978 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
979 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
980 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
981 use ln::channelmanager;
982 use util::test_utils;
983 use util::ser::Writeable;
985 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
986 use bitcoin::hashes::Hash;
987 use bitcoin::network::constants::Network;
988 use bitcoin::blockdata::constants::genesis_block;
989 use bitcoin::blockdata::script::Builder;
990 use bitcoin::blockdata::opcodes;
991 use bitcoin::blockdata::transaction::TxOut;
995 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
996 use bitcoin::secp256k1::{Secp256k1, All};
1000 // Using the same keys for LN and BTC ids
1001 fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
1002 node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
1003 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1004 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1006 let unsigned_announcement = UnsignedChannelAnnouncement {
1008 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1012 bitcoin_key_1: node_id_1,
1013 bitcoin_key_2: node_id_2,
1014 excess_data: Vec::new(),
1017 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1018 let valid_announcement = ChannelAnnouncement {
1019 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1020 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1021 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1022 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1023 contents: unsigned_announcement.clone(),
1025 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1026 Ok(res) => assert!(res),
1031 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) {
1032 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1033 let valid_channel_update = ChannelUpdate {
1034 signature: secp_ctx.sign(&msghash, node_privkey),
1035 contents: update.clone()
1038 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1039 Ok(res) => assert!(res),
1044 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,
1045 features: NodeFeatures, timestamp: u32) {
1046 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1047 let unsigned_announcement = UnsignedNodeAnnouncement {
1053 addresses: Vec::new(),
1054 excess_address_data: Vec::new(),
1055 excess_data: Vec::new(),
1057 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1058 let valid_announcement = NodeAnnouncement {
1059 signature: secp_ctx.sign(&msghash, node_privkey),
1060 contents: unsigned_announcement.clone()
1063 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1069 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1070 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1071 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1074 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1076 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1077 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1079 (our_privkey, our_id, privkeys, pubkeys)
1082 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1083 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1084 // test for it later.
1085 let idx = (id - 1) * 2 + 1;
1087 vec![1 << (idx - 8*3), 0, 0, 0]
1088 } else if idx > 8*2 {
1089 vec![1 << (idx - 8*2), 0, 0]
1090 } else if idx > 8*1 {
1091 vec![1 << (idx - 8*1), 0]
1097 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>) {
1098 let secp_ctx = Secp256k1::new();
1099 let logger = Arc::new(test_utils::TestLogger::new());
1100 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1101 let net_graph_msg_handler = NetGraphMsgHandler::new(genesis_block(Network::Testnet).header.block_hash(), None, Arc::clone(&logger));
1102 // Build network from our_id to node7:
1104 // -1(1)2- node0 -1(3)2-
1106 // our_id -1(12)2- node7 -1(13)2--- node2
1108 // -1(2)2- node1 -1(4)2-
1111 // chan1 1-to-2: disabled
1112 // chan1 2-to-1: enabled, 0 fee
1114 // chan2 1-to-2: enabled, ignored fee
1115 // chan2 2-to-1: enabled, 0 fee
1117 // chan3 1-to-2: enabled, 0 fee
1118 // chan3 2-to-1: enabled, 100 msat fee
1120 // chan4 1-to-2: enabled, 100% fee
1121 // chan4 2-to-1: enabled, 0 fee
1123 // chan12 1-to-2: enabled, ignored fee
1124 // chan12 2-to-1: enabled, 0 fee
1126 // chan13 1-to-2: enabled, 200% fee
1127 // chan13 2-to-1: enabled, 0 fee
1130 // -1(5)2- node3 -1(8)2--
1134 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1136 // -1(7)2- node5 -1(10)2-
1138 // chan5 1-to-2: enabled, 100 msat fee
1139 // chan5 2-to-1: enabled, 0 fee
1141 // chan6 1-to-2: enabled, 0 fee
1142 // chan6 2-to-1: enabled, 0 fee
1144 // chan7 1-to-2: enabled, 100% fee
1145 // chan7 2-to-1: enabled, 0 fee
1147 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1148 // chan8 2-to-1: enabled, 0 fee
1150 // chan9 1-to-2: enabled, 1001 msat fee
1151 // chan9 2-to-1: enabled, 0 fee
1153 // chan10 1-to-2: enabled, 0 fee
1154 // chan10 2-to-1: enabled, 0 fee
1156 // chan11 1-to-2: enabled, 0 fee
1157 // chan11 2-to-1: enabled, 0 fee
1159 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1161 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1162 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1163 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1164 short_channel_id: 1,
1167 cltv_expiry_delta: 0,
1168 htlc_minimum_msat: 0,
1169 htlc_maximum_msat: OptionalField::Absent,
1171 fee_proportional_millionths: 0,
1172 excess_data: Vec::new()
1175 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1177 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1178 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1180 short_channel_id: 2,
1183 cltv_expiry_delta: u16::max_value(),
1184 htlc_minimum_msat: 0,
1185 htlc_maximum_msat: OptionalField::Absent,
1186 fee_base_msat: u32::max_value(),
1187 fee_proportional_millionths: u32::max_value(),
1188 excess_data: Vec::new()
1190 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1191 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1192 short_channel_id: 2,
1195 cltv_expiry_delta: 0,
1196 htlc_minimum_msat: 0,
1197 htlc_maximum_msat: OptionalField::Absent,
1199 fee_proportional_millionths: 0,
1200 excess_data: Vec::new()
1203 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1205 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1206 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1207 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1208 short_channel_id: 12,
1211 cltv_expiry_delta: u16::max_value(),
1212 htlc_minimum_msat: 0,
1213 htlc_maximum_msat: OptionalField::Absent,
1214 fee_base_msat: u32::max_value(),
1215 fee_proportional_millionths: u32::max_value(),
1216 excess_data: Vec::new()
1218 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1219 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1220 short_channel_id: 12,
1223 cltv_expiry_delta: 0,
1224 htlc_minimum_msat: 0,
1225 htlc_maximum_msat: OptionalField::Absent,
1227 fee_proportional_millionths: 0,
1228 excess_data: Vec::new()
1231 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1233 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1234 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1235 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1236 short_channel_id: 3,
1239 cltv_expiry_delta: (3 << 8) | 1,
1240 htlc_minimum_msat: 0,
1241 htlc_maximum_msat: OptionalField::Absent,
1243 fee_proportional_millionths: 0,
1244 excess_data: Vec::new()
1246 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1247 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1248 short_channel_id: 3,
1251 cltv_expiry_delta: (3 << 8) | 2,
1252 htlc_minimum_msat: 0,
1253 htlc_maximum_msat: OptionalField::Absent,
1255 fee_proportional_millionths: 0,
1256 excess_data: Vec::new()
1259 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1260 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1261 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1262 short_channel_id: 4,
1265 cltv_expiry_delta: (4 << 8) | 1,
1266 htlc_minimum_msat: 0,
1267 htlc_maximum_msat: OptionalField::Absent,
1269 fee_proportional_millionths: 1000000,
1270 excess_data: Vec::new()
1272 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1273 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1274 short_channel_id: 4,
1277 cltv_expiry_delta: (4 << 8) | 2,
1278 htlc_minimum_msat: 0,
1279 htlc_maximum_msat: OptionalField::Absent,
1281 fee_proportional_millionths: 0,
1282 excess_data: Vec::new()
1285 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1286 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1288 short_channel_id: 13,
1291 cltv_expiry_delta: (13 << 8) | 1,
1292 htlc_minimum_msat: 0,
1293 htlc_maximum_msat: OptionalField::Absent,
1295 fee_proportional_millionths: 2000000,
1296 excess_data: Vec::new()
1298 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1299 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1300 short_channel_id: 13,
1303 cltv_expiry_delta: (13 << 8) | 2,
1304 htlc_minimum_msat: 0,
1305 htlc_maximum_msat: OptionalField::Absent,
1307 fee_proportional_millionths: 0,
1308 excess_data: Vec::new()
1311 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1313 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1314 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1316 short_channel_id: 6,
1319 cltv_expiry_delta: (6 << 8) | 1,
1320 htlc_minimum_msat: 0,
1321 htlc_maximum_msat: OptionalField::Absent,
1323 fee_proportional_millionths: 0,
1324 excess_data: Vec::new()
1326 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1327 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1328 short_channel_id: 6,
1331 cltv_expiry_delta: (6 << 8) | 2,
1332 htlc_minimum_msat: 0,
1333 htlc_maximum_msat: OptionalField::Absent,
1335 fee_proportional_millionths: 0,
1336 excess_data: Vec::new(),
1339 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1340 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1341 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1342 short_channel_id: 11,
1345 cltv_expiry_delta: (11 << 8) | 1,
1346 htlc_minimum_msat: 0,
1347 htlc_maximum_msat: OptionalField::Absent,
1349 fee_proportional_millionths: 0,
1350 excess_data: Vec::new()
1352 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1353 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1354 short_channel_id: 11,
1357 cltv_expiry_delta: (11 << 8) | 2,
1358 htlc_minimum_msat: 0,
1359 htlc_maximum_msat: OptionalField::Absent,
1361 fee_proportional_millionths: 0,
1362 excess_data: Vec::new()
1365 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1367 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1369 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1370 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1371 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1372 short_channel_id: 7,
1375 cltv_expiry_delta: (7 << 8) | 1,
1376 htlc_minimum_msat: 0,
1377 htlc_maximum_msat: OptionalField::Absent,
1379 fee_proportional_millionths: 1000000,
1380 excess_data: Vec::new()
1382 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1383 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1384 short_channel_id: 7,
1387 cltv_expiry_delta: (7 << 8) | 2,
1388 htlc_minimum_msat: 0,
1389 htlc_maximum_msat: OptionalField::Absent,
1391 fee_proportional_millionths: 0,
1392 excess_data: Vec::new()
1395 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1397 (secp_ctx, net_graph_msg_handler, chain_monitor, logger)
1401 fn simple_route_test() {
1402 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1403 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1405 // Simple route to 2 via 1
1407 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 0, 42, Arc::clone(&logger)) {
1408 assert_eq!(err, "Cannot send a payment of 0 msat");
1409 } else { panic!(); }
1411 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1412 assert_eq!(route.paths[0].len(), 2);
1414 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1415 assert_eq!(route.paths[0][0].short_channel_id, 2);
1416 assert_eq!(route.paths[0][0].fee_msat, 100);
1417 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1418 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1419 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1421 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1422 assert_eq!(route.paths[0][1].short_channel_id, 4);
1423 assert_eq!(route.paths[0][1].fee_msat, 100);
1424 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1425 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1426 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1430 fn invalid_first_hop_test() {
1431 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1432 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1434 // Simple route to 2 via 1
1436 let our_chans = vec![channelmanager::ChannelDetails {
1437 channel_id: [0; 32],
1438 short_channel_id: Some(2),
1439 remote_network_id: our_id,
1440 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1441 channel_value_satoshis: 100000,
1443 outbound_capacity_msat: 100000,
1444 inbound_capacity_msat: 100000,
1448 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)) {
1449 assert_eq!(err, "First hop cannot have our_node_id as a destination.");
1450 } else { panic!(); }
1452 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1453 assert_eq!(route.paths[0].len(), 2);
1457 fn htlc_minimum_test() {
1458 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1459 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1461 // Simple route to 2 via 1
1463 // Disable other paths
1464 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1465 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1466 short_channel_id: 12,
1468 flags: 2, // to disable
1469 cltv_expiry_delta: 0,
1470 htlc_minimum_msat: 0,
1471 htlc_maximum_msat: OptionalField::Absent,
1473 fee_proportional_millionths: 0,
1474 excess_data: Vec::new()
1476 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1477 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1478 short_channel_id: 3,
1480 flags: 2, // to disable
1481 cltv_expiry_delta: 0,
1482 htlc_minimum_msat: 0,
1483 htlc_maximum_msat: OptionalField::Absent,
1485 fee_proportional_millionths: 0,
1486 excess_data: Vec::new()
1488 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1489 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1490 short_channel_id: 13,
1492 flags: 2, // to disable
1493 cltv_expiry_delta: 0,
1494 htlc_minimum_msat: 0,
1495 htlc_maximum_msat: OptionalField::Absent,
1497 fee_proportional_millionths: 0,
1498 excess_data: Vec::new()
1500 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1501 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1502 short_channel_id: 6,
1504 flags: 2, // to disable
1505 cltv_expiry_delta: 0,
1506 htlc_minimum_msat: 0,
1507 htlc_maximum_msat: OptionalField::Absent,
1509 fee_proportional_millionths: 0,
1510 excess_data: Vec::new()
1512 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1513 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1514 short_channel_id: 7,
1516 flags: 2, // to disable
1517 cltv_expiry_delta: 0,
1518 htlc_minimum_msat: 0,
1519 htlc_maximum_msat: OptionalField::Absent,
1521 fee_proportional_millionths: 0,
1522 excess_data: Vec::new()
1525 // Check against amount_to_transfer_over_msat.
1526 // Set minimal HTLC of 200_000_000 msat.
1527 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1528 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1529 short_channel_id: 2,
1532 cltv_expiry_delta: 0,
1533 htlc_minimum_msat: 200_000_000,
1534 htlc_maximum_msat: OptionalField::Absent,
1536 fee_proportional_millionths: 0,
1537 excess_data: Vec::new()
1540 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
1542 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1543 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1544 short_channel_id: 4,
1547 cltv_expiry_delta: 0,
1548 htlc_minimum_msat: 0,
1549 htlc_maximum_msat: OptionalField::Present(199_999_999),
1551 fee_proportional_millionths: 0,
1552 excess_data: Vec::new()
1555 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
1556 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)) {
1557 assert_eq!(err, "Failed to find a path to the given destination");
1558 } else { panic!(); }
1560 // Lift the restriction on the first hop.
1561 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1562 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1563 short_channel_id: 2,
1566 cltv_expiry_delta: 0,
1567 htlc_minimum_msat: 0,
1568 htlc_maximum_msat: OptionalField::Absent,
1570 fee_proportional_millionths: 0,
1571 excess_data: Vec::new()
1574 // A payment above the minimum should pass
1575 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 199_999_999, 42, Arc::clone(&logger)).unwrap();
1576 assert_eq!(route.paths[0].len(), 2);
1580 fn htlc_minimum_overpay_test() {
1581 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1582 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1584 // A route to node#2 via two paths.
1585 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
1586 // Thus, they can't send 60 without overpaying.
1587 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1588 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1589 short_channel_id: 2,
1592 cltv_expiry_delta: 0,
1593 htlc_minimum_msat: 35_000,
1594 htlc_maximum_msat: OptionalField::Present(40_000),
1596 fee_proportional_millionths: 0,
1597 excess_data: Vec::new()
1599 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1600 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1601 short_channel_id: 12,
1604 cltv_expiry_delta: 0,
1605 htlc_minimum_msat: 35_000,
1606 htlc_maximum_msat: OptionalField::Present(40_000),
1608 fee_proportional_millionths: 0,
1609 excess_data: Vec::new()
1613 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1614 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1615 short_channel_id: 13,
1618 cltv_expiry_delta: 0,
1619 htlc_minimum_msat: 0,
1620 htlc_maximum_msat: OptionalField::Absent,
1622 fee_proportional_millionths: 0,
1623 excess_data: Vec::new()
1625 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1626 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1627 short_channel_id: 4,
1630 cltv_expiry_delta: 0,
1631 htlc_minimum_msat: 0,
1632 htlc_maximum_msat: OptionalField::Absent,
1634 fee_proportional_millionths: 0,
1635 excess_data: Vec::new()
1638 // Disable other paths
1639 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1640 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1641 short_channel_id: 1,
1643 flags: 2, // to disable
1644 cltv_expiry_delta: 0,
1645 htlc_minimum_msat: 0,
1646 htlc_maximum_msat: OptionalField::Absent,
1648 fee_proportional_millionths: 0,
1649 excess_data: Vec::new()
1652 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1653 // Overpay fees to hit htlc_minimum_msat.
1654 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
1655 // TODO: this could be better balanced to overpay 10k and not 15k.
1656 assert_eq!(overpaid_fees, 15_000);
1658 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
1659 // while taking even more fee to match htlc_minimum_msat.
1660 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1661 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1662 short_channel_id: 12,
1665 cltv_expiry_delta: 0,
1666 htlc_minimum_msat: 65_000,
1667 htlc_maximum_msat: OptionalField::Present(80_000),
1669 fee_proportional_millionths: 0,
1670 excess_data: Vec::new()
1672 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1674 short_channel_id: 2,
1677 cltv_expiry_delta: 0,
1678 htlc_minimum_msat: 0,
1679 htlc_maximum_msat: OptionalField::Absent,
1681 fee_proportional_millionths: 0,
1682 excess_data: Vec::new()
1684 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1685 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1686 short_channel_id: 4,
1689 cltv_expiry_delta: 0,
1690 htlc_minimum_msat: 0,
1691 htlc_maximum_msat: OptionalField::Absent,
1693 fee_proportional_millionths: 100_000,
1694 excess_data: Vec::new()
1697 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 60_000, 42, Arc::clone(&logger)).unwrap();
1698 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
1699 assert_eq!(route.paths.len(), 1);
1700 assert_eq!(route.paths[0][0].short_channel_id, 12);
1701 let fees = route.paths[0][0].fee_msat;
1702 assert_eq!(fees, 5_000);
1704 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
1705 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
1706 // the other channel.
1707 assert_eq!(route.paths.len(), 1);
1708 assert_eq!(route.paths[0][0].short_channel_id, 2);
1709 let fees = route.paths[0][0].fee_msat;
1710 assert_eq!(fees, 5_000);
1714 fn disable_channels_test() {
1715 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1716 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1718 // // Disable channels 4 and 12 by flags=2
1719 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1720 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1721 short_channel_id: 4,
1723 flags: 2, // to disable
1724 cltv_expiry_delta: 0,
1725 htlc_minimum_msat: 0,
1726 htlc_maximum_msat: OptionalField::Absent,
1728 fee_proportional_millionths: 0,
1729 excess_data: Vec::new()
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: 12,
1735 flags: 2, // to disable
1736 cltv_expiry_delta: 0,
1737 htlc_minimum_msat: 0,
1738 htlc_maximum_msat: OptionalField::Absent,
1740 fee_proportional_millionths: 0,
1741 excess_data: Vec::new()
1744 // If all the channels require some features we don't understand, route should fail
1745 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1746 assert_eq!(err, "Failed to find a path to the given destination");
1747 } else { panic!(); }
1749 // If we specify a channel to node7, that overrides our local channel view and that gets used
1750 let our_chans = vec![channelmanager::ChannelDetails {
1751 channel_id: [0; 32],
1752 short_channel_id: Some(42),
1753 remote_network_id: nodes[7].clone(),
1754 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1755 channel_value_satoshis: 0,
1757 outbound_capacity_msat: 250_000_000,
1758 inbound_capacity_msat: 0,
1761 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1762 assert_eq!(route.paths[0].len(), 2);
1764 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1765 assert_eq!(route.paths[0][0].short_channel_id, 42);
1766 assert_eq!(route.paths[0][0].fee_msat, 200);
1767 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1768 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1769 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1771 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1772 assert_eq!(route.paths[0][1].short_channel_id, 13);
1773 assert_eq!(route.paths[0][1].fee_msat, 100);
1774 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1775 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1776 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1780 fn disable_node_test() {
1781 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1782 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1784 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
1785 let mut unknown_features = NodeFeatures::known();
1786 unknown_features.set_required_unknown_bits();
1787 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
1788 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
1789 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
1791 // If all nodes require some features we don't understand, route should fail
1792 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
1793 assert_eq!(err, "Failed to find a path to the given destination");
1794 } else { panic!(); }
1796 // If we specify a channel to node7, that overrides our local channel view and that gets used
1797 let our_chans = vec![channelmanager::ChannelDetails {
1798 channel_id: [0; 32],
1799 short_channel_id: Some(42),
1800 remote_network_id: nodes[7].clone(),
1801 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1802 channel_value_satoshis: 0,
1804 outbound_capacity_msat: 250_000_000,
1805 inbound_capacity_msat: 0,
1808 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1809 assert_eq!(route.paths[0].len(), 2);
1811 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1812 assert_eq!(route.paths[0][0].short_channel_id, 42);
1813 assert_eq!(route.paths[0][0].fee_msat, 200);
1814 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1815 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
1816 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1818 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1819 assert_eq!(route.paths[0][1].short_channel_id, 13);
1820 assert_eq!(route.paths[0][1].fee_msat, 100);
1821 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1822 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1823 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1825 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
1826 // naively) assume that the user checked the feature bits on the invoice, which override
1827 // the node_announcement.
1831 fn our_chans_test() {
1832 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1833 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1835 // Route to 1 via 2 and 3 because our channel to 1 is disabled
1836 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0], None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1837 assert_eq!(route.paths[0].len(), 3);
1839 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1840 assert_eq!(route.paths[0][0].short_channel_id, 2);
1841 assert_eq!(route.paths[0][0].fee_msat, 200);
1842 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1843 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1844 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1846 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1847 assert_eq!(route.paths[0][1].short_channel_id, 4);
1848 assert_eq!(route.paths[0][1].fee_msat, 100);
1849 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
1850 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1851 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1853 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
1854 assert_eq!(route.paths[0][2].short_channel_id, 3);
1855 assert_eq!(route.paths[0][2].fee_msat, 100);
1856 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
1857 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
1858 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
1860 // If we specify a channel to node7, that overrides our local channel view and that gets used
1861 let our_chans = vec![channelmanager::ChannelDetails {
1862 channel_id: [0; 32],
1863 short_channel_id: Some(42),
1864 remote_network_id: nodes[7].clone(),
1865 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1866 channel_value_satoshis: 0,
1868 outbound_capacity_msat: 250_000_000,
1869 inbound_capacity_msat: 0,
1872 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1873 assert_eq!(route.paths[0].len(), 2);
1875 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
1876 assert_eq!(route.paths[0][0].short_channel_id, 42);
1877 assert_eq!(route.paths[0][0].fee_msat, 200);
1878 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1879 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1880 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
1882 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1883 assert_eq!(route.paths[0][1].short_channel_id, 13);
1884 assert_eq!(route.paths[0][1].fee_msat, 100);
1885 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1886 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1887 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
1890 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
1891 let zero_fees = RoutingFees {
1893 proportional_millionths: 0,
1896 src_node_id: nodes[3].clone(),
1897 short_channel_id: 8,
1899 cltv_expiry_delta: (8 << 8) | 1,
1900 htlc_minimum_msat: None,
1901 htlc_maximum_msat: None,
1903 src_node_id: nodes[4].clone(),
1904 short_channel_id: 9,
1907 proportional_millionths: 0,
1909 cltv_expiry_delta: (9 << 8) | 1,
1910 htlc_minimum_msat: None,
1911 htlc_maximum_msat: None,
1913 src_node_id: nodes[5].clone(),
1914 short_channel_id: 10,
1916 cltv_expiry_delta: (10 << 8) | 1,
1917 htlc_minimum_msat: None,
1918 htlc_maximum_msat: None,
1923 fn last_hops_test() {
1924 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1925 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1927 // Simple test across 2, 3, 5, and 4 via a last_hop channel
1929 // First check that lst hop can't have its source as the payee.
1930 let invalid_last_hop = RouteHint {
1931 src_node_id: nodes[6],
1932 short_channel_id: 8,
1935 proportional_millionths: 0,
1937 cltv_expiry_delta: (8 << 8) | 1,
1938 htlc_minimum_msat: None,
1939 htlc_maximum_msat: None,
1942 let mut invalid_last_hops = last_hops(&nodes);
1943 invalid_last_hops.push(invalid_last_hop);
1945 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, &invalid_last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)) {
1946 assert_eq!(err, "Last hop cannot have a payee as a source.");
1947 } else { panic!(); }
1950 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, &last_hops(&nodes).iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
1951 assert_eq!(route.paths[0].len(), 5);
1953 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1954 assert_eq!(route.paths[0][0].short_channel_id, 2);
1955 assert_eq!(route.paths[0][0].fee_msat, 100);
1956 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1957 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1958 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1960 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1961 assert_eq!(route.paths[0][1].short_channel_id, 4);
1962 assert_eq!(route.paths[0][1].fee_msat, 0);
1963 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1964 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1965 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1967 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
1968 assert_eq!(route.paths[0][2].short_channel_id, 6);
1969 assert_eq!(route.paths[0][2].fee_msat, 0);
1970 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1971 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
1972 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
1974 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
1975 assert_eq!(route.paths[0][3].short_channel_id, 11);
1976 assert_eq!(route.paths[0][3].fee_msat, 0);
1977 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1978 // If we have a peer in the node map, we'll use their features here since we don't have
1979 // a way of figuring out their features from the invoice:
1980 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
1981 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
1983 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
1984 assert_eq!(route.paths[0][4].short_channel_id, 8);
1985 assert_eq!(route.paths[0][4].fee_msat, 100);
1986 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1987 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
1988 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
1992 fn our_chans_last_hop_connect_test() {
1993 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
1994 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1996 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1997 let our_chans = vec![channelmanager::ChannelDetails {
1998 channel_id: [0; 32],
1999 short_channel_id: Some(42),
2000 remote_network_id: nodes[3].clone(),
2001 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2002 channel_value_satoshis: 0,
2004 outbound_capacity_msat: 250_000_000,
2005 inbound_capacity_msat: 0,
2008 let mut last_hops = last_hops(&nodes);
2009 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2010 assert_eq!(route.paths[0].len(), 2);
2012 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2013 assert_eq!(route.paths[0][0].short_channel_id, 42);
2014 assert_eq!(route.paths[0][0].fee_msat, 0);
2015 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2016 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2017 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2019 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2020 assert_eq!(route.paths[0][1].short_channel_id, 8);
2021 assert_eq!(route.paths[0][1].fee_msat, 100);
2022 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2023 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2024 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2026 last_hops[0].fees.base_msat = 1000;
2028 // Revert to via 6 as the fee on 8 goes up
2029 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::clone(&logger)).unwrap();
2030 assert_eq!(route.paths[0].len(), 4);
2032 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2033 assert_eq!(route.paths[0][0].short_channel_id, 2);
2034 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2035 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2036 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2037 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2039 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2040 assert_eq!(route.paths[0][1].short_channel_id, 4);
2041 assert_eq!(route.paths[0][1].fee_msat, 100);
2042 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2043 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2044 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2046 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2047 assert_eq!(route.paths[0][2].short_channel_id, 7);
2048 assert_eq!(route.paths[0][2].fee_msat, 0);
2049 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2050 // If we have a peer in the node map, we'll use their features here since we don't have
2051 // a way of figuring out their features from the invoice:
2052 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2053 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2055 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2056 assert_eq!(route.paths[0][3].short_channel_id, 10);
2057 assert_eq!(route.paths[0][3].fee_msat, 100);
2058 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2059 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2060 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2062 // ...but still use 8 for larger payments as 6 has a variable feerate
2063 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[6], None, &last_hops.iter().collect::<Vec<_>>(), 2000, 42, Arc::clone(&logger)).unwrap();
2064 assert_eq!(route.paths[0].len(), 5);
2066 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2067 assert_eq!(route.paths[0][0].short_channel_id, 2);
2068 assert_eq!(route.paths[0][0].fee_msat, 3000);
2069 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2070 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2071 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2073 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2074 assert_eq!(route.paths[0][1].short_channel_id, 4);
2075 assert_eq!(route.paths[0][1].fee_msat, 0);
2076 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2077 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2078 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2080 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2081 assert_eq!(route.paths[0][2].short_channel_id, 6);
2082 assert_eq!(route.paths[0][2].fee_msat, 0);
2083 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2084 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2085 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2087 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2088 assert_eq!(route.paths[0][3].short_channel_id, 11);
2089 assert_eq!(route.paths[0][3].fee_msat, 1000);
2090 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2091 // If we have a peer in the node map, we'll use their features here since we don't have
2092 // a way of figuring out their features from the invoice:
2093 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2094 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2096 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2097 assert_eq!(route.paths[0][4].short_channel_id, 8);
2098 assert_eq!(route.paths[0][4].fee_msat, 2000);
2099 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2100 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2101 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2105 fn unannounced_path_test() {
2106 // We should be able to send a payment to a destination without any help of a routing graph
2107 // if we have a channel with a common counterparty that appears in the first and last hop
2109 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2110 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2111 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2113 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2114 let last_hops = vec![RouteHint {
2115 src_node_id: middle_node_id,
2116 short_channel_id: 8,
2119 proportional_millionths: 0,
2121 cltv_expiry_delta: (8 << 8) | 1,
2122 htlc_minimum_msat: None,
2123 htlc_maximum_msat: None,
2125 let our_chans = vec![channelmanager::ChannelDetails {
2126 channel_id: [0; 32],
2127 short_channel_id: Some(42),
2128 remote_network_id: middle_node_id,
2129 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2130 channel_value_satoshis: 100000,
2132 outbound_capacity_msat: 100000,
2133 inbound_capacity_msat: 100000,
2136 let route = get_route(&source_node_id, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), &target_node_id, Some(&our_chans.iter().collect::<Vec<_>>()), &last_hops.iter().collect::<Vec<_>>(), 100, 42, Arc::new(test_utils::TestLogger::new())).unwrap();
2138 assert_eq!(route.paths[0].len(), 2);
2140 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2141 assert_eq!(route.paths[0][0].short_channel_id, 42);
2142 assert_eq!(route.paths[0][0].fee_msat, 1000);
2143 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2144 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2145 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2147 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2148 assert_eq!(route.paths[0][1].short_channel_id, 8);
2149 assert_eq!(route.paths[0][1].fee_msat, 100);
2150 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2151 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2152 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2156 fn available_amount_while_routing_test() {
2157 // Tests whether we choose the correct available channel amount while routing.
2159 let (secp_ctx, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2160 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2162 // We will use a simple single-path route from
2163 // our node to node2 via node0: channels {1, 3}.
2165 // First disable all other paths.
2166 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2167 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2168 short_channel_id: 2,
2171 cltv_expiry_delta: 0,
2172 htlc_minimum_msat: 0,
2173 htlc_maximum_msat: OptionalField::Present(100_000),
2175 fee_proportional_millionths: 0,
2176 excess_data: Vec::new()
2178 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2179 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2180 short_channel_id: 12,
2183 cltv_expiry_delta: 0,
2184 htlc_minimum_msat: 0,
2185 htlc_maximum_msat: OptionalField::Present(100_000),
2187 fee_proportional_millionths: 0,
2188 excess_data: Vec::new()
2191 // Make the first channel (#1) very permissive,
2192 // and we will be testing all limits on the second channel.
2193 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2194 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2195 short_channel_id: 1,
2198 cltv_expiry_delta: 0,
2199 htlc_minimum_msat: 0,
2200 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2202 fee_proportional_millionths: 0,
2203 excess_data: Vec::new()
2206 // First, let's see if routing works if we have absolutely no idea about the available amount.
2207 // In this case, it should be set to 250_000 sats.
2208 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2209 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2210 short_channel_id: 3,
2213 cltv_expiry_delta: 0,
2214 htlc_minimum_msat: 0,
2215 htlc_maximum_msat: OptionalField::Absent,
2217 fee_proportional_millionths: 0,
2218 excess_data: Vec::new()
2222 // Attempt to route more than available results in a failure.
2223 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 250_000_001, 42, Arc::clone(&logger)) {
2224 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2225 } else { panic!(); }
2229 // Now, attempt to route an exact amount we have should be fine.
2230 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 250_000_000, 42, Arc::clone(&logger)).unwrap();
2231 assert_eq!(route.paths.len(), 1);
2232 let path = route.paths.last().unwrap();
2233 assert_eq!(path.len(), 2);
2234 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2235 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
2238 // Check that setting outbound_capacity_msat in first_hops limits the channels.
2239 // Disable channel #1 and use another first hop.
2240 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2241 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2242 short_channel_id: 1,
2245 cltv_expiry_delta: 0,
2246 htlc_minimum_msat: 0,
2247 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2249 fee_proportional_millionths: 0,
2250 excess_data: Vec::new()
2253 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
2254 let our_chans = vec![channelmanager::ChannelDetails {
2255 channel_id: [0; 32],
2256 short_channel_id: Some(42),
2257 remote_network_id: nodes[0].clone(),
2258 counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
2259 channel_value_satoshis: 0,
2261 outbound_capacity_msat: 200_000_000,
2262 inbound_capacity_msat: 0,
2267 // Attempt to route more than available results in a failure.
2268 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_001, 42, Arc::clone(&logger)) {
2269 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2270 } else { panic!(); }
2274 // Now, attempt to route an exact amount we have should be fine.
2275 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], Some(&our_chans.iter().collect::<Vec<_>>()), &Vec::new(), 200_000_000, 42, Arc::clone(&logger)).unwrap();
2276 assert_eq!(route.paths.len(), 1);
2277 let path = route.paths.last().unwrap();
2278 assert_eq!(path.len(), 2);
2279 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2280 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
2283 // Enable channel #1 back.
2284 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2285 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2286 short_channel_id: 1,
2289 cltv_expiry_delta: 0,
2290 htlc_minimum_msat: 0,
2291 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
2293 fee_proportional_millionths: 0,
2294 excess_data: Vec::new()
2298 // Now let's see if routing works if we know only htlc_maximum_msat.
2299 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2300 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2301 short_channel_id: 3,
2304 cltv_expiry_delta: 0,
2305 htlc_minimum_msat: 0,
2306 htlc_maximum_msat: OptionalField::Present(15_000),
2308 fee_proportional_millionths: 0,
2309 excess_data: Vec::new()
2313 // Attempt to route more than available results in a failure.
2314 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2315 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2316 } else { panic!(); }
2320 // Now, attempt to route an exact amount we have should be fine.
2321 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2322 assert_eq!(route.paths.len(), 1);
2323 let path = route.paths.last().unwrap();
2324 assert_eq!(path.len(), 2);
2325 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2326 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2329 // Now let's see if routing works if we know only capacity from the UTXO.
2331 // We can't change UTXO capacity on the fly, so we'll disable
2332 // the existing channel and add another one with the capacity we need.
2333 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2334 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2335 short_channel_id: 3,
2338 cltv_expiry_delta: 0,
2339 htlc_minimum_msat: 0,
2340 htlc_maximum_msat: OptionalField::Absent,
2342 fee_proportional_millionths: 0,
2343 excess_data: Vec::new()
2346 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
2347 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
2348 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
2349 .push_opcode(opcodes::all::OP_PUSHNUM_2)
2350 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
2352 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
2353 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
2355 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
2356 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2357 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2358 short_channel_id: 333,
2361 cltv_expiry_delta: (3 << 8) | 1,
2362 htlc_minimum_msat: 0,
2363 htlc_maximum_msat: OptionalField::Absent,
2365 fee_proportional_millionths: 0,
2366 excess_data: Vec::new()
2368 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2369 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2370 short_channel_id: 333,
2373 cltv_expiry_delta: (3 << 8) | 2,
2374 htlc_minimum_msat: 0,
2375 htlc_maximum_msat: OptionalField::Absent,
2377 fee_proportional_millionths: 0,
2378 excess_data: Vec::new()
2382 // Attempt to route more than available results in a failure.
2383 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 15_001, 42, Arc::clone(&logger)) {
2384 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2385 } else { panic!(); }
2389 // Now, attempt to route an exact amount we have should be fine.
2390 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 15_000, 42, Arc::clone(&logger)).unwrap();
2391 assert_eq!(route.paths.len(), 1);
2392 let path = route.paths.last().unwrap();
2393 assert_eq!(path.len(), 2);
2394 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2395 assert_eq!(path.last().unwrap().fee_msat, 15_000);
2398 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
2399 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2400 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2401 short_channel_id: 333,
2404 cltv_expiry_delta: 0,
2405 htlc_minimum_msat: 0,
2406 htlc_maximum_msat: OptionalField::Present(10_000),
2408 fee_proportional_millionths: 0,
2409 excess_data: Vec::new()
2413 // Attempt to route more than available results in a failure.
2414 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 10_001, 42, Arc::clone(&logger)) {
2415 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2416 } else { panic!(); }
2420 // Now, attempt to route an exact amount we have should be fine.
2421 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 10_000, 42, Arc::clone(&logger)).unwrap();
2422 assert_eq!(route.paths.len(), 1);
2423 let path = route.paths.last().unwrap();
2424 assert_eq!(path.len(), 2);
2425 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2426 assert_eq!(path.last().unwrap().fee_msat, 10_000);
2431 fn available_liquidity_last_hop_test() {
2432 // Check that available liquidity properly limits the path even when only
2433 // one of the latter hops is limited.
2434 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2435 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2437 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2438 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
2439 // Total capacity: 50 sats.
2441 // Disable other potential paths.
2442 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2443 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2444 short_channel_id: 2,
2447 cltv_expiry_delta: 0,
2448 htlc_minimum_msat: 0,
2449 htlc_maximum_msat: OptionalField::Present(100_000),
2451 fee_proportional_millionths: 0,
2452 excess_data: Vec::new()
2454 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2455 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2456 short_channel_id: 7,
2459 cltv_expiry_delta: 0,
2460 htlc_minimum_msat: 0,
2461 htlc_maximum_msat: OptionalField::Present(100_000),
2463 fee_proportional_millionths: 0,
2464 excess_data: Vec::new()
2469 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2470 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2471 short_channel_id: 12,
2474 cltv_expiry_delta: 0,
2475 htlc_minimum_msat: 0,
2476 htlc_maximum_msat: OptionalField::Present(100_000),
2478 fee_proportional_millionths: 0,
2479 excess_data: Vec::new()
2481 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2482 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2483 short_channel_id: 13,
2486 cltv_expiry_delta: 0,
2487 htlc_minimum_msat: 0,
2488 htlc_maximum_msat: OptionalField::Present(100_000),
2490 fee_proportional_millionths: 0,
2491 excess_data: Vec::new()
2494 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2495 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2496 short_channel_id: 6,
2499 cltv_expiry_delta: 0,
2500 htlc_minimum_msat: 0,
2501 htlc_maximum_msat: OptionalField::Present(50_000),
2503 fee_proportional_millionths: 0,
2504 excess_data: Vec::new()
2506 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2507 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2508 short_channel_id: 11,
2511 cltv_expiry_delta: 0,
2512 htlc_minimum_msat: 0,
2513 htlc_maximum_msat: OptionalField::Present(100_000),
2515 fee_proportional_millionths: 0,
2516 excess_data: Vec::new()
2519 // Attempt to route more than available results in a failure.
2520 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3], None, &Vec::new(), 60_000, 42, Arc::clone(&logger)) {
2521 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2522 } else { panic!(); }
2526 // Now, attempt to route 49 sats (just a bit below the capacity).
2527 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3], None, &Vec::new(), 49_000, 42, Arc::clone(&logger)).unwrap();
2528 assert_eq!(route.paths.len(), 1);
2529 let mut total_amount_paid_msat = 0;
2530 for path in &route.paths {
2531 assert_eq!(path.len(), 4);
2532 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2533 total_amount_paid_msat += path.last().unwrap().fee_msat;
2535 assert_eq!(total_amount_paid_msat, 49_000);
2539 // Attempt to route an exact amount is also fine
2540 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3], None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2541 assert_eq!(route.paths.len(), 1);
2542 let mut total_amount_paid_msat = 0;
2543 for path in &route.paths {
2544 assert_eq!(path.len(), 4);
2545 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2546 total_amount_paid_msat += path.last().unwrap().fee_msat;
2548 assert_eq!(total_amount_paid_msat, 50_000);
2553 fn ignore_fee_first_hop_test() {
2554 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2555 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2557 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2558 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2559 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2560 short_channel_id: 1,
2563 cltv_expiry_delta: 0,
2564 htlc_minimum_msat: 0,
2565 htlc_maximum_msat: OptionalField::Present(100_000),
2566 fee_base_msat: 1_000_000,
2567 fee_proportional_millionths: 0,
2568 excess_data: Vec::new()
2570 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2571 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2572 short_channel_id: 3,
2575 cltv_expiry_delta: 0,
2576 htlc_minimum_msat: 0,
2577 htlc_maximum_msat: OptionalField::Present(50_000),
2579 fee_proportional_millionths: 0,
2580 excess_data: Vec::new()
2584 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 50_000, 42, Arc::clone(&logger)).unwrap();
2585 assert_eq!(route.paths.len(), 1);
2586 let mut total_amount_paid_msat = 0;
2587 for path in &route.paths {
2588 assert_eq!(path.len(), 2);
2589 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2590 total_amount_paid_msat += path.last().unwrap().fee_msat;
2592 assert_eq!(total_amount_paid_msat, 50_000);
2597 fn simple_mpp_route_test() {
2598 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2599 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2601 // We need a route consisting of 3 paths:
2602 // From our node to node2 via node0, node7, node1 (three paths one hop each).
2603 // To achieve this, the amount being transferred should be around
2604 // the total capacity of these 3 paths.
2606 // First, we set limits on these (previously unlimited) channels.
2607 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
2609 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
2610 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2611 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2612 short_channel_id: 1,
2615 cltv_expiry_delta: 0,
2616 htlc_minimum_msat: 0,
2617 htlc_maximum_msat: OptionalField::Present(100_000),
2619 fee_proportional_millionths: 0,
2620 excess_data: Vec::new()
2622 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2623 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2624 short_channel_id: 3,
2627 cltv_expiry_delta: 0,
2628 htlc_minimum_msat: 0,
2629 htlc_maximum_msat: OptionalField::Present(50_000),
2631 fee_proportional_millionths: 0,
2632 excess_data: Vec::new()
2635 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
2636 // (total limit 60).
2637 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2638 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2639 short_channel_id: 12,
2642 cltv_expiry_delta: 0,
2643 htlc_minimum_msat: 0,
2644 htlc_maximum_msat: OptionalField::Present(60_000),
2646 fee_proportional_millionths: 0,
2647 excess_data: Vec::new()
2649 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2650 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2651 short_channel_id: 13,
2654 cltv_expiry_delta: 0,
2655 htlc_minimum_msat: 0,
2656 htlc_maximum_msat: OptionalField::Present(60_000),
2658 fee_proportional_millionths: 0,
2659 excess_data: Vec::new()
2662 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
2663 // (total capacity 180 sats).
2664 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2665 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2666 short_channel_id: 2,
2669 cltv_expiry_delta: 0,
2670 htlc_minimum_msat: 0,
2671 htlc_maximum_msat: OptionalField::Present(200_000),
2673 fee_proportional_millionths: 0,
2674 excess_data: Vec::new()
2676 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2677 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2678 short_channel_id: 4,
2681 cltv_expiry_delta: 0,
2682 htlc_minimum_msat: 0,
2683 htlc_maximum_msat: OptionalField::Present(180_000),
2685 fee_proportional_millionths: 0,
2686 excess_data: Vec::new()
2690 // Attempt to route more than available results in a failure.
2691 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 300_000, 42, Arc::clone(&logger)) {
2692 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2693 } else { panic!(); }
2697 // Now, attempt to route 250 sats (just a bit below the capacity).
2698 // Our algorithm should provide us with these 3 paths.
2699 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 250_000, 42, Arc::clone(&logger)).unwrap();
2700 assert_eq!(route.paths.len(), 3);
2701 let mut total_amount_paid_msat = 0;
2702 for path in &route.paths {
2703 assert_eq!(path.len(), 2);
2704 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2705 total_amount_paid_msat += path.last().unwrap().fee_msat;
2707 assert_eq!(total_amount_paid_msat, 250_000);
2711 // Attempt to route an exact amount is also fine
2712 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 290_000, 42, Arc::clone(&logger)).unwrap();
2713 assert_eq!(route.paths.len(), 3);
2714 let mut total_amount_paid_msat = 0;
2715 for path in &route.paths {
2716 assert_eq!(path.len(), 2);
2717 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
2718 total_amount_paid_msat += path.last().unwrap().fee_msat;
2720 assert_eq!(total_amount_paid_msat, 290_000);
2725 fn long_mpp_route_test() {
2726 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2727 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2729 // We need a route consisting of 3 paths:
2730 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2731 // Note that these paths overlap (channels 5, 12, 13).
2732 // We will route 300 sats.
2733 // Each path will have 100 sats capacity, those channels which
2734 // are used twice will have 200 sats capacity.
2736 // Disable other potential paths.
2737 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2738 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2739 short_channel_id: 2,
2742 cltv_expiry_delta: 0,
2743 htlc_minimum_msat: 0,
2744 htlc_maximum_msat: OptionalField::Present(100_000),
2746 fee_proportional_millionths: 0,
2747 excess_data: Vec::new()
2749 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2750 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2751 short_channel_id: 7,
2754 cltv_expiry_delta: 0,
2755 htlc_minimum_msat: 0,
2756 htlc_maximum_msat: OptionalField::Present(100_000),
2758 fee_proportional_millionths: 0,
2759 excess_data: Vec::new()
2762 // Path via {node0, node2} is channels {1, 3, 5}.
2763 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2764 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2765 short_channel_id: 1,
2768 cltv_expiry_delta: 0,
2769 htlc_minimum_msat: 0,
2770 htlc_maximum_msat: OptionalField::Present(100_000),
2772 fee_proportional_millionths: 0,
2773 excess_data: Vec::new()
2775 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2776 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2777 short_channel_id: 3,
2780 cltv_expiry_delta: 0,
2781 htlc_minimum_msat: 0,
2782 htlc_maximum_msat: OptionalField::Present(100_000),
2784 fee_proportional_millionths: 0,
2785 excess_data: Vec::new()
2788 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2789 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2790 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2791 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2792 short_channel_id: 5,
2795 cltv_expiry_delta: 0,
2796 htlc_minimum_msat: 0,
2797 htlc_maximum_msat: OptionalField::Present(200_000),
2799 fee_proportional_millionths: 0,
2800 excess_data: Vec::new()
2803 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2804 // Add 100 sats to the capacities of {12, 13}, because these channels
2805 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2806 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2807 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2808 short_channel_id: 12,
2811 cltv_expiry_delta: 0,
2812 htlc_minimum_msat: 0,
2813 htlc_maximum_msat: OptionalField::Present(200_000),
2815 fee_proportional_millionths: 0,
2816 excess_data: Vec::new()
2818 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2819 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2820 short_channel_id: 13,
2823 cltv_expiry_delta: 0,
2824 htlc_minimum_msat: 0,
2825 htlc_maximum_msat: OptionalField::Present(200_000),
2827 fee_proportional_millionths: 0,
2828 excess_data: Vec::new()
2831 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2832 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2833 short_channel_id: 6,
2836 cltv_expiry_delta: 0,
2837 htlc_minimum_msat: 0,
2838 htlc_maximum_msat: OptionalField::Present(100_000),
2840 fee_proportional_millionths: 0,
2841 excess_data: Vec::new()
2843 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
2844 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2845 short_channel_id: 11,
2848 cltv_expiry_delta: 0,
2849 htlc_minimum_msat: 0,
2850 htlc_maximum_msat: OptionalField::Present(100_000),
2852 fee_proportional_millionths: 0,
2853 excess_data: Vec::new()
2856 // Path via {node7, node2} is channels {12, 13, 5}.
2857 // We already limited them to 200 sats (they are used twice for 100 sats).
2858 // Nothing to do here.
2861 // Attempt to route more than available results in a failure.
2862 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3], None, &Vec::new(), 350_000, 42, Arc::clone(&logger)) {
2863 assert_eq!(err, "Failed to find a sufficient route to the given destination");
2864 } else { panic!(); }
2868 // Now, attempt to route 300 sats (exact amount we can route).
2869 // Our algorithm should provide us with these 3 paths, 100 sats each.
2870 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3], None, &Vec::new(), 300_000, 42, Arc::clone(&logger)).unwrap();
2871 assert_eq!(route.paths.len(), 3);
2873 let mut total_amount_paid_msat = 0;
2874 for path in &route.paths {
2875 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
2876 total_amount_paid_msat += path.last().unwrap().fee_msat;
2878 assert_eq!(total_amount_paid_msat, 300_000);
2884 fn mpp_cheaper_route_test() {
2885 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
2886 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2888 // This test checks that if we have two cheaper paths and one more expensive path,
2889 // so that liquidity-wise any 2 of 3 combination is sufficient,
2890 // two cheaper paths will be taken.
2891 // These paths have equal available liquidity.
2893 // We need a combination of 3 paths:
2894 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
2895 // Note that these paths overlap (channels 5, 12, 13).
2896 // Each path will have 100 sats capacity, those channels which
2897 // are used twice will have 200 sats capacity.
2899 // Disable other potential paths.
2900 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2901 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2902 short_channel_id: 2,
2905 cltv_expiry_delta: 0,
2906 htlc_minimum_msat: 0,
2907 htlc_maximum_msat: OptionalField::Present(100_000),
2909 fee_proportional_millionths: 0,
2910 excess_data: Vec::new()
2912 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2913 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2914 short_channel_id: 7,
2917 cltv_expiry_delta: 0,
2918 htlc_minimum_msat: 0,
2919 htlc_maximum_msat: OptionalField::Present(100_000),
2921 fee_proportional_millionths: 0,
2922 excess_data: Vec::new()
2925 // Path via {node0, node2} is channels {1, 3, 5}.
2926 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2927 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2928 short_channel_id: 1,
2931 cltv_expiry_delta: 0,
2932 htlc_minimum_msat: 0,
2933 htlc_maximum_msat: OptionalField::Present(100_000),
2935 fee_proportional_millionths: 0,
2936 excess_data: Vec::new()
2938 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2939 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2940 short_channel_id: 3,
2943 cltv_expiry_delta: 0,
2944 htlc_minimum_msat: 0,
2945 htlc_maximum_msat: OptionalField::Present(100_000),
2947 fee_proportional_millionths: 0,
2948 excess_data: Vec::new()
2951 // Capacity of 200 sats because this channel will be used by 3rd path as well.
2952 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
2953 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2954 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2955 short_channel_id: 5,
2958 cltv_expiry_delta: 0,
2959 htlc_minimum_msat: 0,
2960 htlc_maximum_msat: OptionalField::Present(200_000),
2962 fee_proportional_millionths: 0,
2963 excess_data: Vec::new()
2966 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
2967 // Add 100 sats to the capacities of {12, 13}, because these channels
2968 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
2969 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2970 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2971 short_channel_id: 12,
2974 cltv_expiry_delta: 0,
2975 htlc_minimum_msat: 0,
2976 htlc_maximum_msat: OptionalField::Present(200_000),
2978 fee_proportional_millionths: 0,
2979 excess_data: Vec::new()
2981 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2982 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2983 short_channel_id: 13,
2986 cltv_expiry_delta: 0,
2987 htlc_minimum_msat: 0,
2988 htlc_maximum_msat: OptionalField::Present(200_000),
2990 fee_proportional_millionths: 0,
2991 excess_data: Vec::new()
2994 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2995 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2996 short_channel_id: 6,
2999 cltv_expiry_delta: 0,
3000 htlc_minimum_msat: 0,
3001 htlc_maximum_msat: OptionalField::Present(100_000),
3002 fee_base_msat: 1_000,
3003 fee_proportional_millionths: 0,
3004 excess_data: Vec::new()
3006 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3007 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3008 short_channel_id: 11,
3011 cltv_expiry_delta: 0,
3012 htlc_minimum_msat: 0,
3013 htlc_maximum_msat: OptionalField::Present(100_000),
3015 fee_proportional_millionths: 0,
3016 excess_data: Vec::new()
3019 // Path via {node7, node2} is channels {12, 13, 5}.
3020 // We already limited them to 200 sats (they are used twice for 100 sats).
3021 // Nothing to do here.
3024 // Now, attempt to route 180 sats.
3025 // Our algorithm should provide us with these 2 paths.
3026 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3], None, &Vec::new(), 180_000, 42, Arc::clone(&logger)).unwrap();
3027 assert_eq!(route.paths.len(), 2);
3029 let mut total_value_transferred_msat = 0;
3030 let mut total_paid_msat = 0;
3031 for path in &route.paths {
3032 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3033 total_value_transferred_msat += path.last().unwrap().fee_msat;
3035 total_paid_msat += hop.fee_msat;
3038 // If we paid fee, this would be higher.
3039 assert_eq!(total_value_transferred_msat, 180_000);
3040 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3041 assert_eq!(total_fees_paid, 0);
3046 fn fees_on_mpp_route_test() {
3047 // This test makes sure that MPP algorithm properly takes into account
3048 // fees charged on the channels, by making the fees impactful:
3049 // if the fee is not properly accounted for, the behavior is different.
3050 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3051 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3053 // We need a route consisting of 2 paths:
3054 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3055 // We will route 200 sats, Each path will have 100 sats capacity.
3057 // This test is not particularly stable: e.g.,
3058 // there's a way to route via {node0, node2, node4}.
3059 // It works while pathfinding is deterministic, but can be broken otherwise.
3060 // It's fine to ignore this concern for now.
3062 // Disable other potential paths.
3063 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3065 short_channel_id: 2,
3068 cltv_expiry_delta: 0,
3069 htlc_minimum_msat: 0,
3070 htlc_maximum_msat: OptionalField::Present(100_000),
3072 fee_proportional_millionths: 0,
3073 excess_data: Vec::new()
3076 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3077 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3078 short_channel_id: 7,
3081 cltv_expiry_delta: 0,
3082 htlc_minimum_msat: 0,
3083 htlc_maximum_msat: OptionalField::Present(100_000),
3085 fee_proportional_millionths: 0,
3086 excess_data: Vec::new()
3089 // Path via {node0, node2} is channels {1, 3, 5}.
3090 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3092 short_channel_id: 1,
3095 cltv_expiry_delta: 0,
3096 htlc_minimum_msat: 0,
3097 htlc_maximum_msat: OptionalField::Present(100_000),
3099 fee_proportional_millionths: 0,
3100 excess_data: Vec::new()
3102 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3103 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3104 short_channel_id: 3,
3107 cltv_expiry_delta: 0,
3108 htlc_minimum_msat: 0,
3109 htlc_maximum_msat: OptionalField::Present(100_000),
3111 fee_proportional_millionths: 0,
3112 excess_data: Vec::new()
3115 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3116 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3118 short_channel_id: 5,
3121 cltv_expiry_delta: 0,
3122 htlc_minimum_msat: 0,
3123 htlc_maximum_msat: OptionalField::Present(100_000),
3125 fee_proportional_millionths: 0,
3126 excess_data: Vec::new()
3129 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3130 // All channels should be 100 sats capacity. But for the fee experiment,
3131 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3132 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3133 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3134 // so no matter how large are other channels,
3135 // the whole path will be limited by 100 sats with just these 2 conditions:
3136 // - channel 12 capacity is 250 sats
3137 // - fee for channel 6 is 150 sats
3138 // Let's test this by enforcing these 2 conditions and removing other limits.
3139 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3140 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3141 short_channel_id: 12,
3144 cltv_expiry_delta: 0,
3145 htlc_minimum_msat: 0,
3146 htlc_maximum_msat: OptionalField::Present(250_000),
3148 fee_proportional_millionths: 0,
3149 excess_data: Vec::new()
3151 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3152 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3153 short_channel_id: 13,
3156 cltv_expiry_delta: 0,
3157 htlc_minimum_msat: 0,
3158 htlc_maximum_msat: OptionalField::Absent,
3160 fee_proportional_millionths: 0,
3161 excess_data: Vec::new()
3164 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3165 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3166 short_channel_id: 6,
3169 cltv_expiry_delta: 0,
3170 htlc_minimum_msat: 0,
3171 htlc_maximum_msat: OptionalField::Absent,
3172 fee_base_msat: 150_000,
3173 fee_proportional_millionths: 0,
3174 excess_data: Vec::new()
3176 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3177 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3178 short_channel_id: 11,
3181 cltv_expiry_delta: 0,
3182 htlc_minimum_msat: 0,
3183 htlc_maximum_msat: OptionalField::Absent,
3185 fee_proportional_millionths: 0,
3186 excess_data: Vec::new()
3190 // Attempt to route more than available results in a failure.
3191 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3], None, &Vec::new(), 210_000, 42, Arc::clone(&logger)) {
3192 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3193 } else { panic!(); }
3197 // Now, attempt to route 200 sats (exact amount we can route).
3198 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3], None, &Vec::new(), 200_000, 42, Arc::clone(&logger)).unwrap();
3199 assert_eq!(route.paths.len(), 2);
3201 let mut total_amount_paid_msat = 0;
3202 for path in &route.paths {
3203 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3204 total_amount_paid_msat += path.last().unwrap().fee_msat;
3206 assert_eq!(total_amount_paid_msat, 200_000);
3212 fn drop_lowest_channel_mpp_route_test() {
3213 // This test checks that low-capacity channel is dropped when after
3214 // path finding we realize that we found more capacity than we need.
3215 let (secp_ctx, net_graph_msg_handler, _, logger) = build_graph();
3216 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3218 // We need a route consisting of 3 paths:
3219 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3221 // The first and the second paths should be sufficient, but the third should be
3222 // cheaper, so that we select it but drop later.
3224 // First, we set limits on these (previously unlimited) channels.
3225 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
3227 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
3228 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3229 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3230 short_channel_id: 1,
3233 cltv_expiry_delta: 0,
3234 htlc_minimum_msat: 0,
3235 htlc_maximum_msat: OptionalField::Present(100_000),
3237 fee_proportional_millionths: 0,
3238 excess_data: Vec::new()
3240 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3241 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3242 short_channel_id: 3,
3245 cltv_expiry_delta: 0,
3246 htlc_minimum_msat: 0,
3247 htlc_maximum_msat: OptionalField::Present(50_000),
3249 fee_proportional_millionths: 0,
3250 excess_data: Vec::new()
3253 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
3254 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3256 short_channel_id: 12,
3259 cltv_expiry_delta: 0,
3260 htlc_minimum_msat: 0,
3261 htlc_maximum_msat: OptionalField::Present(60_000),
3263 fee_proportional_millionths: 0,
3264 excess_data: Vec::new()
3266 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3267 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3268 short_channel_id: 13,
3271 cltv_expiry_delta: 0,
3272 htlc_minimum_msat: 0,
3273 htlc_maximum_msat: OptionalField::Present(60_000),
3275 fee_proportional_millionths: 0,
3276 excess_data: Vec::new()
3279 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
3280 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3281 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3282 short_channel_id: 2,
3285 cltv_expiry_delta: 0,
3286 htlc_minimum_msat: 0,
3287 htlc_maximum_msat: OptionalField::Present(20_000),
3289 fee_proportional_millionths: 0,
3290 excess_data: Vec::new()
3292 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3293 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3294 short_channel_id: 4,
3297 cltv_expiry_delta: 0,
3298 htlc_minimum_msat: 0,
3299 htlc_maximum_msat: OptionalField::Present(20_000),
3301 fee_proportional_millionths: 0,
3302 excess_data: Vec::new()
3306 // Attempt to route more than available results in a failure.
3307 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 150_000, 42, Arc::clone(&logger)) {
3308 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3309 } else { panic!(); }
3313 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
3314 // Our algorithm should provide us with these 3 paths.
3315 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 125_000, 42, Arc::clone(&logger)).unwrap();
3316 assert_eq!(route.paths.len(), 3);
3317 let mut total_amount_paid_msat = 0;
3318 for path in &route.paths {
3319 assert_eq!(path.len(), 2);
3320 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3321 total_amount_paid_msat += path.last().unwrap().fee_msat;
3323 assert_eq!(total_amount_paid_msat, 125_000);
3327 // Attempt to route without the last small cheap channel
3328 let route = get_route(&our_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2], None, &Vec::new(), 90_000, 42, Arc::clone(&logger)).unwrap();
3329 assert_eq!(route.paths.len(), 2);
3330 let mut total_amount_paid_msat = 0;
3331 for path in &route.paths {
3332 assert_eq!(path.len(), 2);
3333 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3334 total_amount_paid_msat += path.last().unwrap().fee_msat;
3336 assert_eq!(total_amount_paid_msat, 90_000);
3342 #[cfg(all(test, feature = "unstable"))]
3345 use util::logger::{Logger, Record};
3350 struct DummyLogger {}
3351 impl Logger for DummyLogger {
3352 fn log(&self, _record: &Record) {}
3356 fn generate_routes(bench: &mut Bencher) {
3357 let mut d = File::open("net_graph-2021-02-12.bin").expect("Please fetch https://bitcoin.ninja/ldk-net_graph-879e309c128-2020-02-12.bin and place it at lightning/net_graph-2021-02-12.bin");
3358 let graph = NetworkGraph::read(&mut d).unwrap();
3360 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
3361 let mut path_endpoints = Vec::new();
3362 let mut seed: usize = 0xdeadbeef;
3363 'load_endpoints: for _ in 0..100 {
3366 let src = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3368 let dst = graph.get_nodes().keys().skip(seed % graph.get_nodes().len()).next().unwrap();
3369 let amt = seed as u64 % 1_000_000;
3370 if get_route(src, &graph, dst, None, &[], amt, 42, &DummyLogger{}).is_ok() {
3371 path_endpoints.push((src, dst, amt));
3372 continue 'load_endpoints;
3377 // ...then benchmark finding paths between the nodes we learned.
3380 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
3381 assert!(get_route(src, &graph, dst, None, &[], amt, 42, &DummyLogger{}).is_ok());